~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): receiver-aware attribute ban in check-sensitive-logging hook (#4998)
LearningCircuitd89ef6b85273
diff --git a/.pre-commit-hooks/check-sensitive-logging.py b/.pre-commit-hooks/check-sensitive-logging.pyindex 8f2dbc0c1e..392d9b8b83 100755--- a/.pre-commit-hooks/check-sensitive-logging.py+++ b/.pre-commit-hooks/check-sensitive-logging.py@@ -10,7 +10,9 @@ wraps user-facing exceptions should omit ``from e`` to break the chain."""import ast+import bisectimport io+import reimport sysimport tokenizefrom pathlib import Path@@ -262,6 +264,255 @@ BANNED_DYNAMIC_IMPORTS = {"loguru", "traceback"}# still production-visible and must pass the exception-variable check.WRAPPER_CHAIN_METHODS = {"bind"}+# ``.patch`` on these bare module names is a genuine HTTP-client PATCH call+# (``requests.patch(url, ...)``, ``httpx.patch(url, ...)``), not a logger —+# the concrete false positive #4976 named. This is deliberately the ONLY+# escape hatch from the fail-closed ``opt``/``catch``/``patch`` ban. It is+# a whole-file DENYLIST of in-file spellings plus a few structural+# conditions — not a model of execution order and not a proof that the+# name is the real module. A receiver is exempted only when:+#+# 1. its bare name is one of these, bound by a genuine top-level,+# unaliased ``import requests``/``import httpx``;+# 2. that import appears textually before every reference to the name+# and before every ``def``/``lambda``/``class`` whose body references+# it (a function defined earlier could run before the import);+# 3. nothing else in the file binds, deletes or shadows that name (any+# assignment/augmented/annotated target, ``del``, walrus, loop/+# comprehension/``with``/``except`` target, parameter, ``def``/+# ``class``, type parameter, ``match`` capture, other or star+# import);+# 4. the reference is not evaluated in any ``class`` scope (a class+# body, outside the bodies of the functions defined in it), and no+# ``class`` in the file passes keywords (``metaclass=``, or any+# keyword a metaclass ``__prepare__`` could turn into a namespace);+# 5. the file contains none of the spellings in+# ``_NAMESPACE_VOCABULARY`` (as a name, attribute, imported name or+# identifier token inside a string/bytes literal), no import of a+# ``_NAMESPACE_MODULES`` module, no ``getattr`` other than a direct+# call with a literal attribute name, no direct top-level ``def+# __getattr__`` (one nested in ``if``/``try``, or an assignment to+# the name, is not matched), no write/delete of a dunder attribute+# (``x.__class__ = ...``), and no attribute write to a+# ``.requests``/``.httpx``/``.patch`` attribute or rooted at an+# exempted name (``requests.x = ...``);+# 6. the bare ``requests``/``httpx`` name is never used as a value —+# every load of it is the receiver of an attribute access. Passing+# the module object anywhere (``f(requests)``, ``x = requests``,+# ``[requests]``, ``return requests``) lets code this rule cannot+# follow mutate it, e.g. ``functools.update_wrapper(requests,+# logger, assigned=("patch",))`` copies the logger's ``patch`` onto+# the module.+#+# Any one failure turns the exemption off and the ``.patch`` is banned as+# on every other receiver, so a mistake here can only drop a finding for+# a spelling these lists do not name — never add one main would not emit.+# The rule sees only this file: it cannot see code in other modules+# (another module writing this one's globals or ``sys.modules``), a+# shadowing ``requests.py``/``httpx.py`` on ``sys.path``, or a+# namespace-reaching API these lists do not name (for example an+# unlisted library that resolves a computed dotted name or deserialises+# an external payload). ``.opt``/``.catch`` have no such concrete,+# nameable false positive and stay fully receiver-blind — see+# ``visit_Attribute``.+SAFE_PATCH_RECEIVER_MODULES = {"requests", "httpx"}++# Spellings that can reach a module namespace or module object (or run+# code that can) without a binding statement. One occurrence anywhere+# in a file — as a name, an attribute, an imported name or an+# identifier token inside a string/bytes literal (a dotted-name+# resolver, format field or code string spells it there) — revokes+# the requests/httpx ``.patch`` exemption for the whole file. This can+# never add a finding main would not emit: main bans every ``.patch``.+_NAMESPACE_VOCABULARY = frozenset(+ {+ # builtins that return, write or execute into a namespace+ "globals",+ "locals",+ "vars",+ "setattr",+ "delattr",+ "exec",+ "eval",+ "compile",+ "__import__",+ "__builtins__",+ "builtins",+ "operator",+ "inspect",+ "importlib",+ "ChainMap",+ # a module table, import hooks, namespace-holding attributes and+ # the raw writers behind setattr/item assignment+ "modules",+ "meta_path",+ "path_hooks",+ "path_importer_cache",+ "__dict__",+ "__globals__",+ "__code__",+ "f_globals",+ "f_locals",+ # frame and code-object routes to a namespace (a frame's+ # builtins/globals, the caller chain, a traceback's or+ # generator's/coroutine's frame)+ "f_builtins",+ "_getframe",+ "f_back",+ "f_code",+ "tb_frame",+ "gi_frame",+ "cr_frame",+ "ag_frame",+ "gi_code",+ "cr_code",+ "ag_code",+ # module re-execution and class/type machinery (a module's spec+ # or loader, an object's class swap, a metaclass namespace)+ "__spec__",+ "__loader__",+ "__class__",+ "__bases__",+ "__mro__",+ "__subclasses__",+ "__prepare__",+ "__missing__",+ "__setattr__",+ "__setitem__",+ "__delattr__",+ "__getattribute__",+ }+)+# Modules whose import alone revokes the exemption: each can reach a+# live namespace, frame or object graph (gc, ctypes), resolve a dotted+# name or format field to a live object (logging.config, pkgutil,+# pydoc, string.Formatter), run a code string (runpy ... doctest),+# patch a module attribute (unittest.mock, mock), or resolve globals by+# name while deserialising. Matched against import statements only+# (the dotted path or its first component) — without an import in this+# file (or ``__import__``/``importlib``, which are vocabulary above)+# the name is just a local.+_NAMESPACE_MODULES = frozenset(+ {+ "gc",+ "logging.config",+ "pkgutil",+ "pydoc",+ "string",+ "mock",+ "ctypes",+ "runpy",+ "code",+ "codeop",+ "pdb",+ "bdb",+ "cProfile",+ "profile",+ "timeit",+ "trace",+ "doctest",+ "unittest",+ "pickle",+ "_pickle",+ "copyreg",+ "marshal",+ "shelve",+ "dill",+ "cloudpickle",+ "jsonpickle",+ "yaml",+ }+)+# Identifier tokens inside string/bytes literals (see+# _NAMESPACE_VOCABULARY).+_IDENTIFIER_TOKEN = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")++_NAME_DOMAIN_BASELINES = {+ "getattr": frozenset({"getattr"}),+ "builtins": frozenset(),+}+# Attribute spelling of each builtin-function domain on the builtins+# module itself: ``builtins.getattr``.+_BUILTIN_FN_LEAF = {+ "getattr": "getattr",+}+# Statement fields whose bindings are not guaranteed to execute — or+# to execute in textual order — relative to code that follows the+# construct. A binding under one of these fields can only ADD an alias,+# never clear one. This only governs ALIAS names (``ga = getattr``): a+# tracked builtin's own bare name is never retired by any binding (see+# ``_name_may``). A mistake here can only drop a ``getattr``-alias+# finding (main has none); the requests/httpx ``.patch`` exemption does+# not consult these timelines. Every field that may not run, or may run+# out of textual order, belongs here.+#+# * conditional branches, loop bodies/targets, match cases,+# short-circuit operands, comprehension filters/elements;+# * a ``with``/``async with`` *item* and *body*: an earlier item+# such as ``contextlib.suppress`` can swallow an exception raised+# while a later item is evaluated or entered, skipping that item's+# ``as`` target and the whole body; and a context manager can+# swallow an exception raised partway through the body;+# * an ``assert``'s *test*/*msg* (both are stripped under ``-O``);+# * an assignment's *target* (Assign/AnnAssign): a walrus nested in+# a subscript target runs AFTER the right-hand side, so ordering it+# at its textual position would let it clear an alias the RHS still+# reads (an AugAssign target is evaluated before its RHS, so it+# stays ordered);+# * a For/AsyncFor/comprehension *target*: rebound per iteration,+# never if the iterable is empty;+# * every annotation (AnnAssign/parameter/return) and PEP 695 type+# parameter or ``type`` alias value: purely conservative. A walrus+# is a SyntaxError wherever these are evaluated lazily (PEP 695+# bounds and ``type`` values always; annotations under+# ``from __future__ import annotations`` or on 3.14+), and where an+# annotation still runs eagerly it runs in order — treating it as+# conditional only keeps an alias alive, so it can add a finding,+# never drop one.+#+# Everything else (an If/While *test*, a For *iter*, a Try+# *finalbody*, a Match *subject*, and a comprehension's *first*+# generator *iter*) evaluates unconditionally and in order.+_CONDITIONAL_CHILD_FIELDS = {+ ast.If: frozenset({"body", "orelse"}),+ ast.While: frozenset({"body", "orelse"}),+ ast.For: frozenset({"target", "body", "orelse"}),+ ast.AsyncFor: frozenset({"target", "body", "orelse"}),+ ast.Try: frozenset({"body", "handlers", "orelse"}),+ ast.Match: frozenset({"cases"}),+ ast.With: frozenset({"items", "body"}),+ ast.AsyncWith: frozenset({"items", "body"}),+ ast.Assert: frozenset({"test", "msg"}),+ ast.Assign: frozenset({"targets"}),+ ast.AnnAssign: frozenset({"target", "annotation"}),+ ast.arg: frozenset({"annotation"}),+ ast.comprehension: frozenset({"target", "ifs"}),+ ast.ListComp: frozenset({"elt"}),+ ast.SetComp: frozenset({"elt"}),+ ast.GeneratorExp: frozenset({"elt"}),+ ast.DictComp: frozenset({"key", "value"}),+ ast.BoolOp: frozenset({"values"}),+ ast.IfExp: frozenset({"body", "orelse"}),+}+# ``ast.TryStar`` (PEP 654 ``except*``) only exists on Python 3.11+.+# This hook runs as a pre-commit ``language: script`` — no isolated+# venv — so it imports under whatever system Python is on PATH; a bare+# ``ast.TryStar`` reference above would raise ``AttributeError`` at+# import time on 3.10. Guard it and only add the entry when present;+# no behaviour change on 3.11+, where it is identical to ``ast.Try``.+_TRY_STAR = getattr(ast, "TryStar", None)+if _TRY_STAR is not None:+ _CONDITIONAL_CHILD_FIELDS[_TRY_STAR] = frozenset(+ {"body", "handlers", "orelse"}+ )+# Same 3.10 guard for PEP 695 ``type X = ...`` (3.12+).+_TYPE_ALIAS = getattr(ast, "TypeAlias", None)+if _TYPE_ALIAS is not None:+ _CONDITIONAL_CHILD_FIELDS[_TYPE_ALIAS] = frozenset({"type_params", "value"})+++_DELETED_BINDING = object()+class SensitiveLoggingChecker(ast.NodeVisitor):"""AST visitor to detect sensitive data in logging statements."""@@ -323,6 +574,1132 @@ class SensitiveLoggingChecker(ast.NodeVisitor):# local_deep_research package root so the leading-dot count matches# the file's actual position in the tree.self.wrapper_import_hint = self._compute_wrapper_import_hint()+ # Populated by _prescan_safe_patch_receivers() the first time+ # visit() sees the module root — see SAFE_PATCH_RECEIVER_MODULES.+ self._safe_patch_receiver_names: set = set()+ # Populated by _prescan_getattr_binding_state() — see+ # _NAME_DOMAIN_BASELINES. Flattened module-level final state,+ # consumed by the source-census tests; enforcement uses the+ # position/scope-aware timelines below.+ self._getattr_names = {"getattr"}+ # Name binding events indexed per (domain, name, scope) as sorted+ # positions plus the running replay state after each event, so+ # a lookup is a bisection instead of a replay of the whole+ # timeline (see _record_name_event / _name_may).+ self._scope_timelines: dict = {+ domain: {} for domain in _NAME_DOMAIN_BASELINES+ }+ # Attribute-held aliases (``h.ga = getattr``), keyed by the+ # unparsed receiver expression plus attribute name so one+ # receiver's rebind cannot erase another receiver's alias, and+ # indexed per scope like the name events (see+ # _record_attr_event / _attr_may_be).+ self._attribute_timelines: dict = {+ domain: {} for domain in _NAME_DOMAIN_BASELINES+ }+ # Lexical (node id, kind) scope stack mirroring the prescan's+ # scope paths at query time.+ self._lex_scopes: List[tuple] = []+ # Definition position of every lexical scope the prescan+ # created, bounding which enclosing-scope bindings a nested+ # query is guaranteed to see.+ self._scope_def_pos: dict = {}+ # First namespace-vocabulary hit that revoked the requests/httpx+ # exemption, as (line, spelling), for the diagnostic.+ self._patch_exemption_revoked_by: Optional[tuple] = None+ # Per-name revocations (a reference before the qualifying+ # import), as {name: (line, description)}.+ self._patch_exemption_revoked_for: dict = {}+ # ids of Name nodes evaluated in a class scope: never exempted+ # (see _prescan_safe_patch_receivers).+ self._class_body_name_ids: set = set()+ self._prescanned = False++ def visit(self, node):+ if not self._prescanned and isinstance(node, ast.Module):+ self._prescanned = True+ if self.in_secure_dir:+ self._prescan_getattr_binding_state(node)+ self._prescan_safe_patch_receivers(node)+ return super().visit(node)++ def _prescan_safe_patch_receivers(self, tree: ast.Module) -> None:+ """Whole-file denylist check that a bare name is not a logger.++ Only a name that (a) is genuinely bound by a top-level unaliased+ ``import requests``/``import httpx`` that textually precedes+ every reference to it and every ``def``/``lambda``/``class``+ whose body references it, (b) is never bound by any other form+ anywhere in the file, in a file that (c) contains no spelling+ flagged by ``_namespace_vocabulary_hit`` qualifies — and even+ then never where it is evaluated in a ``class`` scope. See+ SAFE_PATCH_RECEIVER_MODULES. Nothing here models execution+ order: one occurrence anywhere, reachable or not, revokes.+ """+ import_positions: dict = {}+ qualifying_alias_ids = set()+ for stmt in tree.body:+ if isinstance(stmt, ast.Import):+ for alias in stmt.names:+ if (+ alias.name in SAFE_PATCH_RECEIVER_MODULES+ and alias.asname is None+ ):+ import_positions.setdefault(+ alias.name, (stmt.lineno, stmt.col_offset)+ )+ qualifying_alias_ids.add(id(alias))+ if not import_positions:+ return+ # A name looked up in a class body resolves through the class+ # namespace first, which a metaclass ``__prepare__`` (or a+ # ``__missing__`` on the mapping it returns) controls — possibly+ # one inherited from a base class defined in another module — so+ # a reference evaluated in any class scope is never exempted.+ # Only the bodies of functions defined there (``def``/``lambda``)+ # are skipped: they look names up in the module globals, never+ # in the class namespace. Their decorators, defaults and+ # annotations run in the class scope and stay covered.+ for node in ast.walk(tree):+ if isinstance(node, ast.ClassDef):+ stack = list(node.body)+ while stack:+ inner = stack.pop()+ if isinstance(inner, ast.Name):+ self._class_body_name_ids.add(id(inner))+ if isinstance(+ inner, (ast.FunctionDef, ast.AsyncFunctionDef)+ ):+ stack.extend(inner.decorator_list)+ stack.append(inner.args)+ if inner.returns is not None:+ stack.append(inner.returns)+ stack.extend(getattr(inner, "type_params", ()))+ elif isinstance(inner, ast.Lambda):+ stack.append(inner.args)+ else:+ stack.extend(ast.iter_child_nodes(inner))+ hit = self._namespace_vocabulary_hit(tree)+ if hit is not None:+ self._patch_exemption_revoked_by = hit+ return+ rebound_names = set()+ for node in ast.walk(tree):+ self._collect_bound_names(node, qualifying_alias_ids, rebound_names)+ early = self._references_before_import(tree, import_positions)+ self._patch_exemption_revoked_for.update(early)+ self._safe_patch_receiver_names = (+ set(import_positions) - rebound_names - set(early)+ )++ @staticmethod+ def _references_before_import(+ tree: ast.Module, import_positions: dict+ ) -> dict:+ """Names referenced textually before their qualifying import.++ Maps each such name to ``(line, description)`` of the earliest+ offending reference, or ``def``/``lambda``/``class`` that starts+ before the import and references the name in its body.+ """+ early: dict = {}+ for node in ast.walk(tree):+ if isinstance(node, ast.Name):+ names = {node.id} & set(import_positions)+ start = (node.lineno, node.col_offset)+ what = f"a reference to {node.id}"+ elif isinstance(+ node,+ (+ ast.FunctionDef,+ ast.AsyncFunctionDef,+ ast.Lambda,+ ast.ClassDef,+ ),+ ):+ start = min(+ [(node.lineno, node.col_offset)]+ + [+ (dec.lineno, dec.col_offset)+ for dec in getattr(node, "decorator_list", ())+ ]+ )+ if not any(start < pos for pos in import_positions.values()):+ continue+ names = {+ inner.id+ for inner in ast.walk(node)+ if isinstance(inner, ast.Name)+ and inner.id in import_positions+ }+ what = f"a {type(node).__name__} that uses it"+ else:+ continue+ for name in names:+ if start < import_positions[name]:+ found = (start[0], f"{what} before import {name}")+ if name not in early or found < early[name]:+ early[name] = found+ return early++ @staticmethod+ def _namespace_vocabulary_hit(tree: ast.Module) -> Optional[tuple]:+ """Earliest spelling that can rebind a module global out of band.++ Returns ``(line, description)`` for the first-by-line name,+ attribute, imported name or identifier token inside a string/+ bytes literal that is in _NAMESPACE_VOCABULARY; import of a+ _NAMESPACE_MODULES module; ``getattr`` spelling other than a+ direct call with a literal attribute name; attribute write+ that targets a ``requests``/``httpx``/``patch`` attribute, a+ dunder attribute, or is rooted at a ``requests``/``httpx`` name;+ a load of a bare ``requests``/``httpx`` name that is not the+ receiver of an attribute access (the module object used as a+ value); an ``import requests``/``import httpx`` under another+ name, or a ``from ... import requests``/``httpx``, at any scope;+ ``class`` with keywords (``metaclass=`` or any other); or a+ direct top-level ``def __getattr__`` (not one nested in+ ``if``/``try``, and not an assignment to the name). ``None``+ when clean.+ """+ literal_getattr_funcs = {+ id(node.func)+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and len(node.args) >= 2+ and not any(isinstance(arg, ast.Starred) for arg in node.args)+ and isinstance(node.args[1], ast.Constant)+ and isinstance(node.args[1].value, str)+ }+ attribute_receiver_ids = {+ id(node.value)+ for node in ast.walk(tree)+ if isinstance(node, ast.Attribute)+ }+ hits = [+ (stmt.lineno, "a module-level def __getattr__")+ for stmt in tree.body+ if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef))+ and stmt.name == "__getattr__"+ ]+ for node in ast.walk(tree):+ line = getattr(node, "lineno", 0)+ if isinstance(node, ast.ClassDef):+ if node.keywords:+ hits.append((line, f"keywords on class {node.name}"))+ continue+ if isinstance(node, ast.Name):+ spelling = node.id+ if (+ spelling in SAFE_PATCH_RECEIVER_MODULES+ and isinstance(node.ctx, ast.Load)+ and id(node) not in attribute_receiver_ids+ ):+ hits.append((line, f"{spelling} used as a value"))+ elif isinstance(node, ast.Attribute):+ spelling = node.attr+ if isinstance(node.ctx, (ast.Store, ast.Del)):+ root = node.value+ while isinstance(root, (ast.Attribute, ast.Subscript)):+ root = root.value+ if (+ node.attr in SAFE_PATCH_RECEIVER_MODULES+ or node.attr == "patch"+ or (+ len(node.attr) > 4+ and node.attr.startswith("__")+ and node.attr.endswith("__")+ )+ or (+ isinstance(root, ast.Name)+ and root.id in SAFE_PATCH_RECEIVER_MODULES+ )+ ):+ hits.append((line, f"a write to .{node.attr}"))+ elif isinstance(node, ast.Constant) and isinstance(+ node.value, (str, bytes)+ ):+ text = (+ node.value.decode("latin-1")+ if isinstance(node.value, bytes)+ else node.value+ )+ found = sorted(+ set(_IDENTIFIER_TOKEN.findall(text)) & _NAMESPACE_VOCABULARY+ )+ if found:+ hits.append((line, f"{found[0]!r} in a string literal"))+ continue+ elif isinstance(node, (ast.Import, ast.ImportFrom)):+ for alias in node.names:+ if isinstance(node, ast.ImportFrom):+ base = node.module or ""+ modules = [base, f"{base}.{alias.name}".strip(".")]+ else:+ modules = [alias.name]+ words = {+ part for module in modules for part in module.split(".")+ }+ words.update({alias.name, alias.asname})+ if (words & _NAMESPACE_VOCABULARY) or any(+ module in _NAMESPACE_MODULES+ or module.split(".")[0] in _NAMESPACE_MODULES+ for module in modules+ ):+ hits.append((line, f"an import of {modules[-1]}"))+ # A second binding of requests/httpx under another+ # name (``import requests as rq``, at any scope) can+ # be handed to code this rule cannot follow without+ # the bare name ever being used as a value. Revoke+ # the exemption rather than track every alias.+ if (+ isinstance(node, ast.Import)+ and alias.name.split(".")[0]+ in SAFE_PATCH_RECEIVER_MODULES+ and alias.asname not in (None, alias.name)+ ):+ hits.append(+ (line, f"{alias.name} imported as {alias.asname}")+ )+ elif (+ isinstance(node, ast.ImportFrom)+ and alias.name in SAFE_PATCH_RECEIVER_MODULES+ ):+ # ``from x import requests [as y]`` binds some+ # object as (or instead of) the module.+ hits.append(+ (line, f"{alias.name} imported from {base or '.'}")+ )+ continue+ else:+ continue+ if spelling in _NAMESPACE_VOCABULARY:+ hits.append((line, spelling))+ elif spelling == "getattr" and id(node) not in (+ literal_getattr_funcs+ ):+ hits.append((line, "a computed getattr"))+ return min(hits) if hits else None++ def _prescan_getattr_binding_state(self, tree: ast.Module) -> None:+ """Build position/scope-aware state for tracked builtin names.++ The earlier monotonic alias set marked a name forever, so a+ definite rebind or parameter shadow still produced a diagnostic.+ This records every binding on a timeline instead. A binding is+ ``may`` when its value is a direct or module-qualified spelling+ of ``getattr`` (a ``getattr`` alias, ``builtins.getattr``), a+ statically knowable alias, or a conditional containing one.+ Other definitely executed bindings clear an ALIAS; they never+ clear the bare ``getattr`` itself (see ``_name_may``).+ ``global``/``nonlocal`` declarations remap each write to the+ scope Python actually mutates, and attribute-held aliases are+ keyed by receiver so one receiver's rebind cannot erase+ another's. These timelines only ever ADD ``getattr(...)``+ diagnostics; the requests/httpx ``.patch`` exemption does not+ consult them.+ """+ pending = []+ pending_attrs = []+ scope_decls: dict = {}+ scope_locals: dict = {}++ def local_bindings(scope_node):+ names = (+ set(self._func_param_names(scope_node.args))+ if hasattr(scope_node, "args")+ else set()+ )+ stack = list(ast.iter_child_nodes(scope_node))+ while stack:+ child = stack.pop()+ if isinstance(+ child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)+ ):+ names.add(child.name)+ continue+ if isinstance(child, ast.Lambda):+ continue+ if isinstance(child, ast.Name) and isinstance(+ child.ctx, (ast.Store, ast.Del)+ ):+ names.add(child.id)+ elif isinstance(child, (ast.Import, ast.ImportFrom)):+ names.update(+ alias.asname or alias.name.split(".")[0]+ for alias in child.names+ )+ elif isinstance(child, ast.ExceptHandler) and child.name:+ names.add(child.name)+ elif (+ isinstance(child, (ast.MatchAs, ast.MatchStar))+ and child.name+ ):+ names.add(child.name)+ elif isinstance(child, ast.MatchMapping) and child.rest:+ names.add(child.rest)+ stack.extend(ast.iter_child_nodes(child))+ global_names, nonlocal_names = scope_declarations(scope_node)+ return names - global_names - nonlocal_names++ def scope_declarations(scope_node):+ """global/nonlocal names declared in this exact scope."""+ globals_seen = set()+ nonlocals_seen = set()+ stack = list(ast.iter_child_nodes(scope_node))+ while stack:+ child = stack.pop()+ if isinstance(+ child,+ (+ ast.FunctionDef,+ ast.AsyncFunctionDef,+ ast.Lambda,+ ast.ClassDef,+ ),+ ):+ continue+ if isinstance(child, ast.Global):+ globals_seen.update(child.names)+ elif isinstance(child, ast.Nonlocal):+ nonlocals_seen.update(child.names)+ stack.extend(ast.iter_child_nodes(child))+ return globals_seen, nonlocals_seen++ def binding_scope(path, name):+ """Lexical scope a binding of ``name`` at ``path`` lands in."""+ if not path:+ return path+ globals_seen, nonlocals_seen = scope_decls.get(path, ((), ()))+ if name in globals_seen:+ return ()+ if name in nonlocals_seen:+ for depth in range(len(path) - 1, 0, -1):+ candidate = path[:depth]+ if path[depth - 1][+ 1+ ] == "function" and name in scope_locals.get(candidate, ()):+ return candidate+ return path++ def record(name, value, pos, path, definite=True, value_path=None):+ target_path = binding_scope(path, name)+ # A function body's outer write may never run. In particular,+ # its clear cannot retire a builtin at module definition time.+ definite = definite and target_path == path+ for domain in _NAME_DOMAIN_BASELINES:+ pending.append(+ (+ pos,+ domain,+ name,+ value,+ target_path,+ definite,+ path if value_path is None else value_path,+ )+ )++ def record_target(target, value, path, definite=True, pos=None):+ # Assignment evaluates the RHS before any target is bound.+ if pos is None:+ pos = (target.end_lineno, target.end_col_offset)+ if isinstance(target, ast.Name):+ record(+ target.id,+ value,+ pos,+ path,+ definite,+ )+ elif isinstance(target, (ast.Tuple, ast.List)):+ if (+ isinstance(value, (ast.Tuple, ast.List))+ and len(value.elts) == len(target.elts)+ and not any(+ isinstance(element, ast.Starred)+ for element in value.elts+ )+ ):+ for element, element_value in zip(target.elts, value.elts):+ record_target(+ element, element_value, path, definite, pos+ )+ else:+ for element in target.elts:+ record_target(element, value, path, definite, pos)+ elif isinstance(target, ast.Starred):+ record_target(target.value, value, path, definite, pos)+ elif isinstance(target, ast.Attribute):+ pending_attrs.append(+ (+ pos,+ (ast.unparse(target.value), target.attr),+ value,+ path,+ definite,+ )+ )++ def record_params(args, path):+ positional = list(args.posonlyargs) + list(args.args)+ first_default = len(positional) - len(args.defaults)+ for index, arg in enumerate(positional):+ default = (+ args.defaults[index - first_default]+ if index >= first_default+ else None+ )+ record(+ arg.arg,+ default if default is not None else False,+ (args.end_lineno, args.end_col_offset)+ if hasattr(args, "end_lineno")+ else (arg.lineno, arg.col_offset),+ path,+ value_path=path[:-1],+ )+ for arg, default in zip(args.kwonlyargs, args.kw_defaults):+ record(+ arg.arg,+ default if default is not None else False,+ (args.end_lineno, args.end_col_offset)+ if hasattr(args, "end_lineno")+ else (arg.lineno, arg.col_offset),+ path,+ value_path=path[:-1],+ )+ for arg in (args.vararg, args.kwarg):+ if arg is not None:+ record(+ arg.arg,+ False,+ (arg.lineno, arg.col_offset),+ path,+ )++ def walk(node, path, definite=True):+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ record(+ node.name,+ False,+ (node.end_lineno, node.end_col_offset),+ path,+ definite,+ )+ inner = path + ((id(node), "function"),)+ self._scope_def_pos[inner] = (+ node.lineno,+ node.col_offset,+ )+ scope_decls[inner] = scope_declarations(node)+ scope_locals[inner] = local_bindings(node)+ record_params(node.args, inner)+ walk(node.args, path, definite)+ for statement in node.body:+ walk(statement, inner)+ for decorator in node.decorator_list:+ walk(decorator, path, definite)+ # Lazily evaluated (see _CONDITIONAL_CHILD_FIELDS).+ if node.returns is not None:+ walk(node.returns, path, False)+ for type_param in getattr(node, "type_params", ()) or ():+ walk(type_param, path, False)+ return+ if isinstance(node, ast.Lambda):+ inner = path + ((id(node), "function"),)+ self._scope_def_pos[inner] = (+ node.lineno,+ node.col_offset,+ )+ scope_decls[inner] = scope_declarations(node)+ scope_locals[inner] = local_bindings(node)+ record_params(node.args, inner)+ walk(node.args, path, definite)+ walk(node.body, inner)+ return+ if isinstance(node, ast.ClassDef):+ record(+ node.name,+ False,+ (node.end_lineno, node.end_col_offset),+ path,+ definite,+ )+ inner = path + ((id(node), "class"),)+ self._scope_def_pos[inner] = (+ node.lineno,+ node.col_offset,+ )+ scope_decls[inner] = scope_declarations(node)+ scope_locals[inner] = local_bindings(node)+ for decorator in node.decorator_list:+ walk(decorator, path, definite)+ for base in node.bases:+ walk(base, path, definite)+ for keyword in node.keywords:+ walk(keyword, path, definite)+ for statement in node.body:+ walk(statement, inner)+ return+ if isinstance(node, ast.Assign):+ for target in node.targets:+ record_target(+ target,+ node.value,+ path,+ definite,+ (node.end_lineno, node.end_col_offset),+ )+ elif isinstance(node, ast.AnnAssign) and node.value is not None:+ record_target(+ node.target,+ node.value,+ path,+ definite,+ (node.end_lineno, node.end_col_offset),+ )+ elif isinstance(node, ast.AugAssign):+ record_target(+ node.target,+ node.target,+ path,+ definite,+ (node.end_lineno, node.end_col_offset),+ )+ elif isinstance(node, ast.NamedExpr):+ record_target(+ node.target,+ node.value,+ path,+ definite,+ (node.end_lineno, node.end_col_offset),+ )+ elif isinstance(node, (ast.For, ast.AsyncFor)):+ record_target(node.target, False, path, False)+ elif isinstance(node, ast.comprehension):+ record_target(node.target, False, path, False)+ elif isinstance(node, (ast.With, ast.AsyncWith)):+ # Never definite: an earlier item (``suppress``) can+ # swallow the exception that skips this ``as`` target.+ for item in node.items:+ if item.optional_vars is not None:+ record_target(item.optional_vars, False, path, False)+ elif isinstance(node, ast.Delete):+ names = set()+ for target in node.targets:+ self._collect_target_names(target, names)+ for name in names:+ record(+ name,+ _DELETED_BINDING,+ (node.end_lineno, node.end_col_offset),+ path,+ definite,+ )+ elif isinstance(node, (ast.MatchAs, ast.MatchStar)):+ if node.name is not None:+ record(+ node.name,+ False,+ (node.lineno, node.col_offset),+ path,+ False,+ )+ elif isinstance(node, ast.MatchMapping):+ if node.rest is not None:+ record(+ node.rest,+ False,+ (node.lineno, node.col_offset),+ path,+ False,+ )+ elif isinstance(node, ast.ExceptHandler):+ if node.name is not None:+ record(+ node.name,+ False,+ (node.lineno, node.col_offset),+ path,+ False,+ )+ # Python deletes the handler name when the handler+ # ends; in a class body the lookup then falls back+ # to the enclosing (module) binding.+ record(+ node.name,+ _DELETED_BINDING,+ (node.end_lineno, node.end_col_offset),+ path,+ False,+ )+ elif isinstance(node, (ast.Import, ast.ImportFrom)):+ pos = (node.end_lineno, node.end_col_offset)+ for alias in node.names:+ if alias.name == "*":+ continue+ is_import = isinstance(node, ast.Import)+ bound = alias.asname or (+ alias.name.split(".")[0] if is_import else alias.name+ )+ from_builtins = (+ not is_import+ and node.module == "builtins"+ and node.level == 0+ )+ target_path = binding_scope(path, bound)+ for domain in _NAME_DOMAIN_BASELINES:+ may = (+ is_import and alias.name == "builtins"+ if domain == "builtins"+ else from_builtins+ and alias.name == _BUILTIN_FN_LEAF.get(domain)+ )+ pending.append(+ (+ pos,+ domain,+ bound,+ may,+ target_path,+ definite and target_path == path,+ path,+ )+ )+ conditional_fields = _CONDITIONAL_CHILD_FIELDS.get(type(node))+ for field, value in ast.iter_fields(node):+ if isinstance(value, ast.AST):+ children = [value]+ elif (+ isinstance(value, list)+ and value+ and all(isinstance(item, ast.AST) for item in value)+ ):+ children = value+ else:+ continue+ child_definite = definite and not (+ conditional_fields is not None+ and field in conditional_fields+ )+ for child in children:+ walk(child, path, child_definite)++ walk(tree, ())+ # Name and attribute events interleave in position order so an+ # attribute alias established earlier (``h.ga = getattr``) is+ # visible to a name bound from it later (``lookup = h.ga``) and+ # vice versa.+ events = [+ (pos, 0, (domain, key), value, path, definite, path)+ for pos, key, value, path, definite in pending_attrs+ for domain in _NAME_DOMAIN_BASELINES+ ]+ events.extend(+ (pos, 1, (domain, name), value, path, definite, value_path)+ for pos, domain, name, value, path, definite, value_path in pending+ )+ events.sort(key=lambda event: event[0])+ for pos, kind, key, value, path, definite, value_path in events:+ domain = key[0]+ may = (+ value+ if isinstance(value, bool) or value is _DELETED_BINDING+ else self._expr_may_be(+ value,+ domain,+ (value.lineno, value.col_offset),+ value_path,+ )+ )+ if kind == 0:+ self._record_attr_event(+ domain, key[1], pos, may, definite, path+ )+ else:+ self._record_name_event(+ domain, key[1], pos, may, definite, path+ )+ self._getattr_names = {"getattr"} | {+ name+ for name in self._scope_timelines["getattr"]+ if self._name_may(name, "getattr", (10**9, 0), ())+ }++ def _expr_may_be(self, expr, domain: str, pos, path) -> bool:+ """Whether an expression may evaluate to the tracked domain."""+ if isinstance(expr, ast.Name):+ return self._name_may(+ expr.id,+ domain,+ (expr.lineno, expr.col_offset),+ path,+ )+ if isinstance(expr, ast.NamedExpr):+ return self._expr_may_be(expr.value, domain, pos, path)+ if isinstance(expr, ast.IfExp):+ return self._expr_may_be(+ expr.body, domain, pos, path+ ) or self._expr_may_be(expr.orelse, domain, pos, path)+ if isinstance(expr, ast.BoolOp):+ return any(+ self._expr_may_be(value, domain, pos, path)+ for value in expr.values+ )+ if isinstance(expr, ast.Starred):+ return self._expr_may_be(expr.value, domain, pos, path)+ if isinstance(expr, (ast.Tuple, ast.List)):+ return any(+ self._expr_may_be(element, domain, pos, path)+ for element in expr.elts+ )+ leaf = _BUILTIN_FN_LEAF.get(domain)+ if isinstance(expr, ast.Attribute):+ if (+ leaf is not None+ and expr.attr == leaf+ and (+ # ``__import__("builtins").getattr``: a computed+ # receiver cannot be proven not to be builtins.+ not isinstance(expr.value, ast.Name)+ or self._name_may(+ expr.value.id,+ "builtins",+ (expr.value.lineno, expr.value.col_offset),+ path,+ )+ )+ ):+ return True+ return self._attr_may_be(expr, domain, pos, path)+ # Selection out of a container that may hold the builtin+ # (``[getattr][0]``, ``{"k": getattr}["k"]``, ``x[0]`` where+ # ``x = (getattr,)``), or a lookup keyed by the builtin's own+ # name (``vars(builtins)["getattr"]``,+ # ``builtins.__dict__["getattr"]``).+ if isinstance(expr, ast.Subscript):+ if (+ leaf is not None+ and isinstance(expr.slice, ast.Constant)+ and expr.slice.value == leaf+ ):+ return True+ return self._expr_may_be(expr.value, domain, pos, path)+ if isinstance(expr, ast.Dict):+ return any(+ self._expr_may_be(value, domain, pos, path)+ for value in expr.values+ )+ if isinstance(expr, ast.Set):+ return any(+ self._expr_may_be(element, domain, pos, path)+ for element in expr.elts+ )+ if isinstance(expr, ast.Call):+ # ``(lambda: getattr)()`` returns its body.+ if isinstance(expr.func, ast.Lambda):+ return self._expr_may_be(expr.func.body, domain, pos, path)+ # ``getattr(builtins, "getattr")``: a literal lookup of the+ # builtin's own name through a getattr spelling.+ if (+ leaf is not None+ and len(expr.args) >= 2+ and isinstance(expr.args[1], ast.Constant)+ and expr.args[1].value == leaf+ and self._expr_may_be(expr.func, "getattr", pos, path)+ ):+ return True+ return False++ def _name_may(self, name: str, domain: str, pos, path) -> bool:+ """Resolve one name's nearest visible binding at ``pos``.++ The bare ``getattr`` (the baseline member of+ _NAME_DOMAIN_BASELINES) ALWAYS may be that builtin, whatever+ the file binds to it, exactly as on main. Deciding that a+ rebind definitely retired the builtin requires modelling every+ way a binding can fail to run or be undone (a suppressed+ ``with`` item, an ``except ... as`` handler's implicit ``del``,+ a walrus in an assignment target that runs after the RHS, an+ opaque RHS that still yields the builtin); getting any one of+ them wrong silently removed a diagnostic main emits. Timelines+ therefore only ever ADD aliases (``ga = getattr``); they never+ subtract the builtin itself.+ """+ if name in _NAME_DOMAIN_BASELINES[domain]:+ return True+ scopes = self._scope_timelines[domain].get(name)+ if not scopes:+ return False+ cutoff = self._scope_def_pos.get(path)+ for depth in range(len(path), -1, -1):+ scope = path[:depth]+ entry = scopes.get(scope)+ if entry is None or not self._scope_visible(scope, path):+ continue+ positions, states, last_alias_pos = entry+ if depth == len(path):+ # A class-body name that MAY have been deleted (a+ # conditional ``del``, an ``except ... as`` handler's+ # implicit delete) may resolve to the enclosing binding.+ index = bisect.bisect_right(positions, pos)+ if index:+ state, fallthrough = states[index - 1]+ else:+ state = None if scope and scope[-1][1] == "class" else False+ fallthrough = False+ if state is True:+ return True+ if state is None or fallthrough:+ continue+ return state+ # Enclosing scope: the querying scope's body runs no earlier+ # than its own definition, so only bindings established+ # there are guaranteed visible. Later writes count only+ # when they (re)introduce an alias — a later definite clear+ # cannot be relied on at an unknown call time.+ if cutoff is not None:+ index = bisect.bisect_right(positions, cutoff)+ if index and states[index - 1][0] is True:+ return True+ return last_alias_pos is not None and (+ cutoff is None or last_alias_pos > cutoff+ )+ return False++ def _record_name_event(self, domain, name, pos, may, definite, path):+ """Append one binding event to the per-scope replay index.++ Events arrive in position order, so each scope's positions stay+ sorted and ``states[i]`` is the replay state after event ``i``:+ an alias binding sets it, a definite clear or delete resets it+ (a class body resets to "unbound here", falling through to the+ enclosing scope), and a conditional delete in a class body+ marks a possible fall-through.+ """+ entry = self._scope_timelines[domain].setdefault(name, {}).get(path)+ is_class = bool(path and path[-1][1] == "class")+ if entry is None:+ entry = [[], [], None]+ self._scope_timelines[domain][name][path] = entry+ state, fallthrough = (None if is_class else False), False+ else:+ state, fallthrough = entry[1][-1]+ if may is _DELETED_BINDING:+ if definite:+ state = None if is_class else False+ fallthrough = False+ elif is_class:+ fallthrough = True+ elif may:+ state = True+ entry[2] = pos+ elif definite:+ state = False+ fallthrough = False+ entry[0].append(pos)+ entry[1].append((state, fallthrough))++ @staticmethod+ def _scope_visible(event_path, query_path) -> bool:+ """Whether a lexical binding scope is visible at a call site."""+ if len(event_path) > len(query_path):+ return False+ if query_path[: len(event_path)] != event_path:+ return False+ if event_path and event_path[-1][1] == "class":+ return len(event_path) == len(query_path)+ return True++ def _class_body_attr_may(self, attr: str, domain: str = "getattr") -> bool:+ """Whether a class body binds ``attr`` to a getattr alias.++ ``class H: ga = getattr`` puts the alias on every instance,+ and an instance's class cannot be recovered statically, so any+ ``<obj>.ga`` may reach it. A definite same-class rebind retires+ it; a rebind in a different class does not.+ """+ return any(+ scope and scope[-1][1] == "class" and states[-1][0] is True+ for scope, (_, states, _) in self._scope_timelines[domain]+ .get(attr, {})+ .items()+ )++ def _attr_may_be_getattr(self, attr_node: ast.Attribute, pos, path) -> bool:+ return self._attr_may_be(attr_node, "getattr", pos, path)++ def _attr_may_be(+ self, attr_node: ast.Attribute, domain: str, pos, path+ ) -> bool:+ """Resolve an attribute-held alias (``h.ga = getattr``).++ The timeline is keyed by the unparsed receiver expression+ plus attribute name, so another receiver's definite rebind+ cannot erase a live alias. Same-scope writes replay in+ position order; enclosing-scope writes are bounded by the+ querying scope's definition (a later definite clear cannot be+ relied on); and a write in any other function/class scope may+ execute in any order relative to the call, so a ``may`` there+ always sticks.+ """+ attr = attr_node.attr+ if self._class_body_attr_may(attr, domain):+ return True+ index = self._attribute_timelines[domain].get(+ (ast.unparse(attr_node.value), attr)+ )+ if index is None:+ return False+ scopes, alias_scopes = index+ entry = scopes.get(path)+ if entry is not None:+ at = bisect.bisect_right(entry[0], pos)+ if at and entry[1][at - 1] is not None and entry[1][at - 1][1]:+ return True+ cutoff = self._scope_def_pos.get(path)+ latest = None+ for depth in range(len(path)):+ entry = scopes.get(path[:depth])+ if entry is None:+ continue+ positions, decisive, last_alias_pos = entry+ if cutoff is not None:+ at = bisect.bisect_right(positions, cutoff)+ if at and decisive[at - 1] is not None:+ if latest is None or decisive[at - 1][0] > latest[0]:+ latest = decisive[at - 1]+ if last_alias_pos is not None and (+ cutoff is None or last_alias_pos > cutoff+ ):+ return True+ if latest is not None and latest[1]:+ return True+ # Any other scope: execution order relative to the call is+ # unknowable, so only a live alias matters.+ visible = sum(+ path[:depth] in alias_scopes for depth in range(len(path) + 1)+ )+ return len(alias_scopes) > visible++ def _record_attr_event(self, domain, key, pos, may, definite, path):+ """Append one attribute-alias event to the per-scope index.++ Per scope: sorted positions, the last decisive event+ ``(position, is_alias)`` after each event (an alias write or a+ definite clear; a conditional clear decides nothing), and the+ position of the last alias write. ``alias_scopes`` holds every+ scope that ever writes an alias.+ """+ scopes, alias_scopes = self._attribute_timelines[domain].setdefault(+ key, ({}, set())+ )+ entry = scopes.setdefault(path, [[], [], None])+ decisive = entry[1][-1] if entry[1] else None+ if may:+ decisive = (pos, True)+ entry[2] = pos+ alias_scopes.add(path)+ elif definite:+ decisive = (pos, False)+ entry[0].append(pos)+ entry[1].append(decisive)++ @staticmethod+ def _collect_bound_names(+ node: ast.AST, qualifying_alias_ids: set, bound: set+ ) -> None:+ """Record every name ``node`` binds, deletes or shadows.++ ``qualifying_alias_ids`` are the top-level aliases that ESTABLISH+ the exemption, so they alone do not invalidate it. A star import+ binds unknowable names and records every exempted name.+ """+ if isinstance(node, ast.Name):+ if isinstance(node.ctx, (ast.Store, ast.Del)):+ bound.add(node.id)+ elif isinstance(node, ast.arg):+ bound.add(node.arg)+ elif isinstance(+ node,+ (+ ast.FunctionDef,+ ast.AsyncFunctionDef,+ ast.ClassDef,+ ast.ExceptHandler,+ ast.MatchAs,+ ast.MatchStar,+ ),+ ) or type(node).__name__ in ("TypeVar", "ParamSpec", "TypeVarTuple"):+ if node.name is not None:+ bound.add(node.name)+ elif isinstance(node, ast.MatchMapping):+ if node.rest is not None:+ bound.add(node.rest)+ elif isinstance(node, ast.Import):+ for alias in node.names:+ if id(alias) not in qualifying_alias_ids:+ bound.add(alias.asname or alias.name.split(".")[0])+ elif isinstance(node, ast.ImportFrom):+ for alias in node.names:+ if alias.name == "*":+ bound.update(SAFE_PATCH_RECEIVER_MODULES)+ else:+ bound.add(alias.asname or alias.name)++ def _collect_target_names(self, target: ast.AST, names: set) -> None:+ if isinstance(target, ast.Name):+ names.add(target.id)+ elif isinstance(target, (ast.Tuple, ast.List)):+ for elt in target.elts:+ self._collect_target_names(elt, names)+ elif isinstance(target, ast.Starred):+ self._collect_target_names(target.value, names)++ def _is_safe_patch_receiver(self, expr: ast.AST) -> bool:+ """True only for the narrow, denylist-gated ``.patch`` case.++ See SAFE_PATCH_RECEIVER_MODULES: a bare ``requests``/``httpx``+ name, not evaluated in any ``class`` scope, that is imported at top+ level before any reference to it, bound by nothing else in the+ file, in a file with none of the denylisted spellings or+ structures. This is a denylist of in-file spellings plus those+ structural conditions, not a proof: it cannot see other modules+ (which can write this module's globals or ``sys.modules``), a+ shadowing ``requests.py``/``httpx.py`` on ``sys.path``, or a+ namespace-reaching API the lists do not name. It is+ intentionally NOT a general receiver-shape allowlist — anything+ else (attributes, subscripts, calls, parameters, dict/list+ elements, ternaries, aliases) stays banned by default.+ """+ return (+ isinstance(expr, ast.Name)+ and expr.id in self._safe_patch_receiver_names+ and id(expr) not in self._class_body_name_ids+ )++ def _patch_exemption_note(self, expr: ast.AST) -> str:+ """Explain a revoked requests/httpx exemption in the diagnostic."""+ if (+ not isinstance(expr, ast.Name)+ or expr.id not in SAFE_PATCH_RECEIVER_MODULES+ ):+ return ""+ revoked = self._patch_exemption_revoked_by+ if revoked is None:+ revoked = self._patch_exemption_revoked_for.get(expr.id)+ if revoked is not None:+ return (+ f" (the {expr.id}.patch exemption is revoked for this file "+ f"by {revoked[1]} on line {revoked[0]})"+ )+ if id(expr) in self._class_body_name_ids:+ return (+ f" (the {expr.id}.patch exemption never applies inside a "+ f"class body)"+ )+ return ""def _compute_wrapper_import_hint(self) -> str:"""Compute the per-file import hint with the correct dot count.@@ -1101,36 +2478,53 @@ class SensitiveLoggingChecker(ast.NodeVisitor):f"secure-logging dirs — rename the parameter")- def visit_FunctionDef(self, node: ast.FunctionDef) -> None:+ def _visit_function(self, node) -> None:if self.in_secure_dir:self._check_func_params(node)+ # Defaults, annotations and decorators are evaluated outside the+ # function body, before its parameters exist.+ self.visit(node.args)+ for decorator in getattr(node, "decorator_list", ()):+ self.visit(decorator)+ returns = getattr(node, "returns", None)+ if returns is not None:+ self.visit(returns)+ for type_param in getattr(node, "type_params", ()):+ self.visit(type_param)self._push_name_scope(self._func_param_names(node.args), kind="function")- self.generic_visit(node)+ self._lex_scopes.append((id(node), "function"))+ if isinstance(node, ast.Lambda):+ self.visit(node.body)+ else:+ for statement in node.body:+ self.visit(statement)+ self._lex_scopes.pop()self._pop_name_scope()+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:+ self._visit_function(node)+def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:- if self.in_secure_dir:- self._check_func_params(node)- self._push_name_scope(- self._func_param_names(node.args), kind="function"- )- self.generic_visit(node)- self._pop_name_scope()+ self._visit_function(node)def visit_Lambda(self, node: ast.Lambda) -> None:- if self.in_secure_dir:- self._check_func_params(node)- self._push_name_scope(- self._func_param_names(node.args), kind="function"- )- self.generic_visit(node)- self._pop_name_scope()+ self._visit_function(node)def visit_ClassDef(self, node: ast.ClassDef) -> None:+ for expr in [+ *node.decorator_list,+ *node.bases,+ *node.keywords,+ *getattr(node, "type_params", ()),+ ]:+ self.visit(expr)self._push_name_scope(kind="class")- self.generic_visit(node)+ self._lex_scopes.append((id(node), "class"))+ for statement in node.body:+ self.visit(statement)+ self._lex_scopes.pop()self._pop_name_scope()# ------------------------------------------------------------------@@ -1139,20 +2533,33 @@ class SensitiveLoggingChecker(ast.NodeVisitor):def visit_Attribute(self, node: ast.Attribute) -> None:if self.in_secure_dir:- if node.attr in ("opt", "catch"):+ # Fail closed: opt/catch/patch are banned on ANY receiver unless+ # provably not a logger. A receiver is "unknown" (a parameter, an+ # attribute not named logger, a dict/list element, a ternary, an+ # alias chain, ...) far more easily than it is provably safe, so+ # the default must be to block, not to allow. The single narrow,+ # justified exception is ``requests.patch``/``httpx.patch`` — see+ # SAFE_PATCH_RECEIVER_MODULES. ``opt``/``catch`` have no such+ # concrete, nameable false positive and stay fully receiver-blind.+ if node.attr == "patch" and self._is_safe_patch_receiver(+ node.value+ ):+ pass+ elif node.attr == "patch":self.errors.append(f"{self.filename}:{node.lineno}: "- f".{node.attr} is banned in secure-logging dirs — the "- f"secure_logging wrapper delegates it to raw loguru, "- f"reattaching tracebacks ungated; use logger.exception() "- f"with a scrubbed safe_msg"+ f".patch is banned in secure-logging dirs — patchers "+ f'mutate record["exception"] and reattach '+ f"tracebacks ungated; use logger.bind() for metadata"+ f"{self._patch_exemption_note(node.value)}")- elif node.attr == "patch":+ elif node.attr in ("opt", "catch"):self.errors.append(f"{self.filename}:{node.lineno}: "- f".patch is banned in secure-logging dirs — patchers can "- f'mutate record["exception"] and reattach tracebacks '- f"ungated; use logger.bind() for metadata"+ f".{node.attr} is banned in secure-logging dirs — the "+ f"secure_logging wrapper delegates it to raw loguru, "+ f"reattaching tracebacks ungated; use "+ f"logger.exception() with a scrubbed safe_msg")elif node.attr == "logger":self.errors.append(@@ -1193,21 +2600,43 @@ class SensitiveLoggingChecker(ast.NodeVisitor):def _check_secure_dir_call(self, node: ast.Call) -> None:"""Literal getattr/import_module dodges + chained message checks."""func = node.func- # getattr(x, "opt"/"catch"/"logger"/private handles)+ pos = (node.lineno, node.col_offset)+ scope_path = tuple(self._lex_scopes)+ if isinstance(func, ast.Name):+ is_getattr_call = self._name_may(+ func.id, "getattr", pos, scope_path+ )+ elif isinstance(func, ast.Attribute):+ is_getattr_call = self._attr_may_be_getattr(+ func, pos, scope_path+ ) or (+ func.attr == "getattr"+ and isinstance(func.value, ast.Name)+ and self._name_may(func.value.id, "builtins", pos, scope_path)+ )+ else:+ is_getattr_call = Falseif (- isinstance(func, ast.Name)- and func.id == "getattr"+ is_getattr_calland len(node.args) >= 2and isinstance(node.args[1], ast.Constant)and isinstance(node.args[1].value, str)):attr = node.args[1].value- if attr in BANNED_LOGGER_ATTRS:+ # Fail closed, mirroring visit_Attribute: getattr(x, "patch") is+ # banned on every receiver in practice — passing a bare+ # requests/httpx name to getattr is a value use, which revokes+ # the exemption (SAFE_PATCH_RECEIVER_MODULES, condition 6).+ # getattr(x, "opt"/"catch") stay receiver-blind — no concrete+ # false positive was ever named for them.+ if attr in BANNED_LOGGER_ATTRS and not (+ attr == "patch" and self._is_safe_patch_receiver(node.args[0])+ ):if attr == "patch":reason = ('patchers can mutate record["exception"] and '"reattach tracebacks ungated"- )+ ) + self._patch_exemption_note(node.args[0])else:reason = "it reaches raw loguru handles"self.errors.append(@@ -1260,16 +2689,29 @@ class SensitiveLoggingChecker(ast.NodeVisitor):self._check_search_query_in_log(node)def _is_wrapper_chain(self, expr: ast.AST) -> bool:- """True for bind() call chains rooted at the name 'logger'."""+ """True for ``bind()`` chains rooted at a logger receiver.++ Returns False for non-``Call`` receivers (e.g. bare ``logger``) so+ that direct ``logger.error(...)`` calls are not double-checked —+ ``_is_logger_call`` already routes them through the message checks.+ """if not isinstance(expr, ast.Call):return False+ seen_bind = Falsewhile (isinstance(expr, ast.Call)and isinstance(expr.func, ast.Attribute)and expr.func.attr in WRAPPER_CHAIN_METHODS):+ seen_bind = Trueexpr = expr.func.value- return isinstance(expr, ast.Name) and expr.id == "logger"+ if not seen_bind:+ return False+ if isinstance(expr, ast.Name):+ return expr.id == "logger"+ if isinstance(expr, ast.Attribute):+ return expr.attr == "logger"+ return Falsedef visit_Call(self, node: ast.Call) -> None:"""Check function calls for logging sensitive data."""diff --git a/changelog.d/4998.security.md b/changelog.d/4998.security.mdnew file mode 100644index 0000000000..4fe42e2c3d--- /dev/null+++ b/changelog.d/4998.security.md@@ -0,0 +1 @@+HTTP PATCH calls through unchanged top-level `requests`/`httpx` imports are allowed in the sensitive-logging hook when the file passes a whole-file check: a denylist of namespace-reaching spellings (such as `globals()`, `setattr`, `sys.modules`, frame attributes, `exec`/`eval`) plus structural conditions (the import precedes every use, the module is never used as a value or imported under another name, no class keywords, no class-scope use, no dunder attribute writes). Code in other modules and APIs these lists do not name are not seen. Keep other receivers restricted and track builtin `getattr` aliases in their evaluation scopes.diff --git a/tests/security/test_sensitive_logging_hook.py b/tests/security/test_sensitive_logging_hook.pyindex d5f4d634de..7d936d418c 100644--- a/tests/security/test_sensitive_logging_hook.py+++ b/tests/security/test_sensitive_logging_hook.py@@ -421,6 +421,10 @@ class TestBypassRouteDetection:assert any(".patch" in e for e in errors), codedef test_getattr_dodges_flagged(self):+ # Fail closed: opt/catch/patch are banned on ANY receiver (a bare+ # `obj` name here) unless the receiver is provably not a logger —+ # see test_getattr_patch_dodge_allowed_on_safe_receiver_only for the+ # single narrow exception.for attr in ("opt","catch",@@ -434,6 +438,306 @@ class TestBypassRouteDetection:errors = _check_code(code, IN_DIR)assert any("getattr" in e for e in errors), attr+ def test_getattr_patch_dodge_never_exempt(self):+ # getattr(requests, "patch") passes the module object as a value+ # to a callable this rule cannot prove is the builtin (``from x+ # import getattr``), which revokes the requests/httpx exemption+ # (see SAFE_PATCH_RECEIVER_MODULES, condition 6) — so no+ # receiver is exempted from the getattr(..., "patch") ban,+ # including `requests` when it is NOT actually imported.+ for code in (+ 'import requests\ngetattr(requests, "patch")("u")\n',+ "import requests\n"+ "from .helpers import getattr\n"+ 'getattr(requests, "patch")("u")\n',+ 'getattr(obj, "patch")\n',+ # "requests" the bare name, but never imported: not provably+ # safe — could be a parameter holding a logger.+ 'getattr(requests, "patch")\n',+ ):+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in e for e in errors), code++ def test_attribute_ban_flagged_on_generic_receiver(self):+ # Fail closed: opt/catch are receiver-blind (no concrete,+ # nameable false positive was ever found for them), and patch is+ # banned on any receiver that isn't the narrow requests/httpx case.+ for code in (+ "obj.catch()\n",+ "obj.opt()\n",+ "obj.patch()\n",+ "requests.patch('https://x')\n", # no `import requests` present+ ):+ errors = _check_code(code, IN_DIR)+ assert errors, code++ def test_patch_allowed_on_safe_requests_httpx_receiver_only(self):+ # The one legitimate false positive #4976 named: bare, genuinely+ # imported `requests`/`httpx` making an HTTP PATCH call.+ for code in (+ "import requests\nrequests.patch('https://x')\n",+ "import httpx\nhttpx.patch('https://x')\n",+ ):+ assert _check_code(code, IN_DIR) == [], code++ def test_patch_safe_receiver_exception_does_not_cover_lookalikes(self):+ # Aliased imports, non-bare receivers, and other modules named+ # "patch" are NOT exempted — only the exact bare+ # requests/httpx-imported-unaliased shape is.+ for code in (+ "import requests as req\nreq.patch('u')\n",+ "from unittest import mock\nmock.patch('os.getenv')\n",+ "import requests\nsession.patch('u')\n", # unrelated receiver+ ):+ errors = _check_code(code, IN_DIR)+ assert errors, code++ def test_patch_safe_receiver_closed_when_name_is_a_parameter(self):+ # The class of bug #4998 introduced: a logger reaching a banned+ # attribute through a differently-named receiver. If "requests" is+ # ever used as a parameter anywhere in the file, the name can no+ # longer be trusted to be the imported module — the exception must+ # not apply, even though `import requests` is also present.+ code = (+ "import requests\n"+ "def helper(requests):\n"+ " requests.patch('boom')\n"+ "helper(logger)\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), errors++ def test_patch_safe_receiver_closed_when_name_is_rebound(self):+ # The imported-client exemption used to+ # survive every rebinding that was not a function parameter.+ # ANY binding form that can hand the imported name to a logger+ # before the call site must close it — factory or container+ # assignment, annotated/augmented assignment, loop, comprehension,+ # with-as, except-as, walrus, match capture, nested/aliased/star+ # imports, del, and same-named def/class bindings.+ for code in (+ "import requests\n"+ "requests = get_logger()\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ "requests = holders[0]\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ "requests: Any = get_logger()\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ "requests += extras\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ "for requests in holders:\n"+ " requests.patch(lambda r: r)\n",+ "import httpx\n"+ "async def f():\n"+ " async for httpx in holders:\n"+ " httpx.patch(lambda r: r)\n",+ "import requests\n"+ "out = [requests.patch(r) for requests in holders]\n",+ "import requests\n"+ "with get_ctx() as requests:\n"+ " requests.patch(lambda r: r)\n",+ "import httpx\n"+ "async def f():\n"+ " async with get_ctx() as httpx:\n"+ " httpx.patch(lambda r: r)\n",+ "import requests\n"+ "if (requests := get_logger()):\n"+ " requests.patch(lambda r: r)\n",+ "import requests\n"+ "try:\n"+ " f()\n"+ "except Exception as requests:\n"+ " requests.patch(lambda r: r)\n",+ "import requests\n"+ "match get_logger():\n"+ " case requests:\n"+ " requests.patch(lambda r: r)\n",+ "import requests\n"+ "def f():\n"+ " import provider as requests\n"+ " requests.patch(lambda r: r)\n",+ "import requests\n"+ "from helpers import requests\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ "from helpers import *\n"+ "requests.patch(lambda r: r)\n",+ "import requests\ndel requests\nrequests.patch(lambda r: r)\n",+ "import requests\n"+ "class requests:\n"+ " pass\n"+ "requests.patch(lambda r: r)\n",+ ):+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), code++ def test_getattr_patch_dodge_closed_when_safe_receiver_is_rebound(self):+ # The same closure through the literal-getattr route: once the+ # name is rebound, getattr(httpx, "patch") is no longer provably+ # an HTTP-client call and must stay banned.+ code = (+ "import httpx\n"+ "httpx = get_logger()\n"+ 'getattr(httpx, "patch")(lambda r: r)\n'+ )+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in e for e in errors), errors++ def test_patch_safe_receiver_closed_by_dynamic_namespace_rebinding(self):+ for code in (+ "import requests\n"+ "globals()[name] = get_logger()\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ 'globals()["requests"] = get_logger()\n'+ "requests.patch(lambda r: r)\n",+ "import httpx\n"+ "globals().update(httpx=get_logger())\n"+ 'getattr(httpx, "patch")(lambda r: r)\n',+ "import sys\n"+ "import requests\n"+ 'setattr(sys.modules[__name__], "requests", get_logger())\n'+ "requests.patch(lambda r: r)\n",+ ):+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), code++ def test_patch_safe_receiver_closed_by_ordinary_namespace_mutation(self):+ for code in (+ "import sys\n"+ "import requests\n"+ "sys.modules[__name__].requests = get_logger()\n"+ "requests.patch(lambda r: r)\n",+ "import sys as s\n"+ "import requests\n"+ "s.modules[__name__].requests = get_logger()\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ "g = globals\n"+ "g()['requests'] = get_logger()\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ "g = globals\n"+ "g().update(requests=get_logger())\n"+ "requests.patch(lambda r: r)\n",+ "import requests\n"+ "dict.update(globals(), requests=get_logger())\n"+ "requests.patch(lambda r: r)\n",+ "import sys\n"+ "import requests\n"+ "sa = setattr\n"+ "sa(sys.modules[__name__], 'requests', get_logger())\n"+ "requests.patch(lambda r: r)\n",+ ):+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), code++ def test_getattr_aliases_and_alias_chains_are_checked_fail_closed(self):+ for code in (+ "ga = getattr\nga(logger, 'patch')(lambda r: r)\n",+ "ga = getattr\nlookup = ga\nlookup(logger, 'patch')(lambda r: r)\n",+ "import builtins as b\nga = b.getattr\nga(logger, 'patch')()\n",+ "from builtins import getattr as ga\nga(logger, 'patch')()\n",+ ):+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in error for error in errors), (+ code+ )++ def test_getattr_module_and_static_alias_forms_checked_fail_closed(self):+ for code in (+ "import builtins\nbuiltins.getattr(logger, 'patch')(lambda r: r)\n",+ "import builtins as b\nb.getattr(logger, 'patch')(lambda r: r)\n",+ "if (ga := getattr):\n ga(logger, 'patch')(lambda r: r)\n",+ "ga, pr = getattr, print\nga(logger, 'patch')(lambda r: r)\n",+ "def f(ga=getattr):\n ga(logger, 'patch')(lambda r: r)\n",+ "ga = getattr if flag else print\n"+ "ga(logger, 'patch')(lambda r: r)\n",+ "h = Holder()\n"+ "h.ga = getattr\n"+ "h.ga(logger, 'patch')(lambda r: r)\n",+ ):+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in error for error in errors), (+ code+ )++ def test_getattr_alias_rebind_and_parameter_shadow_are_allowed(self):+ for code in (+ "ga = getattr\nga = api_call\nga(obj, 'patch')\n",+ "ga = getattr\ndef f(ga):\n ga(obj, 'patch')\n",+ "import builtins as b\n"+ "b = api_call\n"+ "ga = b.getattr\n"+ "ga(obj, 'patch')\n",+ "import builtins as b\nb = api_call\nb.getattr(obj, 'patch')\n",+ ):+ assert _check_code(code, IN_DIR) == [], code++ def test_patch_safe_receiver_survives_unrelated_rebinding(self):+ # Rebinding a DIFFERENT name must not close the exemption: the+ # whole-file invalidation is keyed on the safe name itself.+ code = (+ "import requests\n"+ "other = get_logger()\n"+ "for other in holders:\n"+ " pass\n"+ "requests.patch('https://x')\n"+ )+ assert _check_code(code, IN_DIR) == [], code++ def test_patch_safe_receiver_rebinding_is_whole_file_fail_closed(self):+ # The invalidation is deliberately whole-file, matching the+ # parameter rule it extends: one rebinding anywhere closes the+ # exemption for every call site in the file, including genuine+ # HTTP calls in unrelated functions. An inline suppression is+ # the escape hatch, not a scope-aware allowlist.+ code = (+ "import requests\n"+ "def helper():\n"+ " requests = get_logger()\n"+ " requests.patch(lambda r: r)\n"+ "def genuine():\n"+ " requests.patch('https://x')\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), errors++ def test_attribute_ban_flagged_on_indirect_logger_receiver(self):+ # Actual logger receivers must still trip the opt/catch/patch ban:+ # ``self.logger``, ``cls.logger``, ``pkg.logger`` and bind chains+ # rooted at them.+ for code in (+ "self.logger.opt(exception=True).error('x')\n",+ "cls.logger.catch()\n",+ "pkg.logger.patch(lambda r: None)\n",+ "self.logger.bind(x=1).opt(depth=1)\n",+ ):+ errors = _check_code(code, IN_DIR)+ assert any(+ ".opt" in e or ".catch" in e or ".patch" in e for e in errors+ ), code++ def test_attribute_ban_flagged_on_getattr_bind_chain(self):+ # Any getattr-obfuscated bind chain stays banned for opt/catch+ # (receiver-blind) and for patch (the receiver is a Call, never+ # the bare safe-module Name, so it fails closed too — even when+ # nominally rooted at ``requests``).+ for code in (+ 'getattr(logger, "bind")(x=1).opt(exception=True).error("x")\n',+ 'getattr(self.logger, "bind")(x=1).patch(lambda r: None)\n',+ 'getattr(logger, "bind")(a=1).bind(b=2).catch()\n',+ 'import requests\ngetattr(requests, "bind")(x=1).patch("u")\n',+ ):+ errors = _check_code(code, IN_DIR)+ assert any(+ ".opt" in e or ".catch" in e or ".patch" in e for e in errors+ ), code+def test_logger_attribute_access_flagged(self):for code in ("something.logger.exception('x')\n",@@ -535,6 +839,1123 @@ class TestBypassRouteDetection:assert _check_code(code, IN_DIR) == []+class TestReceiverObfuscationClasses:+ """#4998 regression: a receiver-narrowing allowlist reopened the exact+ false-negative class the opt/catch/patch ban exists to close — a logger+ reaching a banned attribute through ANY receiver shape other than the+ handful of literal patterns an allowlist happened to name. These cover+ the CLASS (parameter passing, non-``logger``-named attributes, dict/list+ elements, ternaries, multi-hop aliasing), not just the two examples that+ slipped through review. Direction coverage is asymmetric by design:+ real loggers must be flagged, and genuine non-loggers must stay+ usable for method names the ban does not name at all (``.get``);+ a genuine non-logger calling an identically-named banned method+ through a non-provably-safe receiver stays blocked — that+ fail-closed tradeoff is pinned explicitly by+ test_requests_httpx_patch_still_flagged_through_ternary_or_param+ """++ # -- must be flagged: a logger reaches a banned attribute through an+ # obfuscated receiver ---------------------------------------------------++ def test_logger_passed_as_differently_named_parameter_flagged(self):+ code = (+ "def helper(log_obj):\n"+ " log_obj.opt(exception=True).error('boom')\n"+ "helper(logger)\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".opt" in e for e in errors), errors++ def test_logger_stored_on_non_logger_named_attribute_flagged(self):+ code = (+ "class Foo:\n"+ " def __init__(self, lg):\n"+ " self.lg = lg\n"+ " def go(self):\n"+ " self.lg.catch()(func)\n"+ "Foo(logger).go()\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".catch" in e for e in errors), errors++ def test_logger_in_dict_element_flagged(self):+ code = (+ "handlers = {'main': logger}\n"+ "handlers['main'].opt(exception=True).error('boom')\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".opt" in e for e in errors), errors++ def test_logger_in_list_element_flagged(self):+ code = "handlers = [logger]\nhandlers[0].catch()(func)\n"+ errors = _check_code(code, IN_DIR)+ assert any(".catch" in e for e in errors), errors++ def test_logger_selected_by_ternary_flagged(self):+ code = (+ "def pick(flag, other):\n"+ " chosen = logger if flag else other\n"+ " chosen.opt(exception=True).error('boom')\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".opt" in e for e in errors), errors++ def test_logger_aliased_through_several_assignments_flagged(self):+ # Direct `x = logger` derivation is banned on the first hop, but the+ # attribute access on the further-aliased name must ALSO be caught+ # independently — belt and suspenders against a hop the derivation+ # check itself might miss.+ code = (+ "class Wrapper:\n"+ " def __init__(self):\n"+ " self.handle = logger\n"+ " def emit(self):\n"+ " h = self.handle\n"+ " h2 = h\n"+ " h2.patch(lambda r: r)('boom')\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), errors++ def test_logger_returned_from_call_then_chained_flagged(self):+ # Receiver is itself a Call (e.g. a factory/getter) rather than any+ # recognisable name shape at all.+ code = "get_logger().opt(exception=True).error('boom')\n"+ errors = _check_code(code, IN_DIR)+ assert any(".opt" in e for e in errors), errors++ # -- must NOT be flagged: no logger is anywhere in the picture ---------++ def test_non_logger_passed_as_parameter_not_flagged_for_bind(self):+ # Sanity check for the "both directions" requirement using a shape+ # that never touches a banned attribute name in the first place.+ code = (+ "def helper(session):\n"+ " session.get('https://x')\n"+ "helper(requests.Session())\n"+ )+ assert _check_code(code, IN_DIR) == [], code++ def test_non_logger_dict_and_list_elements_not_flagged_absent_ban(self):+ code = (+ "sessions = {'main': make_session()}\n"+ "sessions['main'].get('https://x')\n"+ "queue = [make_session()]\n"+ "queue[0].get('https://x')\n"+ )+ assert _check_code(code, IN_DIR) == [], code++ def test_requests_httpx_patch_still_flagged_through_ternary_or_param(self):+ # The narrow, tracked-as-safe exception (SAFE_PATCH_RECEIVER_MODULES)+ # is a bare, genuinely-imported, never-shadowed name — it does not+ # extend through indirection. A ternary or parameter hop around+ # requests/httpx therefore stays banned even though no logger is+ # actually involved; that is the accepted, documented fail-closed+ # tradeoff. There is no inline suppression for ``.patch`` — the+ # remedy is to call through the bare imported module name+ # directly (``requests.patch(...)``/``httpx.patch(...)``) or to+ # move the call out of a secure logging directory.+ code = (+ "import requests\n"+ "def call(flag, other):\n"+ " client = requests if flag else other\n"+ " client.patch('https://x')\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), errors+++class TestAttributeAndScopeAliasSoundness:+ """Attribute-held+ getattr aliases must be tracked per receiver, scope, and execution+ order with transitive propagation; any module-namespace spelling+ revokes the requests/httpx .patch exemption; and definite+ rebindings must clear getattr aliases in If tests, finally suites,+ and enclosing scopes without contributor-blocking false positives.+ """++ def test_attribute_alias_tracked_per_receiver(self):+ # Another receiver's definite rebind of the same attribute+ # text must not erase a live alias: the timeline is keyed by+ # receiver plus attribute, not attribute text alone.+ code = (+ "class H:\n"+ " pass\n"+ "a = H()\n"+ "b = H()\n"+ "a.ga = getattr\n"+ "b.ga = print\n"+ 'a.ga(logger, "patch")(lambda r: r)\n'+ )+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in e for e in errors), errors++ def test_attribute_alias_same_receiver_definite_rebind_allowed(self):+ # The definite clear on the SAME receiver retires the alias;+ # pins the false-positive direction of the receiver keying.+ code = (+ 'h = Holder()\nh.ga = getattr\nh.ga = print\nh.ga(obj, "patch")\n'+ )+ assert _check_code(code, IN_DIR) == [], code++ def test_attribute_alias_propagates_through_name(self):+ # Transitive propagation: a name bound to an attribute-held+ # alias (``lookup = h.ga``) is itself a getattr alias.+ code = (+ "h = Holder()\n"+ "h.ga = getattr\n"+ "lookup = h.ga\n"+ 'lookup(logger, "patch")(lambda r: r)\n'+ )+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in e for e in errors), errors++ def test_attribute_alias_respects_function_execution_order(self):+ # install() runs before use(), so the alias is live inside+ # use() even though the installing assignment textually+ # follows the call site it protects.+ code = (+ "h = Holder()\n"+ "def use():\n"+ ' h.ga(logger, "patch")(lambda r: r)\n'+ "def install():\n"+ " h.ga = getattr\n"+ "install()\n"+ "use()\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in e for e in errors), errors++ def test_class_body_alias_binding_covers_instances(self):+ # ``class H: ga = getattr`` puts the alias on every instance;+ # the instance's class cannot be recovered statically, so any+ # ``self.ga`` may reach it.+ code = (+ "class H:\n"+ " ga = getattr\n"+ " def use(self):\n"+ ' self.ga(logger, "patch")(lambda r: r)\n'+ )+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in e for e in errors), errors++ def test_class_body_alias_definite_rebind_retires_it(self):+ # A definite later rebind in the same class body retires the+ # instance-visible alias; pins the false-positive direction+ # of the class-body wildcard.+ code = (+ "class H:\n"+ " ga = getattr\n"+ " ga = print\n"+ " def use(self):\n"+ ' self.ga(obj, "patch")\n'+ )+ assert _check_code(code, IN_DIR) == [], code++ def test_safe_receiver_closed_by_builtins_globals_alias(self):+ # ``g = builtins.globals`` is a realistic alias spelling the+ # old bare-Name propagation missed.+ code = (+ "import builtins\n"+ "import requests\n"+ "g = builtins.globals\n"+ 'g()["requests"] = get_logger()\n'+ "requests.patch(lambda r: r)\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), errors++ def test_safe_receiver_closed_by_globals_setitem(self):+ code = (+ "import requests\n"+ 'globals().__setitem__("requests", get_logger())\n'+ "requests.patch(lambda r: r)\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), errors++ def test_safe_receiver_closed_by_tuple_created_globals_alias(self):+ # Tuple destructuring created the alias; only the element-wise+ # value tracking recognizes it.+ code = (+ "import requests\n"+ "g, other = globals, None\n"+ 'g()["requests"] = get_logger()\n'+ "requests.patch(lambda r: r)\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), errors++ def test_stale_globals_alias_still_revokes_patch_exemption(self):+ # At runtime g no longer is the globals builtin when the+ # subscript runs, so this particular file is harmless. The+ # exemption deliberately does not model that: deciding it+ # needed execution-order reasoning that loops, starred+ # arguments and indirect call sites kept defeating. Any+ # ``globals`` spelling revokes it for the whole file, and the+ # diagnostic names the spelling so the author can see why.+ code = (+ "import requests\n"+ "g = globals\n"+ "g = lambda: {}\n"+ 'g()["requests"] = get_logger()\n'+ 'requests.patch("https://example.test")\n'+ )+ errors = _check_code(code, IN_DIR)+ assert any(+ ":5: .patch is banned" in e+ and "exemption is revoked for this file by globals on line 2" in e+ for e in errors+ ), errors++ def test_global_alias_install_flagged(self):+ # ``global ga`` inside install() writes the module binding, so+ # the module-level call after install() sees the alias.+ code = (+ "ga = print\n"+ "def install():\n"+ " global ga\n"+ " ga = getattr\n"+ "install()\n"+ 'ga(logger, "patch")(lambda r: r)\n'+ )+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in e for e in errors), errors++ def test_nonlocal_alias_install_flagged(self):+ # ``nonlocal ga`` writes outer()'s binding, so the call inside+ # outer() after install() sees the alias.+ code = (+ "def outer():\n"+ " ga = print\n"+ " def install():\n"+ " nonlocal ga\n"+ " ga = getattr\n"+ " install()\n"+ ' ga(logger, "patch")(lambda r: r)\n'+ "outer()\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "patch")' in e for e in errors), errors++ def test_walrus_in_if_test_definite_rebind_allowed(self):+ # The If test always executes before the body and any+ # following statement, so its walrus rebind is definite.+ code = 'ga = getattr\nif (ga := print):\n pass\nga(obj, "patch")\n'+ assert _check_code(code, IN_DIR) == [], code++ def test_with_body_rebind_is_conditional(self):+ # A ``with`` body does not always run to completion — a context+ # manager such as ``contextlib.suppress`` can swallow the+ # exception raised partway through it, so the rebind here never+ # executes. The bare ``getattr`` is never retired by any rebind;+ # the ``ga`` alias pins the ``With: body`` conditional row.+ for name in ("getattr", "ga"):+ code = (+ "import contextlib\n"+ "ga = getattr\n"+ "with contextlib.suppress(AttributeError):\n"+ " y = object().missing\n"+ f" {name} = str\n"+ f"x = {name}(logger, 'opt')\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "opt")' in e for e in errors), code++ def test_with_body_globals_rebind_does_not_arm_patch_exemption(self):+ # Same non-execution as above, but through the globals()+ # namespace-mutation channel: ``globals = lambda: {}`` inside+ # the suppressed body never runs, so ``globals()`` at module+ # level is still the real builtin and its subscript write+ # rebinds the module's ``requests`` name to a logger before+ # ``requests.patch(...)`` is reached — the full SAFE_PATCH_+ # RECEIVER_MODULES bypass chain from B1.+ # The ``g`` alias variant pins the same row for aliases, since+ # the bare ``globals`` is never retired by any rebind.+ for name in ("globals", "g"):+ code = (+ "import contextlib\n"+ "class FakeLogger:\n"+ " def patch(self, *a, **k): return 'RAW-LOGURU-PATCH'\n"+ "def get_logger(): return FakeLogger()\n"+ "import requests\n"+ "g = globals\n"+ "with contextlib.suppress(AttributeError):\n"+ " y = object().missing\n"+ f" {name} = lambda: {{}}\n"+ f"{name}()['requests'] = get_logger()\n"+ "requests.patch('u')\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), code++ def test_assert_walrus_rebind_is_conditional(self):+ # ``assert`` statements (both test and msg) are stripped under+ # ``-O``, so a walrus rebind inside one is never definite — it+ # must not retire a globals alias, or the namespace-mutation+ # write below silently escapes the ban. (The bare ``globals``+ # is never retired by any rebind; ``g`` pins the Assert row.)+ for name in ("globals", "g"):+ code = (+ "import requests\n"+ "g = globals\n"+ f"assert ({name} := (lambda: {{}}))\n"+ f"{name}()['requests'] = get_logger()\n"+ "requests.patch('u')\n"+ )+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), code++ def test_finally_definite_rebind_allowed(self):+ # The finally suite always runs before any statement that+ # follows the try, so its rebind is definite.+ code = (+ "ga = getattr\n"+ "try:\n"+ " pass\n"+ "finally:\n"+ " ga = print\n"+ 'ga(obj, "patch")\n'+ )+ assert _check_code(code, IN_DIR) == [], code++ def test_enclosing_scope_definite_rebind_allowed(self):+ # Both module-level rebinds precede use's definition, so the+ # free name inside use() resolves to print at every call+ # time — an enclosing-scope definite clear must be honored.+ code = (+ "ga = getattr\n"+ "ga = print\n"+ "def use():\n"+ ' ga(obj, "patch")\n'+ "use()\n"+ )+ assert _check_code(code, IN_DIR) == [], code+++class TestBindingEvaluationAndNamespaceObjects:+ """Builtin lookups follow evaluation scope and namespace writes."""++ def test_assignment_reads_rhs_before_binding(self):+ cases = {+ "rhs_before_binding": 'getattr = getattr(obj, "patch")\ngetattr()\n',+ "annotated_rhs": 'getattr: object = getattr(obj, "patch")\n',+ "builtin_named_definition_default": 'def getattr(x=getattr(obj,"patch")):\n pass\n',+ "builtin_named_class_base": 'class getattr(getattr(obj,"patch")):\n pass\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), (name, errors)++ def test_deferred_outer_clears_do_not_hide_aliases(self):+ cases = {+ "uncalled_global_clear": 'def unused():\n global getattr\n getattr = lambda *a: None\ngetattr(obj, "patch")()\n',+ "nonlocal_clear": 'def outer():\n ga=getattr\n def unused():\n nonlocal ga\n ga=print\n ga(obj,"patch")\n',+ "global_rhs_local_alias": 'def install():\n global ga\n source=getattr\n ga=source\ninstall()\nga(obj,"patch")\n',+ "global_namespace_clear_deferred": 'import requests\ndef unused():\n global globals\n globals=lambda:{}\nglobals()["requests"]=candidate\nrequests.patch()\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), (name, errors)++ def test_definition_expressions_use_enclosing_scope(self):+ cases = {+ "default_builtin_parameter": 'def f(getattr, value=getattr(obj, "patch")):\n pass\n',+ "keyword_default_builtin_parameter": 'def f(*, getattr=None, value=getattr(obj, "patch")):\n pass\n',+ "annotation_builtin_parameter": 'def f(getattr: getattr(obj, "patch")):\n pass\n',+ "decorator_outer_alias": 'ga = getattr\n@decorate(ga(obj, "patch"))\ndef f(ga):\n pass\n',+ "default_outer_alias": 'ga = getattr\ndef f(ga, value=ga(obj, "patch")):\n pass\n',+ "lambda_default_builtin_parameter": 'f = lambda getattr, value=getattr(obj, "patch"): None\n',+ "class_base_shadow": 'ga = getattr\nclass C(ga(obj, "patch")):\n ga = print\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), (name, errors)++ def test_namespace_objects_and_dynamic_targets_invalidate_http_receiver(+ self,+ ):+ cases = {+ "namespace_object": 'import requests\nnamespace = globals()\nnamespace["requests"] = candidate\nrequests.patch()\n',+ "module_object": "import sys\nimport requests\nmodule = sys.modules[__name__]\nmodule.requests = candidate\nrequests.patch()\n",+ "module_locals": 'import requests\nlocals()["requests"] = candidate\nrequests.patch()\n',+ "loop_dynamic_target": 'import requests\nfor globals()["requests"] in [candidate]:\n requests.patch()\n',+ "with_target": 'import requests\nwith resource as globals()["requests"]:\n requests.patch()\n',+ "comprehension_target": 'import requests\n[None for globals()["requests"] in values]\nrequests.patch()\n',+ "namespace_update": "import requests\nns=globals()\nns.update(requests=candidate)\nrequests.patch()\n",+ "namespace_dunder": 'import requests\nns=globals()\nns.__setitem__("requests",candidate)\nrequests.patch()\n',+ "module_dict_alias": 'import sys\nimport requests\nm=sys.modules[__name__]\nns=m.__dict__\nns["requests"]=candidate\nrequests.patch()\n',+ "module_alias_setattr": 'import sys\nimport requests\nm=sys.modules[__name__]\nsetattr(m,"requests",candidate)\nrequests.patch()\n',+ "module_locals_alias": 'import requests\nf=locals\nns=f()\nns["requests"]=candidate\nrequests.patch()\n',+ "imported_locals": 'from builtins import locals as get_ns\nimport requests\nget_ns()["requests"]=candidate\nrequests.patch()\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), (name, errors)++ def test_namespace_vocabulary_revokes_http_receiver_unconditionally(+ self,+ ):+ # These writes miss the module's ``requests`` at runtime (another+ # key, a rebound alias, a function's locals), but the exemption+ # no longer reasons about which namespace a write reaches: any+ # namespace-reaching spelling revokes it for the whole file, so+ # each is flagged exactly as on main. Only the vocabulary-free+ # file keeps the exemption.+ cases = {+ "unrelated_namespace_key": 'import requests\nns=globals()\nns["unrelated"] = candidate\nrequests.patch()\n',+ "cleared_namespace_function": 'import requests\ng=globals\ng=lambda: {}\ng()["requests"] = candidate\nrequests.patch()\n',+ "namespace_rebound": 'import requests\nns=globals()\nns={}\nns["requests"]=candidate\nrequests.patch()\n',+ "module_alias_rebound": "import sys\nimport requests\nm=sys.modules[__name__]\nm=other\nm.requests=candidate\nrequests.patch()\n",+ "function_locals_control": 'import requests\ndef f():\n ns=locals()\n ns["requests"]=candidate\nrequests.patch()\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any(".patch is banned" in e for e in errors), (name, errors)+ genuine = 'import requests\nrequests.patch("synthetic")\n'+ assert _check_code(genuine, IN_DIR) == [], genuine+++class TestDeletionFallbackAndNamespaceMutation:+ """Deletion fallback and identity-preserving namespace updates."""++ def test_deleted_names_resolve_correct_fallback(self):+ cases = {+ "delete_builtin_restore": 'getattr=print\ndel getattr\ngetattr(obj,"patch")\n',+ "delete_globals_restore": 'import requests\nglobals=lambda:{}\ndel globals\nglobals()["requests"]=candidate\nrequests.patch()\n',+ "class_delete_outer_alias": 'ga=getattr\nclass C:\n ga=print\n del ga\n ga(obj,"patch")\n',+ "deferred_global_deletion": 'getattr=print\ndef restore():\n global getattr\n del getattr\nrestore()\ngetattr(obj,"patch")\n',+ # A bare builtin name is never retired by a rebind (as on+ # main), so these two formerly-allowed shapes are flagged.+ "class_delete_outer_safe": 'getattr=print\nclass C:\n getattr=print\n del getattr\n getattr(obj,"patch")\n',+ "function_deleted_local_unbound": 'def f():\n getattr=print\n del getattr\n getattr(obj,"patch")\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), (name, errors)++ def test_lexical_aliases_use_the_defining_binding(self):+ cases = {+ "default_alias_from_outer_shadowed_parameter": 'ga=getattr\ndef f(ga, lookup=ga):\n lookup(obj,"patch")\nf(None)\n',+ "class_fallback_outer_alias": 'ga=getattr\nclass C:\n ga(obj,"patch")\n ga=print\n',+ "nonlocal_skips_unbound_middle": 'def outer():\n ga=getattr\n def middle():\n def unused():\n nonlocal ga\n ga=print\n ga(obj,"patch")\n middle()\nouter()\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), (name, errors)++ def test_namespace_mutation_spellings_reject_replaced_clients(self):+ cases = {+ "namespace_property_storage": 'import requests\nh.ns=globals()\nh.ns["requests"]=candidate\nrequests.patch()\n',+ "class_locals": 'import requests\nclass C:\n locals()["requests"]=candidate\n requests.patch()\n',+ "namespace_ior_empty": 'import requests\nns=globals()\nns |= {}\nns["requests"]=candidate\nrequests.patch()\n',+ "namespace_ior_keys": 'import requests\nns=globals()\nns |= {"requests":candidate}\nrequests.patch()\n',+ "unbound_setitem": 'import requests\ndict.__setitem__(globals(),"requests",candidate)\nrequests.patch()\n',+ "vars_module": 'import requests\nimport sys\nvars(sys.modules[__name__])["requests"]=candidate\nrequests.patch()\n',+ "vars_zero": 'import requests\nvars()["requests"]=candidate\nrequests.patch()\n',+ "direct_ior": 'import requests\nglobals().__ior__({"requests":candidate})\nrequests.patch()\n',+ "class_setdefault": 'import requests\nclass C:\n locals().setdefault("requests",candidate)\n requests.patch()\n',+ "attribute_function_alias": 'import requests\nh.g=globals\nh.g()["requests"]=candidate\nrequests.patch()\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any("patch" in error for error in errors), (name, errors)++ def test_harmless_namespace_reads_and_updates_still_revoke(self):+ # Harmless at runtime (another key, a copy), yet flagged: the+ # exemption is vocabulary-gated, not a model of which mapping a+ # write lands in. This matches main, which bans every .patch.+ cases = {+ "class_unrelated": 'import requests\nclass C:\n locals()["unrelated"]=candidate\n requests.patch()\n',+ "globals_copy": 'import requests\nns=globals().copy()\nns["requests"]=candidate\nrequests.patch()\n',+ "unrelated_ior": 'import requests\nns=globals()\nns |= {"other":candidate}\nrequests.patch()\n',+ }+ for name, code in cases.items():+ errors = _check_code(code, IN_DIR)+ assert any(".patch is banned" in e for e in errors), (name, errors)+++class TestBuiltinNamesNeverRetired:+ """A rebind never retires the bare ``getattr``.++ ``getattr`` always may be the builtin, whatever the file binds to+ it — as on main. Each class below is a construct an earlier+ revision modelled as a definite clear although at runtime the+ builtin was still (or again) reachable, silently dropping a+ diagnostic main emits. The ``ga`` alias variants pin the same+ constructs for aliases, which ARE cleared by definite rebinds.+ Each ``.patch`` case, run for real, rebinds ``requests`` to the+ logger before the call; they stay flagged because the+ ``globals``/``g`` spellings revoke the requests/httpx exemption.+ """++ PATCH_TAIL = "g()['requests'] = get_logger()\nrequests.patch('u')\n"++ @staticmethod+ def _assert_opt(code):+ errors = _check_code(code, IN_DIR)+ assert any('getattr(..., "opt")' in e for e in errors), (code, errors)++ @staticmethod+ def _assert_patch(code):+ errors = _check_code(code, IN_DIR)+ assert any(".patch" in e for e in errors), (code, errors)++ def test_with_item_behind_suppress_is_not_a_definite_rebind(self):+ # ``suppress`` swallows the AttributeError raised while the+ # second item is evaluated, so its ``as`` target never binds+ # and the with body is skipped.+ pre = "import contextlib\n"+ for code in (+ pre + "with contextlib.suppress(AttributeError),"+ " object().missing as getattr:\n"+ " pass\n"+ "x = getattr(logger, 'opt')\n",+ # suppress(...).__enter__ returns None: unpacking it raises+ # TypeError inside the manager, which it swallows.+ pre + "with contextlib.suppress(TypeError) as (getattr, _):\n"+ " pass\n"+ "x = getattr(logger, 'opt')\n",+ ):+ self._assert_opt(code)+ for code in (+ "import requests\n"+ + pre+ + "with contextlib.suppress(AttributeError),"+ " object().missing as globals:\n"+ " pass\n"+ "globals()['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ "import requests\n" + pre + "g = globals\n"+ "with contextlib.suppress(AttributeError),"+ " object().missing as g:\n"+ " pass\n" + self.PATCH_TAIL,+ "import requests\n" + pre + "g = globals\n"+ "with contextlib.suppress(AttributeError),"+ " (object().missing, (g := dict))[0]:\n"+ " pass\n" + self.PATCH_TAIL,+ ):+ self._assert_patch(code)++ def test_except_as_implicit_delete_restores_the_builtin(self):+ # Python deletes the handler name when the handler ends, so the+ # builtin is visible again afterwards.+ self._assert_opt(+ "getattr = str\n"+ "try:\n"+ " raise ValueError\n"+ "except ValueError as getattr:\n"+ " pass\n"+ "x = getattr(logger, 'opt')\n"+ )+ for code in (+ "import requests\n"+ "globals = (lambda: {})\n"+ "try:\n"+ " raise ValueError\n"+ "except ValueError as globals:\n"+ " pass\n"+ "globals()['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ "import requests\n"+ "class K:\n"+ " globals = lambda: {}\n"+ " try:\n"+ " raise ValueError\n"+ " except ValueError as globals:\n"+ " pass\n"+ " globals()['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ # In a class body the deleted alias falls back to the+ # module-level ``g = globals``.+ "import requests\n"+ "g = globals\n"+ "class K:\n"+ " g = lambda: {}\n"+ " try:\n"+ " raise ValueError\n"+ " except ValueError as g:\n"+ " pass\n"+ " g()['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ ):+ self._assert_patch(code)++ def test_walrus_in_assignment_target_runs_after_the_rhs(self):+ # The RHS is evaluated before any target expression, and a For+ # target is never evaluated for an empty iterable.+ for code in (+ "d = {}\nd[(getattr := str)] = getattr(logger, 'opt')\n",+ "d = {}\n"+ "for d[(getattr := str)] in []:\n"+ " pass\n"+ "x = getattr(logger, 'opt')\n",+ ):+ self._assert_opt(code)+ for code in (+ "import requests\n"+ "g = globals\n"+ "d = {}\n"+ "d[(g := dict)] = g().__setitem__('requests', get_logger())\n"+ "requests.patch('u')\n",+ "import requests\n"+ "g = globals\n"+ "d = {}\n"+ "for d[(g := dict)] in []:\n"+ " pass\n" + self.PATCH_TAIL,+ ):+ self._assert_patch(code)++ def test_subscript_and_lambda_rhs_still_yield_the_builtin(self):+ for code in (+ "getattr = [getattr][0]\nx = getattr(logger, 'opt')\n",+ "getattr = (lambda: getattr)()\nx = getattr(logger, 'opt')\n",+ # Alias gains through the same value shapes.+ "ga = {'k': getattr}['k']\nx = ga(logger, 'opt')\n",+ "ga = __import__('builtins').getattr\nx = ga(logger, 'opt')\n",+ ):+ self._assert_opt(code)+ for code in (+ "import requests\n"+ "globals = (globals,)[0]\n"+ "globals()['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ "import requests\ng = [globals][0]\n" + self.PATCH_TAIL,+ "import requests\ng = (lambda: globals)()\n" + self.PATCH_TAIL,+ "import requests\n"+ "import builtins\n"+ "g = vars(builtins)['globals']\n" + self.PATCH_TAIL,+ "import requests\n"+ "import builtins\n"+ "g = getattr(builtins, 'globals')\n" + self.PATCH_TAIL,+ ):+ self._assert_patch(code)++ def test_async_with_body_is_conditional(self):+ # The async context manager swallows the AttributeError, so the+ # alias rebind after it never runs.+ manager = (+ "class Suppress:\n"+ " async def __aenter__(self): return self\n"+ " async def __aexit__(self, *exc): return True\n"+ )+ self._assert_opt(+ manager + "async def f():\n"+ " ga = getattr\n"+ " async with Suppress():\n"+ " y = object().missing\n"+ " ga = str\n"+ " return ga(logger, 'opt')\n"+ )+ self._assert_patch(+ "import requests\n" + manager + "async def f():\n"+ " g = globals\n"+ " async with Suppress():\n"+ " y = object().missing\n"+ " g = lambda: {}\n"+ " g()['requests'] = get_logger()\n"+ "requests.patch('u')\n"+ )+++class TestPatchExemptionNamespaceVocabulary:+ """The requests/httpx ``.patch`` exemption is vocabulary-gated.++ Each fixture below, run for real, hands ``requests`` a logger (or+ swaps ``requests.patch``) before the final call, through a channel+ an execution-order model of aliases got wrong. The exemption now+ ignores order entirely: any namespace-reaching spelling anywhere in+ the file revokes it, so each is flagged on the final line as on+ main. The clean files at the end are why the exemption exists.+ """++ @staticmethod+ def _assert_final_patch_flagged(code):+ last = code.rstrip("\n").count("\n") + 1+ errors = _check_code(code, IN_DIR)+ assert any(f":{last}: .patch is banned" in e for e in errors), (+ code,+ errors,+ )++ def test_loop_back_edge_rebinding(self):+ for code in (+ "import requests\n"+ "g = dict\n"+ "for i in range(2):\n"+ " g()['requests'] = get_logger()\n"+ " g = globals\n"+ "requests.patch('u')\n",+ "import requests\n"+ "ns = {}\n"+ "while cond():\n"+ " ns['requests'] = get_logger()\n"+ " ns = globals()\n"+ "requests.patch('u')\n",+ ):+ self._assert_final_patch_flagged(code)++ def test_starred_argument_evaluation_order(self):+ # Starred positionals run before keyword values.+ self._assert_final_patch_flagged(+ "import requests\n"+ "ns = globals()\n"+ "f(k=(ns := {}), *[ns.__setitem__('requests', get_logger())])\n"+ "requests.patch('u')\n"+ )++ def test_indirect_setattr_call_sites(self):+ for code in (+ "import requests, sys\n"+ "[setattr][0](sys.modules[__name__], 'requests', get_logger())\n"+ "requests.patch('u')\n",+ "import requests, sys\n"+ "(s := setattr)(sys.modules[__name__], 'requests', get_logger())\n"+ "requests.patch('u')\n",+ "import requests, sys\n"+ "(lambda: setattr)()(sys.modules[__name__], 'requests', L)\n"+ "requests.patch('u')\n",+ ):+ self._assert_final_patch_flagged(code)++ def test_function_and_frame_globals(self):+ for code in (+ "import requests\n"+ "def f():\n"+ " pass\n"+ "f.__globals__['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ "import requests, sys\n"+ "sys._getframe().f_globals['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ "import requests\n"+ "def f():\n"+ " pass\n"+ "getattr(f, '__glo' + 'bals__')['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ ):+ self._assert_final_patch_flagged(code)++ def test_sys_modules_main_and_self_import(self):+ for code in (+ "import requests, sys\n"+ "sys.modules['__main__'].requests = get_logger()\n"+ "requests.patch('u')\n",+ "import requests\n"+ "from sys import modules\n"+ "modules[__name__].requests = get_logger()\n"+ "requests.patch('u')\n",+ "import requests\n"+ "import this_package.this_module as me\n"+ "me.requests = get_logger()\n"+ "requests.patch('u')\n",+ ):+ self._assert_final_patch_flagged(code)++ def test_import_poisoning_before_the_import(self):+ self._assert_final_patch_flagged(+ "import sys\n"+ "sys.modules['requests'] = get_logger()\n"+ "import requests\n"+ "requests.patch('u')\n"+ )++ def test_module_attribute_replacement(self):+ for code in (+ "import requests\n"+ "requests.patch = get_logger().info\n"+ "requests.patch('u')\n",+ "import httpx\n"+ "import httpx as client\n"+ "client.patch = get_logger().info\n"+ "httpx.patch('u')\n",+ ):+ self._assert_final_patch_flagged(code)++ def test_string_resolvers_and_code_runners_revoke(self):+ for code in (+ "import requests, gc\n"+ "gc.get_referrers(requests)[0]['requests'] = get_logger()\n"+ "requests.patch('u')\n",+ "import requests, cProfile\n"+ "cProfile.run('requests = get_logger()')\n"+ "requests.patch('u')\n",+ "import requests\n"+ "from unittest.mock import patch as p\n"+ "p(__name__ + '.requests', get_logger()).start()\n"+ "requests.patch('u')\n",+ "import requests\n"+ "import typing\n"+ 'def f(x: "sys.modules[__name__].__setattr__(1, 2)"):\n'+ " pass\n"+ "typing.get_type_hints(f)\n"+ "requests.patch('u')\n",+ ):+ self._assert_final_patch_flagged(code)++ def test_revocation_is_named_in_the_diagnostic(self):+ errors = _check_code(+ "import httpx\ndef f():\n return 1\nvars(f)\nhttpx.patch('u')\n",+ IN_DIR,+ )+ assert any(+ "httpx.patch exemption is revoked for this file by vars on line 4"+ in e+ for e in errors+ ), errors++ def test_plain_http_client_patch_still_exempt(self):+ # The exemption's reason to exist (#4976): a realistic client+ # module with no namespace-reaching spelling stays clean.+ for code in (+ "import httpx\n"+ "httpx.patch('https://example.test/item', json={'a': 1})\n",+ "import httpx\n"+ "\n"+ "\n"+ "def update(url, payload, timeout=10):\n"+ " response = httpx.patch(url, json=payload, timeout=timeout)\n"+ " code = response.status_code\n"+ " if code >= 400:\n"+ " return None\n"+ " return getattr(response, 'text', '')\n",+ "import requests\n"+ "\n"+ "\n"+ "class Client:\n"+ " def __init__(self, base):\n"+ " self.base = base\n"+ "\n"+ " def update(self, path, data):\n"+ " return requests.patch(self.base + path, data=data)\n",+ ):+ assert _check_code(code, IN_DIR) == [], code+++class TestPatchExemptionStructuralConditions:+ """Structural conditions on the requests/httpx ``.patch`` exemption.++ The vocabulary denylist alone missed a class namespace supplied by a+ metaclass ``__prepare__`` (class keywords, or a base class's+ metaclass), a module class swap through an alias, and a function+ defined before the import that runs first. Each fixture here must be+ flagged on its ``.patch`` line, as on main.+ """++ @staticmethod+ def _assert_patch_flagged(code, needle=""):+ line = next(+ i for i, text in enumerate(code.split("\n"), 1) if ".patch(" in text+ )+ errors = _check_code(code, IN_DIR)+ assert any(+ f":{line}: .patch is banned" in e and needle in e for e in errors+ ), (code, errors)++ def test_class_keywords_revoke_the_exemption(self):+ for code in (+ "import requests\n"+ "\n"+ "\n"+ "def run(sink, secret):\n"+ " class _C(metaclass=_Meta, requests=sink):\n"+ " pass\n"+ " requests.patch('leak {}', secret)\n",+ "import requests\n"+ "\n"+ "\n"+ "class _C(Base, lg=sink):\n"+ " pass\n"+ "\n"+ "\n"+ "def run(secret):\n"+ " requests.patch('leak {}', secret)\n",+ ):+ self._assert_patch_flagged(code, "keywords on class _C")++ def test_class_scope_reference_never_exempt(self):+ # The class namespace comes from the metaclass, possibly one a+ # base class inherits from another module.+ for code in (+ "import requests\n"+ "from .base import Base\n"+ "\n"+ "\n"+ "def run(secret):\n"+ " class _C(Base):\n"+ " requests.patch('leak {}', secret)\n",+ "import httpx\n"+ "from .base import Base\n"+ "\n"+ "\n"+ "class _C(Base):\n"+ " @httpx.patch('u')\n"+ " def f(self):\n"+ " pass\n",+ ):+ self._assert_patch_flagged(code, "inside a class body")++ def test_reference_before_the_import_revokes(self):+ for code in (+ "import sys\n"+ "\n"+ "\n"+ "def _late(secret):\n"+ " requests.patch('leak {}', secret)\n"+ "\n"+ "\n"+ "_late('SECRET')\n"+ "import requests # noqa: E402\n",+ "import httpx\n"+ "run = lambda u: requests.patch(u)\n"+ "import requests # noqa: E402\n",+ ):+ self._assert_patch_flagged(code, "before import requests")++ def test_dunder_attribute_write_revokes(self):+ for code in (+ "import requests\n"+ "\n"+ "\n"+ "def run(sink, secret):\n"+ " m = requests\n"+ " m.__doc__ = sink\n"+ " requests.patch('leak {}', secret)\n",+ "import requests\n"+ "\n"+ "\n"+ "def run(sink, secret):\n"+ " m = requests\n"+ "\n"+ " class _Evil(type(m)):\n"+ " patch = property(lambda self: sink)\n"+ "\n"+ " m.__class__ = _Evil\n"+ " requests.patch('leak {}', secret)\n",+ ):+ self._assert_patch_flagged(code)++ def test_frame_and_module_hook_spellings_revoke(self):+ for code in (+ "import sys\n"+ "import requests\n"+ "\n"+ "\n"+ "def _late(secret):\n"+ " requests.patch('leak {}', secret)\n"+ "\n"+ "\n"+ "sys._getframe().f_builtins['requests'] = LOG\n",+ "import requests\n"+ "\n"+ "\n"+ "def run(tb, secret):\n"+ " tb.tb_frame.f_back\n"+ " requests.patch('leak {}', secret)\n",+ "import requests\n"+ "\n"+ "\n"+ "def __getattr__(name):\n"+ " return LOG\n"+ "\n"+ "\n"+ "def run(secret):\n"+ " requests.patch('leak {}', secret)\n",+ "import requests\n"+ "\n"+ "\n"+ "def run(gen, secret):\n"+ " gen.gi_code\n"+ " requests.patch('leak {}', secret)\n",+ ):+ self._assert_patch_flagged(code, "exemption is revoked")++ def test_import_first_function_and_method_still_exempt(self):+ for code in (+ "import httpx\n\n\ndef update(url):\n return httpx.patch(url)\n",+ "import requests\n"+ "\n"+ "\n"+ "class Client:\n"+ " def update(self, url):\n"+ " return requests.patch(url, timeout=lambda: requests.codes)\n",+ ):+ assert _check_code(code, IN_DIR) == [], code++ def test_module_used_as_a_value_revokes(self):+ # The module object handed to code this rule cannot follow can+ # be mutated there: functools.update_wrapper copies the logger's+ # ``patch`` onto it with no denylisted spelling in the file.+ # Any load of the bare name other than as an attribute receiver+ # revokes the exemption.+ self._assert_patch_flagged(+ "import functools\n"+ "import requests\n"+ "from ...security.secure_logging import logger\n"+ "functools.update_wrapper("+ "requests, logger, assigned=('patch',), updated=())\n"+ "requests.patch(lambda record: record)\n",+ "requests used as a value on line 4",+ )+ for code in (+ "import requests\nhelper(requests)\nrequests.patch('u')\n",+ "import httpx\nhelper(client=httpx)\nhttpx.patch('u')\n",+ "import requests\nm = requests\nrequests.patch('u')\n",+ "import requests\n"+ "\n"+ "\n"+ "def get():\n"+ " return requests\n"+ "\n"+ "\n"+ "requests.patch('u')\n",+ "import httpx\nmods = [httpx]\nhttpx.patch('u')\n",+ ):+ self._assert_patch_flagged(code, "used as a value")++ def test_aliased_module_import_revokes(self):+ # A second name bound to the same module object walks around the+ # bare-name value-use check: ``rq is requests`` at runtime, so+ # update_wrapper(rq, ...) replaces requests.patch. Any aliased+ # import of requests/httpx, at any scope, revokes the exemption.+ self._assert_patch_flagged(+ "import functools\n"+ "import requests\n"+ "import requests as rq\n"+ "from ...security.secure_logging import logger\n"+ "functools.update_wrapper("+ "rq, logger, assigned=('patch',), updated=())\n"+ "requests.patch(lambda r: r)\n",+ "requests imported as rq on line 3",+ )+ self._assert_patch_flagged(+ "import functools\n"+ "import requests\n"+ "from ...security.secure_logging import logger\n"+ "\n"+ "\n"+ "def f():\n"+ " import requests as rq\n"+ "\n"+ " functools.update_wrapper("+ "rq, logger, assigned=('patch',), updated=())\n"+ "\n"+ "\n"+ "f()\n"+ "requests.patch(lambda r: r)\n",+ "requests imported as rq on line 7",+ )+ for code in (+ "import httpx\nimport httpx as hx\nhttpx.patch('u')\n",+ "import requests\nimport requests.sessions as s\n"+ "requests.patch('u')\n",+ "import requests\nfrom pkg import requests as r2\n"+ "requests.patch('u')\n",+ ):+ self._assert_patch_flagged(code, "imported")++class TestWrapperChainMessageChecks:"""bind() chains keep the wrapper but messages stay checked."""@@ -1400,6 +2821,13 @@ class TestSourceTreeInvariant:def test_no_banned_attribute_or_getattr_access_in_tree(self):"""Attribute/literal-getattr shapes only — a FunctionDef named__getattr__ (rate_limiting/llm/wrapper.py) must not trip this."""+ # Fail closed, mirroring the hook: opt/catch are receiver-blind+ # (always banned). patch has exactly one narrow, provably-safe+ # exception — a bare name genuinely bound by a top-level+ # `import requests`/`import httpx`, never rebound anywhere in the+ # file, in a file free of namespace-reaching spellings+ # (SAFE_PATCH_RECEIVER_MODULES in the hook).+ patch_only = {"patch"}banned_attrs = {"opt","catch",@@ -1410,6 +2838,9 @@ class TestSourceTreeInvariant:"__getattr__",}+ def is_safe_patch_receiver(expr, safe_names):+ return isinstance(expr, ast.Name) and expr.id in safe_names+def is_literal_dynamic_sys_import(expr):if not isinstance(expr, ast.Call) or not expr.args:return False@@ -1446,13 +2877,23 @@ class TestSourceTreeInvariant:and alias.asname is None):sys_names.add(alias.asname or "sys")+ checker = SensitiveLoggingChecker(str(path))+ checker.visit(tree)+ safe_names = checker._safe_patch_receiver_names+ getattr_names = checker._getattr_namesfor node in ast.walk(tree):if isinstance(node, ast.FunctionDef) and (node.name == "__getattr__"):saw_dunder_getattr_def = Trueif isinstance(node, ast.Attribute):- if node.attr in banned_attrs:+ if node.attr in patch_only and is_safe_patch_receiver(+ node.value, safe_names+ ):+ # requests.patch(...)/httpx.patch(...) — the one+ # narrow, provably-safe exception. Allowed.+ pass+ elif node.attr in banned_attrs:failures.append(f"{path}:{node.lineno}: .{node.attr} access")@@ -1481,7 +2922,7 @@ class TestSourceTreeInvariant:elif (isinstance(node, ast.Call)and isinstance(node.func, ast.Name)- and node.func.id == "getattr"+ and node.func.id in getattr_namesand len(node.args) >= 2and isinstance(node.args[1], ast.Constant)and isinstance(node.args[1].value, str)@@ -1492,6 +2933,12 @@ class TestSourceTreeInvariant:and is_sys_module_expr(node.args[0], sys_names)))+ # Fail closed: banned unless it is the narrow, safe+ # getattr(requests/httpx, "patch") exception.+ and not (+ node.args[1].value in patch_only+ and is_safe_patch_receiver(node.args[0], safe_names)+ )):failures.append(f"{path}:{node.lineno}: literal getattr dodge"