~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: avoid annotation false positives in architecture fences (#7063)
LearningCircuit333eadf446b6
diff --git a/.pre-commit-hooks/check-per-user-isolation.py b/.pre-commit-hooks/check-per-user-isolation.pyindex 27be4f006a..ebaa1739f5 100755--- a/.pre-commit-hooks/check-per-user-isolation.py+++ b/.pre-commit-hooks/check-per-user-isolation.py@@ -61,17 +61,72 @@ walrus or lambda inside it (``x: (s := get_user_db_session) = 1`` bindsthe constructor in the enclosing scope), a class field with no bindingin its own class body on a class with a base other than ``object`` /``Generic`` / ``Protocol`` (it may inherit a ``Depends()`` default), or-a string that does not parse. A string in a type position that does-not parse as an expression (``"*[NoteService]"`` is a valid ForwardRef-but not an expression) or nests deeper than ``_MAX_QUOTE_DEPTH`` is-also reported on its own, as an annotation string that cannot be-checked (strings that are plain values -- call arguments, ``Literal``-members, ``Annotated`` metadata -- are not). Every string in a type position is-parsed and checked like unquoted code, recursively, since FastAPI-evaluates it: a wholly quoted ``"Annotated[NoteService, Depends()]"``-is as live as the unquoted form (``Annotated`` metadata strings are-plain values and are not parsed). An attribute read off a-constructor is a non-call reference too (``NoteService.__call__``,+a string, other than an exempt one (below), that does not parse. Every+string inside such an annotation is parsed and checked like unquoted+code, recursively, since FastAPI evaluates it -- a wholly quoted+``"Annotated[NoteService, Depends()]"`` is as live as the unquoted form+-- unless it is exempt. Exemption is an allowlist of shapes (see+``_approved_children``), so whatever it does not name fails closed: a+string is exempt only if every step of its path from the annotation's+root is approved -- subscripts of a proven generic head (``Optional``,+``Union``, ``list`` ...) and the first element of a proven ``Annotated``+whose metadata is inert (each element a constant, a call of a proven+listed callee or a dict display: pydantic hands the first element to any+other metadata object's ``__get_pydantic_core_schema__``), then one last+step -- and it ends as a string member of a proven ``Literal[...]``; as+metadata of such an ``Annotated`` (an element after the first, where the+key has two or more elements and none is starred); as a string passed+directly, in that metadata or in a type slot, to an argument+``VALUE_ARGUMENTS`` lists, of a proven callee+(``Query(description="...")``, ``NewType("Name", str)``,+``ForwardRef("T", module="...")``); or as a string key or value of a+dict display in that metadata. Any other node on the path -- an+attribute read, a subscript of another head, an operator or comparison,+an unlisted call, a lambda, walrus, conditional, starred or formatted+value -- ends it, and every string below it is checked, whatever reads+the string back out: ``Literal["NoteService"].__args__[0]``, ``G |+Literal["NoteService"]``, ``G[Literal["NoteService"]]``,+``f"{Literal['NoteService']}"``, ``Annotated[*(), "NoteService",+Depends()]`` and ``Annotated[Literal["NoteService"], G]`` can each hand+the string on to a type position, which FastAPI resolves. ``Literal``+and ``Annotated`` are proven only when imported from ``typing`` or+``typing_extensions`` (``PLAIN_FORMS``), a ``VALUE_ARGUMENTS`` callee+only when imported from its own module (``from fastapi import Query [as+Q]``, or ``fastapi.Query`` after ``import fastapi``), and a generic head+only from ``typing``, ``typing_extensions`` or ``collections.abc`` or as+an unbound builtin, each under a name nothing else in the file binds+(after ``from typing import Annotated as Literal``,+``Literal["NoteService", Depends()]`` is checked as the ``Annotated`` it+is). Nothing in a file is proven if it could change what a proven name+denotes (see ``_proven_names``): a star import; a reference to a name+that can look up or rewrite a namespace dynamically (such as+``setattr``, ``vars``, ``globals``, ``locals``, ``__dict__``,+``sys.modules``, ``importlib``, ``exec`` or ``eval``); an attribute or+item store or delete rooted in an imported name (``typing.Literal =+...``), in an unbound name or in an expression; on any object, a store+or delete whose target attribute is named like something a proof rests+on (``mod.Literal = ...``), or whose target goes through a dunder or a+private attribute of anything but ``self`` / ``cls``; a proven module,+or one a proof rests on reached as an attribute, used other than to read+an attribute off it (``mod = typing``, ``mod =+typing_extensions.typing``), or a private name of one; or a proven form,+listed callee or subscripted generic head used outside a type position+(``L = Literal``, ``type(typing.List)``). Every other call argument is+checked, so an unknown call fails closed: ``typing.cast(object,+"NoteService")`` hands its string on to a type position, which FastAPI+resolves. ``ForwardRef``'s type argument is a type position, under any+name it is imported as or qualified. A string is parsed as it is (as+``ForwardRef`` compiles it, so ``"NoteService"`` followed by a line+continuation is checked) and stripped. A string in a type position that+parses neither way (``"*[NoteService]"`` is a valid ForwardRef but not+an expression), or one nested deeper than ``_MAX_QUOTE_DEPTH``, is also+reported on its own, as an annotation string that cannot be checked;+elsewhere -- a call argument, or a ``Literal`` member or ``Annotated``+metadata that is not exempt -- a string is also parsed the way+``ForwardRef`` reads ``"*[NoteService]"``, and one that parses no way is+not reported (``typing`` cannot resolve it; it may be a regex). An+attribute read off a constructor is a non-call reference too+(``NoteService.__call__``,``get_user_db_session.__wrapped__``, ``NoteService.__new__(...)``,``FollowUpResearchService.__call__()``, ``NoteService.some_method``),since the attribute can be, or can produce, the unchecked constructor;@@ -90,7 +145,16 @@ lookups (``getattr``, ``importlib``, ``__import__``, ``globals()`` /``module.__dict__[...]``, ``eval``); ``Annotated`` reached through anassignment alias (``A = Annotated``) with non-call metadata(``svc: A[NoteService, dep]``; an ``import ... as`` alias is-recognised); and constant-valued non-literal ``username=`` expressions+recognised); a ``VALUE_ARGUMENTS`` callee, ``PLAIN_FORMS`` form or+generic head changed from another module, through a dynamic lookup that+uses none of the names above (``getattr(m, "Lit" + "eral")``), through a+name used only inside a quoted annotation, or through an object derived+from it at runtime (``type(Literal["x"])``), whose exempt strings stay+unparsed; code that rewrites ``__annotations__`` after the fact, such as+a decorator, which no check of an annotation as written can see; a class+name assembled from pieces as the annotation is evaluated (``"Note" ++"Service"``, ``f"{'Note'}Service"``), since each string is checked on+its own; and constant-valued non-literal ``username=`` expressions(above). Itdoes NOT check where that username came from: ``NoteService(victim_username)`` or ``get_user_db_session(username=request.@@ -237,25 +301,26 @@ def _resolve(node: ast.AST, aliases: dict[str, str]) -> str | None:_EVALUATED = (ast.Call, ast.NamedExpr, ast.Lambda)-def _annotated_names(tree: ast.AST) -> set[str]:- """``Annotated`` plus every local name it is imported as."""- names = {"Annotated"}+def _annotation_names(tree: ast.AST, name: str) -> set[str]:+ """``name`` plus every local name it is imported as."""+ names = {name}for node in ast.walk(tree):if isinstance(node, ast.ImportFrom):names.update(alias.asnamefor alias in node.names- if alias.name == "Annotated" and alias.asname+ if alias.name == name and alias.asname)return names#: Nesting bound for quoted annotations (a string inside a string ...):#: a string nested deeper than this counts as evaluated (fail closed)-#: and, in a type position, is reported as unchecked.+#: and is reported as unchecked (an exempt string is never parsed)._MAX_QUOTE_DEPTH = 8-#: Offender text for a string in a type position the hook cannot check.+#: Offender text for a string the hook cannot check: one in a type+#: position that does not parse, or one nested too deep._UNCHECKED_STRING = ("annotation string that cannot be checked (it does not parse as an ""expression, or quotes nest deeper than "@@ -265,8 +330,10 @@ _UNCHECKED_STRING = (def _is_literal_head(node: ast.AST) -> bool:- """True if ``node`` is ``Literal[...]`` (bare or qualified): its- strings are values, never evaluated as types."""+ """True if ``node`` is a subscript of a name spelled ``Literal`` (bare+ or qualified), whatever that name is bound to. Only a ``Literal``+ that ``_plain_form`` proves can hold exempt strings (see+ ``_approved_children``)."""if not isinstance(node, ast.Subscript):return Falsehead = node.value@@ -276,8 +343,12 @@ def _is_literal_head(node: ast.AST) -> bool:def _is_annotated_head(node: ast.AST, annotated: set[str]) -> bool:- """True if ``node`` is a subscript of ``Annotated`` (under any import- alias, or qualified as ``typing.Annotated``)."""+ """True if ``node`` is a subscript of a name spelled ``Annotated``+ (under any import alias, or qualified as ``typing.Annotated``),+ whatever that name is bound to. ``_has_evaluated_metadata`` checks+ every such subscript (fail closed); only an ``Annotated`` that+ ``_plain_form`` proves can hold exempt strings (see+ ``_approved_children``)."""if not isinstance(node, ast.Subscript):return Falsehead = node.value@@ -286,81 +357,778 @@ def _is_annotated_head(node: ast.AST, annotated: set[str]) -> bool:)+#: Call arguments that only ever hold a plain value -- documentation, an+#: alias, a regex, example values, a ``NewType`` name or a module name --+#: which the callee (from FastAPI, pydantic or ``typing``) itself never+#: evaluates as a type and never calls, as ``{callee: positions}`` (an+#: index for a positional argument, a name for a keyword). A string+#: literal passed there directly is exempt from parsing only where the+#: call sits on an approved path and the callee is provably the listed+#: one (see ``_approved_children`` and ``_proven_names``); every other+#: argument is parsed and checked, so an unknown call fails closed. The+#: entries match the signatures of FastAPI 0.136, pydantic 2.13 and+#: Python 3.12 to 3.14; ``test_value_arguments_match_the_signatures`` in+#: tests/security/test_architecture_fences.py checks them against the+#: installed ones. ``ForwardRef``'s position 2 is ``module`` before+#: Python 3.14, which makes it keyword-only.+_PARAMETER_TEXT = frozenset(+ {"alias", "title", "description", "pattern", "regex", "example", "examples"}+)+VALUE_ARGUMENTS: dict[str, frozenset[int | str]] = {+ **{+ f"fastapi.{name}": _PARAMETER_TEXT+ for name in (+ "Query",+ "Path",+ "Header",+ "Cookie",+ "Body",+ "Form",+ "File",+ )+ },+ "fastapi.Depends": frozenset({"scope"}),+ "pydantic.Field": frozenset(+ {"alias", "title", "description", "pattern", "examples"}+ ),+ "pydantic.constr": frozenset({"pattern"}),+ "typing.NewType": frozenset({0, "name"}),+ "typing.ForwardRef": frozenset({2, "module"}),+}++#: Modules whose import makes ``module.callee`` a ``VALUE_ARGUMENTS`` callee.+_VALUE_MODULES = frozenset(+ callee.rpartition(".")[0] for callee in VALUE_ARGUMENTS+)++#: Subscript forms that can hold exempt strings, as ``module.name``: the+#: string members of ``Literal[...]`` and the metadata of+#: ``Annotated[...]`` (its elements after the first), which ``typing``+#: and FastAPI keep as values. Like a ``VALUE_ARGUMENTS`` callee, a form+#: counts only under a name ``_proven_names`` proves is imported from+#: its module, and only on an approved path (see ``_approved_children``).+PLAIN_FORMS = frozenset(+ f"{module}.{form}"+ for module in ("typing", "typing_extensions")+ for form in ("Literal", "Annotated")+)++#: Modules whose import makes ``module.Literal`` / ``module.Annotated`` a+#: ``PLAIN_FORMS`` form.+_FORM_MODULES = frozenset(form.rpartition(".")[0] for form in PLAIN_FORMS)++#: Modules whose subscriptable names (``Optional``, ``List``,+#: ``Sequence``, ``Literal`` ...) keep the key of a subscript a type+#: argument: subscripting one never hands its key to the project's code,+#: so it is a step of an approved path (see ``_approved_children``).+_GENERIC_MODULES = frozenset({"typing", "typing_extensions", "collections.abc"})++#: Builtins that keep the key of a subscript a type argument+#: (``list[T]``), where nothing in the file binds the name. Their types+#: cannot be changed, only the names rebound.+_GENERIC_BUILTINS = frozenset(+ {"list", "dict", "set", "frozenset", "tuple", "type"}+)++#: What ``_proven_names`` can prove a name denotes (and any name of a+#: ``_GENERIC_MODULES`` module).+_PROVABLE = frozenset(+ {+ *VALUE_ARGUMENTS,+ *_VALUE_MODULES,+ *PLAIN_FORMS,+ *_FORM_MODULES,+ *_GENERIC_MODULES,+ }+)++#: The modules a proof can rest on, and the last part of each module's+#: name, by which an attribute read can reach the module from another+#: one (``typing_extensions.typing``).+_PROOF_MODULES = _VALUE_MODULES | _FORM_MODULES | _GENERIC_MODULES+_PROOF_MODULE_NAMES = frozenset(+ module.rpartition(".")[2] for module in _PROOF_MODULES+)++#: Names through which a file can reach or rewrite a namespace -- a+#: module's, a class's, the builtins or ``sys.modules`` -- without naming+#: what it replaces (``setattr(typing, "Literal", ...)``,+#: ``vars(typing)[...]``, ``typing.__dict__[...]``, ``sys.modules[...]``,+#: ``importlib.import_module("typing")``, ``exec(...)``). A reference to+#: one, as a name, an attribute of anything or a part of an import,+#: voids every proof in the file (see ``_proven_names``).+_DYNAMIC_NAMES = frozenset(+ {+ "__builtins__",+ "__delattr__",+ "__dict__",+ "__import__",+ "__setattr__",+ "delattr",+ "eval",+ "exec",+ "globals",+ "import_module",+ "importlib",+ "locals",+ "modules",+ "setattr",+ "vars",+ }+)++#: Definitions that bind their own name.+_NAMED_DEFINITIONS = (+ ast.FunctionDef,+ ast.AsyncFunctionDef,+ ast.ClassDef,+ ast.ExceptHandler,+ ast.MatchAs,+ ast.MatchStar,+ ast.TypeVar,+ ast.ParamSpec,+ ast.TypeVarTuple,+)+++def _proven_names(tree: ast.AST) -> dict[str, str]:+ """Local names that provably denote a ``VALUE_ARGUMENTS`` callee, a+ ``PLAIN_FORMS`` form, a name of a ``_GENERIC_MODULES`` module, a+ ``_GENERIC_BUILTINS`` builtin, or one of these modules: ``{"Q":+ "fastapi.Query", "fastapi": "fastapi", "Literal": "typing.Literal",+ "list": "builtins.list"}``.++ A name counts only if each import binding it in the file is the same+ ``from <module> import <name> [as <local>]`` (or ``import <module>+ [as <local>]``; a builtin, only if nothing imports it) and nothing+ else in the file binds it -- an assignment or ``del``, a ``def``,+ ``class``, parameter, ``for`` / ``with`` / ``except`` / ``match``+ target, walrus, ``global`` / ``nonlocal`` or type parameter (no+ scope tracking; fail closed) -- so a local pass-through that happens+ to be called ``Query`` is an unknown callee, and ``Literal =+ typing.Annotated`` is not a ``Literal``.++ Nothing in the file is proven at all (fail closed: every string is+ then checked) if it contains any of these, through which it could+ change what a proven name denotes:++ * a star import;+ * a ``_DYNAMIC_NAMES`` name, as a name, as an attribute of anything+ or imported by name (``setattr(typing, "Literal", ...)``,+ ``vars(typing)[...]``, ``typing.__dict__[...]``,+ ``sys.modules[...]``, ``exec(...)``, ``from importlib import+ import_module``);+ * a store or delete (an assignment, augmented assignment or+ ``del``, a loop or ``with`` target) of an attribute or item that+ is rooted in an imported name (``typing.Literal = ...``,+ ``builtins.list = ...``, ``Query.__code__ = ...``), in a name the+ file never binds, or in anything but a name+ (``type(Literal).__getitem__ = ...``);+ * a store or delete, on any object, of an attribute named like+ anything a proof could rest on -- the last part of a+ ``PLAIN_FORMS`` or ``VALUE_ARGUMENTS`` name, a+ ``_GENERIC_BUILTINS`` name, or the last part of a name proven here+ or read off a proven module (``mod.Literal = ...``, ``b.list =+ ...``, ``t.Optional = ...``) -- or one whose target reads a dunder+ attribute (``c.__getitem__ = ...``, ``a.__class__.x = ...``) or a+ ``_``-private attribute of anything but ``self`` or ``cls``+ (``L._getitem = ...``);+ * a proven module referenced other than as the object of an+ attribute read (``mod = typing``, ``getattr(typing, ...)``), an+ attribute named like a module a proof rests on (``typing``,+ ``typing_extensions``, ``fastapi``, ``pydantic``, ``abc``) read+ other than as the object of another attribute read+ (``t = typing_extensions.typing``), or a ``_``-private name read+ off a proven module or imported from a module a proof rests on+ (``typing._SpecialForm``, ``from typing import _GenericAlias``);+ * a ``PLAIN_FORMS`` form, a ``VALUE_ARGUMENTS`` callee or a generic+ head the file subscripts, referenced -- under a name proven to+ denote it, or as an attribute of a proven module -- other than in+ a type position: the head of a subscript, the callee of a call, a+ whole annotation (``-> Dict``), or the key, or an element of the+ key, of a subscript whose head is proven (``List[Dict]``,+ ``dict[str, Dict]``). So ``L = Literal``, ``type(typing.List)``,+ ``partial(Query, ...)`` or ``isinstance(x, Mapping)`` in a file+ that subscripts ``Mapping`` voids every proof.++ Not seen (deliberate evasion, beyond a per-file syntax check): a+ form, callee or generic head changed from another module, through a+ dynamic lookup (``getattr(m, "Lit" + "eral")``), through a name used+ only inside a quoted annotation, or through an object derived from it+ at runtime (``type(Literal["x"])``) whose public attributes are then+ replaced."""+ imported: dict[str, set[str]] = {}+ bound: set[str] = set()+ # Attribute and item store / delete targets; every load of a name or+ # attribute with the node holding it; annotation roots; and each+ # tuple that is a subscript's key, with the subscript.+ targets: list[ast.AST] = []+ loads: list[tuple[ast.AST, ast.AST]] = []+ annotations: set[int] = set()+ keys: dict[int, ast.Subscript] = {}+ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom):+ module = f"{'.' * node.level}{node.module or ''}"+ for alias in node.names:+ if (+ alias.name == "*"+ or alias.name in _DYNAMIC_NAMES+ or (alias.name.startswith("_") and module in _PROOF_MODULES)+ ):+ return {}+ imported.setdefault(alias.asname or alias.name, set()).add(+ f"{module}.{alias.name}"+ )+ elif isinstance(node, ast.Import):+ for alias in node.names:+ local = alias.asname or alias.name.partition(".")[0]+ source = alias.name if alias.asname else local+ imported.setdefault(local, set()).add(source)+ elif isinstance(node, ast.arg):+ bound.add(node.arg)+ if node.annotation is not None:+ annotations.add(id(node.annotation))+ elif isinstance(node, (ast.Global, ast.Nonlocal)):+ bound.update(node.names)+ elif isinstance(node, ast.MatchMapping):+ if node.rest:+ bound.add(node.rest)+ elif isinstance(node, ast.AnnAssign):+ annotations.add(id(node.annotation))+ elif isinstance(node, ast.Subscript) and isinstance(+ node.slice, ast.Tuple+ ):+ keys[id(node.slice)] = node+ if isinstance(node, _NAMED_DEFINITIONS) and node.name:+ bound.add(node.name)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and (+ node.returns is not None+ ):+ annotations.add(id(node.returns))+ for child in ast.iter_child_nodes(node):+ if isinstance(child, ast.Name):+ spelled = child.id+ elif isinstance(child, ast.Attribute):+ spelled = child.attr+ elif isinstance(child, ast.Subscript):+ if not isinstance(child.ctx, ast.Load):+ targets.append(child)+ continue+ else:+ continue+ if spelled in _DYNAMIC_NAMES:+ return {}+ if isinstance(child.ctx, ast.Load):+ loads.append((child, node))+ elif isinstance(child, ast.Name):+ bound.add(child.id)+ else:+ targets.append(child)+ names: dict[str, str] = {}+ for name, sources in imported.items():+ if len(sources) != 1 or name in bound:+ continue+ (source,) = sources+ if source in _PROVABLE or source.rpartition(".")[0] in _GENERIC_MODULES:+ names[name] = source+ for name in _GENERIC_BUILTINS - imported.keys() - bound:+ names[name] = f"builtins.{name}"+ modules = {+ name for name, source in names.items() if source in _PROOF_MODULES+ }++ def denotes(node: ast.AST) -> str:+ """What ``node`` denotes by ``names``, or ``""``."""+ return _proven_name(node, names, _PROOF_MODULES) or ""++ # The last part of everything a proof here could rest on, and of the+ # forms, callees and generic heads to be used only in type positions.+ relied = {+ source.rpartition(".")[2]+ for source in (*VALUE_ARGUMENTS, *PLAIN_FORMS, *names.values())+ } | _GENERIC_BUILTINS+ used = {+ source.rpartition(".")[2] for source in (*VALUE_ARGUMENTS, *PLAIN_FORMS)+ }+ for node, parent in loads:+ if (+ isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and node.value.id in modules+ ):+ relied.add(node.attr)+ if node.attr.startswith("_"):+ return {}+ if isinstance(parent, ast.Subscript) and parent.value is node:+ source = denotes(node)+ if (+ source+ and source not in _PROOF_MODULES+ and not (source.startswith("builtins."))+ ):+ used.add(source.rpartition(".")[2])+ for target in targets:+ root = target+ while isinstance(root, (ast.Attribute, ast.Subscript)):+ root = root.value+ if (+ not isinstance(root, ast.Name)+ or root.id in imported+ or root.id not in bound+ ):+ return {}+ if isinstance(target, ast.Attribute) and target.attr in relied:+ return {}+ step = target+ while isinstance(step, (ast.Attribute, ast.Subscript)):+ if (+ isinstance(step, ast.Attribute)+ and step.attr.startswith("_")+ and (step.attr.endswith("__") or root.id not in ("self", "cls"))+ ):+ return {}+ step = step.value+ for node, parent in loads:+ if isinstance(parent, ast.Attribute) and parent.value is node:+ if isinstance(node, ast.Name) and node.id in modules:+ continue+ elif isinstance(node, ast.Name) and node.id in modules:+ return {}+ elif (+ isinstance(node, ast.Attribute) and node.attr in _PROOF_MODULE_NAMES+ ):+ return {}+ source = denotes(node)+ if (+ not source+ or source in _PROOF_MODULES+ or source.startswith("builtins.")+ or source.rpartition(".")[2] not in used+ ):+ continue+ subscript = keys.get(id(parent), parent)+ if not (+ (isinstance(parent, ast.Subscript) and parent.value is node)+ or (isinstance(parent, ast.Call) and parent.func is node)+ or id(node) in annotations+ or (+ isinstance(subscript, ast.Subscript)+ and node is not subscript.value+ and denotes(subscript.value)+ )+ ):+ return {}+ return names+++def _proven_name(+ node: ast.AST, proven: dict[str, str], modules: frozenset[str]+) -> str | None:+ """What ``node`` provably denotes (see ``_proven_names``): a proven+ name, or an attribute of a name proven to be one of ``modules``+ (``fastapi.Query``), as ``module.name``; else None."""+ if isinstance(node, ast.Name):+ return proven.get(node.id)+ if (+ isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and proven.get(node.value.id) in modules+ ):+ return f"{proven[node.value.id]}.{node.attr}"+ return None+++def _value_callee(func: ast.AST, proven: dict[str, str]) -> str | None:+ """The ``VALUE_ARGUMENTS`` callee ``func`` provably names (``Query``,+ an alias ``Q``, or ``fastapi.Query``; see ``_proven_names``), or+ None."""+ callee = _proven_name(func, proven, _VALUE_MODULES)+ return callee if callee in VALUE_ARGUMENTS else None+++def _plain_form(node: ast.AST, proven: dict[str, str]) -> str | None:+ """``"Literal"`` or ``"Annotated"`` if ``node`` is a subscript of that+ ``PLAIN_FORMS`` form under a name ``_proven_names`` proves+ (``Literal``, an alias ``L``, or ``typing.Literal``), else None."""+ if not isinstance(node, ast.Subscript):+ return None+ form = _proven_name(node.value, proven, _FORM_MODULES)+ return form.rpartition(".")[2] if form in PLAIN_FORMS else None+++def _generic_head(head: ast.AST, proven: dict[str, str]) -> bool:+ """True if ``head`` provably names something of a ``_GENERIC_MODULES``+ module or a ``_GENERIC_BUILTINS`` builtin (``Optional``,+ ``typing.List``, ``list``; see ``_proven_names``), whose subscript+ keeps its key a type argument."""+ name = _proven_name(head, proven, _GENERIC_MODULES)+ return name is not None and (+ name.rpartition(".")[0] in _GENERIC_MODULES+ or name.startswith("builtins.")+ )+++def _is_forward_ref(func: ast.AST, forward_refs: set[str]) -> bool:+ """True if ``func`` is named ``ForwardRef``: bare, under any name it+ is imported as, or qualified (``typing.ForwardRef``)."""+ return (isinstance(func, ast.Name) and func.id in forward_refs) or (+ isinstance(func, ast.Attribute) and func.attr == "ForwardRef"+ )+++def _call_arguments(call: ast.Call) -> list[tuple[ast.AST, int | str | None]]:+ """Each argument of ``call`` with the parameter it binds: an index, a+ keyword, or None where that is unknown.++ Literal unpacking is followed, nested too: ``*("a", "b")`` binds+ indexes and ``**{"k": v}`` binds keyword ``k``. Anything else that is+ unpacked (``*args``, ``**dict(k=v)``, a key that is not a string+ constant) binds None, and so does every positional argument after a+ ``*`` of unknown length. The unpacking syntax itself (the starred+ node, the unpacked tuple, list or dict, and a dict's keys) is listed+ with None too."""+ found: list[tuple[ast.AST, int | str | None]] = []+ index: int | None = 0+ positional = list(reversed(call.args))+ while positional:+ arg = positional.pop()+ if isinstance(arg, ast.Starred):+ found.extend([(arg, None), (arg.value, None)])+ if isinstance(arg.value, (ast.Tuple, ast.List)):+ positional.extend(reversed(arg.value.elts))+ else:+ index = None+ continue+ found.append((arg, index))+ if index is not None:+ index += 1+ mappings: list[ast.AST] = []+ for kw in call.keywords:+ if kw.arg is None:+ mappings.append(kw.value)+ else:+ found.append((kw.value, kw.arg))+ while mappings:+ mapping = mappings.pop()+ found.append((mapping, None))+ if not isinstance(mapping, ast.Dict):+ continue+ for key, value in zip(mapping.keys, mapping.values):+ if key is None:+ mappings.append(value)+ continue+ found.append((key, None))+ named = isinstance(key, ast.Constant) and isinstance(key.value, str)+ found.append((value, key.value if named else None))+ return found+++def _parse_expression(text: str) -> ast.AST | None:+ """``text`` parsed as an expression, or None if it does not parse."""+ try:+ return ast.parse(text, mode="eval").body+ except (SyntaxError, ValueError, RecursionError, MemoryError):+ return None+++def _parse_string(text: str, star: bool) -> list[ast.AST]:+ """The distinct trees ``text`` parses to as an expression, trying it+ as it is (``ForwardRef`` compiles the raw string, so one ending in a+ line continuation -- a backslash and a newline -- is valid there)+ and with surrounding whitespace stripped (``eval`` strips leading+ spaces). With ``star``, each of the two that does not parse is also+ tried the way ``ForwardRef`` reads a string starting with ``*``, as+ ``({text},)[0]`` (``"*[T]"``), which also tolerates leading+ whitespace before a line continuation. Empty only if every attempt+ fails."""+ trees: dict[str, ast.AST] = {}+ for form in (text, text.strip()):+ parsed = _parse_expression(form)+ if parsed is None and star:+ parsed = _parse_expression(f"({form},)[0]")+ if parsed is not None:+ trees.setdefault(ast.dump(parsed), parsed)+ return list(trees.values())+++def _is_string(node: ast.AST) -> bool:+ """True if ``node`` is a string literal."""+ return isinstance(node, ast.Constant) and isinstance(node.value, str)+++#: Where a node sits on an approved path from an annotation's root (see+#: ``_approved_children``): a type slot, an ``Annotated`` metadata slot,+#: or an exempt string. A node that has none is off the path.+_TYPE_SLOT, _METADATA_SLOT, _EXEMPT = "type slot", "metadata slot", "exempt"+++def _listed_arguments(call: ast.Call, proven: dict[str, str]) -> list[ast.AST]:+ """The arguments ``VALUE_ARGUMENTS`` lists for the callee that+ ``_value_callee`` proves ``call`` names, passed directly: a keyword+ by its name, a positional argument by its index before any ``*``+ unpacking (nothing inside a ``*`` or ``**`` is listed)."""+ listed = VALUE_ARGUMENTS.get(_value_callee(call.func, proven), frozenset())+ found: list[ast.AST] = []+ for index, argument in enumerate(call.args):+ if isinstance(argument, ast.Starred):+ break+ if index in listed:+ found.append(argument)+ found.extend(kw.value for kw in call.keywords if kw.arg in listed)+ return found+++def _inert_metadata(node: ast.AST, proven: dict[str, str]) -> bool:+ """True if ``node``, as ``Annotated`` metadata, is an object FastAPI+ and pydantic never hand the annotated type to project code through:+ a constant, a call of a callee ``_value_callee`` proves, or a dict+ display with no ``**`` unpacking. Any other object may define+ ``__get_pydantic_core_schema__``, which pydantic calls with the+ type (``Annotated[Literal["T"], G]`` hands ``Literal["T"]`` to+ ``G``, which can read ``"T"`` back out into the type it validates+ with), so its ``Annotated`` approves nothing."""+ return (+ isinstance(node, ast.Constant)+ or (+ isinstance(node, ast.Call)+ and _value_callee(node.func, proven) is not None+ )+ or (isinstance(node, ast.Dict) and None not in node.keys)+ )+++def _approved_children(+ node: ast.AST, slot: str, proven: dict[str, str]+) -> dict[int, str]:+ """The allowlist: ``{id(descendant): slot}`` for what ``node``, on an+ approved path in ``slot`` (see ``_annotation_nodes``), passes the+ path on to. A string literal is exempt from parsing only where a+ rule here makes it ``_EXEMPT``. Whatever no rule names is off the+ path, and so is everything below it, whatever the node kind -- an+ attribute read, an operator, a comparison, an unlisted call, a+ subscript of another head, a lambda, a walrus, a conditional, a+ starred or formatted value -- so every string there is parsed and+ checked. The rules, where proven means provably the ``typing``,+ ``typing_extensions``, ``collections.abc``, builtin, FastAPI or+ pydantic name (see ``_proven_names``):++ * in a type slot, a subscript of a proven ``Literal``: each string+ member of its key is exempt;+ * in a type slot, a subscript of a proven ``Annotated`` whose key is+ a tuple of two or more elements, none starred, with only inert+ metadata (see ``_inert_metadata``): the first element is a type+ slot, and each later one is exempt if it is a string, else a+ metadata slot;+ * in a type slot, a subscript of another proven generic head+ (``Optional``, ``Union``, ``list`` ...; see ``_generic_head``):+ each element of its key is a type slot;+ * in a type or metadata slot, a call of a proven ``VALUE_ARGUMENTS``+ callee: each string passed directly in a listed position is exempt+ (see ``_listed_arguments``);+ * in a metadata slot, a dict display: each string key and value is+ exempt (one with ``**`` unpacking is not inert metadata, so its+ ``Annotated`` approves nothing)."""+ if slot == _TYPE_SLOT and isinstance(node, ast.Subscript):+ key = node.slice+ elements = key.elts if isinstance(key, ast.Tuple) else [key]+ form = _plain_form(node, proven)+ if form == "Literal":+ return {+ id(member): _EXEMPT for member in elements if _is_string(member)+ }+ if form == "Annotated":+ if (+ not isinstance(key, ast.Tuple)+ or len(elements) < 2+ or any(isinstance(e, ast.Starred) for e in elements)+ or not all(_inert_metadata(m, proven) for m in elements[1:])+ ):+ return {}+ return {+ id(elements[0]): _TYPE_SLOT,+ **{+ id(meta): _EXEMPT if _is_string(meta) else _METADATA_SLOT+ for meta in elements[1:]+ },+ }+ if _generic_head(node.value, proven):+ return {id(element): _TYPE_SLOT for element in elements}+ return {}+ if isinstance(node, ast.Call):+ return {+ id(argument): _EXEMPT+ for argument in _listed_arguments(node, proven)+ if _is_string(argument)+ }+ if slot == _METADATA_SLOT and isinstance(node, ast.Dict):+ return {+ id(item): _EXEMPT+ for item in (*node.keys, *node.values)+ if _is_string(item)+ }+ return {}+++#: How ``_annotation_nodes`` checks a string that is not exempt, by where+#: it sits: in a type position it must parse (it is reported if it does+#: not); in the argument context -- a call argument, a ``Literal``+#: member or ``Annotated`` metadata -- it is also parsed the way+#: ``ForwardRef`` reads a starred string, and not reported if it does+#: not parse at all, since it may be a value such as a regex.+_TYPE, _ARGUMENT = "type", "argument"+++def _child_contexts(+ node: ast.AST,+ context: str,+ annotated: set[str],+ forward_refs: set[str],+ proven: dict[str, str],+) -> list[tuple[ast.AST, str]]:+ """``(descendant, context)`` pairs for what ``node``, seen in+ ``context``, contains. The caller keeps the first pair given for a+ node, so the specific ones come first: the string members of a+ ``Literal`` and the metadata of an ``Annotated`` (the form+ ``_plain_form`` proves, else the name it is spelled with; see+ ``_is_literal_head`` and ``_is_annotated_head``) and every argument+ of a call are in the argument context, except a ``ForwardRef``'s+ type argument, which is a type position; a call's callee is in the+ call's context. Every other child inherits ``context``."""+ given: list[tuple[ast.AST, str]] = []+ form = _plain_form(node, proven)+ if form == "Literal" or (form is None and _is_literal_head(node)):+ members = (+ node.slice.elts+ if isinstance(node.slice, ast.Tuple)+ else [node.slice]+ )+ given.extend(+ (member, _ARGUMENT) for member in members if _is_string(member)+ )+ elif (+ form == "Annotated"+ or (form is None and _is_annotated_head(node, annotated))+ ) and isinstance(node.slice, ast.Tuple):+ given.extend((meta, _ARGUMENT) for meta in node.slice.elts[1:])+ elif isinstance(node, ast.Call):+ forward_ref = _is_forward_ref(node.func, forward_refs)+ given.append((node.func, context))+ for argument, position in _call_arguments(node):+ if forward_ref and position in (0, "arg", None):+ given.append((argument, _TYPE))+ else:+ given.append((argument, _ARGUMENT))+ given.extend((child, context) for child in ast.iter_child_nodes(node))+ return given++def _annotation_nodes(- root: ast.AST, annotated: set[str]+ root: ast.AST,+ annotated: set[str],+ forward_refs: set[str],+ proven: dict[str, str],) -> tuple[list[tuple[ast.AST, int | None]], bool, list[int]]:"""Every node of an annotation, quoted parts included.Returns ``(nodes, unparsable, unchecked)``. ``nodes`` holds- ``(node, line)``- pairs: ``line`` is None for a node of ``root`` itself and, for a node- parsed out of a string, the line of the outermost string literal- holding it. FastAPI (via ``typing.get_type_hints``) evaluates a- quoted annotation, so every string in a type position is parsed as- an expression, recursively (``"Annotated[NoteService, Depends()]"``,- ``Optional["NoteService"]``), and the parsed tree is inspected- exactly like an unquoted one. ``unparsable`` is True if any such- string does not parse or nests deeper than ``_MAX_QUOTE_DEPTH`` (fail- closed: the caller treats the annotation as evaluated).- ``unchecked`` lists, by the line of its outermost string literal,- each such string that sits in a type position, which the caller- reports as an offender: a string that is a plain value -- anywhere- inside ``Annotated`` metadata, a ``Literal[...]`` or the arguments- of a call (``Query(description="...")``) -- is never evaluated as a- type, so it is not reported. ``"*[NoteService]"`` is valid as a- ``ForwardRef`` but not as an expression, so it is unchecked.-- Not parsed: the metadata strings of an ``Annotated[T, "doc"]``- (elements after the first), which are kept as plain values and- never evaluated.+ ``(node, line)`` pairs: ``line`` is None for a node of ``root``+ itself and, for a node parsed out of a string, the line of the+ outermost string literal holding it. FastAPI (via+ ``typing.get_type_hints``) evaluates a quoted annotation, so every+ string in it is parsed as an expression, recursively+ (``"Annotated[NoteService, Depends()]"``, ``Optional["NoteService"]``),+ and the parsed tree is inspected exactly like an unquoted one --+ unless the string is exempt.++ A string is exempt only if every step of its path from the+ annotation's root is one ``_approved_children`` approves (an+ allowlist: what it does not name fails closed). ``root`` is a type+ slot, and a string in a type slot is parsed into a tree whose root+ is a type slot again; the path ends at any other node. So+ ``Literal["NoteService"]``, ``Optional[Literal["NoteService"]]``,+ ``Annotated[str, "NoteService"]``, ``Annotated[str,+ Query(description="NoteService")]`` and ``Annotated[str,+ {"description": "NoteService"}]`` hold exempt strings, and the+ wholly quoted ``"Annotated[Literal['NoteService'], Query()]"`` too,+ while ``Literal["NoteService"].__args__[0]``, ``G |+ Literal["NoteService"]``, ``G[Literal["NoteService"]]`` (``G`` not a+ proven generic head), ``f"{Literal['NoteService']}"``,+ ``Annotated[*(), "NoteService", Depends()]``,+ ``Annotated[Literal["NoteService"], G]`` (see ``_inert_metadata``)+ and ``typing.cast(object, "NoteService")`` do not: below a node no+ rule approves, every string is checked, whatever reads it out, and a+ tree parsed out of a string that is not exempt is off the path as a+ whole.++ A string that is not exempt is parsed (see ``_parse_string``) and+ checked in one of two contexts (see ``_child_contexts``). In a type+ position -- ``root``, and whatever is reached from one other than as+ a call argument, a ``Literal`` member or ``Annotated`` metadata, and+ a ``ForwardRef``'s type argument (the first positional, ``arg=``, or+ an argument whose position is unknown; under any name it is imported+ as or qualified) wherever the call sits -- it is parsed as it is and+ stripped, and one that parses neither way, or that nests deeper than+ ``_MAX_QUOTE_DEPTH``, makes ``unparsable`` True (fail closed: the+ caller treats the annotation as evaluated) and is listed in+ ``unchecked`` by the line of its outermost string literal, which the+ caller reports as an offender. ``"*[NoteService]"`` is valid as a+ ``ForwardRef`` but not as an expression, so in a type position it is+ unchecked. In the argument context it is also parsed the way+ ``ForwardRef`` reads it, as ``(*[NoteService],)[0]``+ (``typing.cast(object, "*[NoteService]")`` hands it on to a type+ position); one that parses no way at all makes ``unparsable`` True+ but is not reported, since ``typing`` cannot resolve it and it may+ be a value, such as a regex, and one nested too deep is reported.+ Literal ``*`` / ``**`` unpacking of call arguments is followed to+ find a ``ForwardRef``'s type argument (see ``_call_arguments``).++ Not seen: a name assembled from pieces as the annotation is+ evaluated (``"Note" + "Service"``, ``f"{'Note'}Service"``), since+ each string is checked on its own; a form, callee or generic head+ changed in a way ``_proven_names`` does not see; and code that+ rewrites ``__annotations__`` after the fact, such as a decorator,+ which no check of the annotation as written can see."""nodes: list[tuple[ast.AST, int | None]] = []unparsable = Falseunchecked: list[int] = []- values: set[int] = set()- # ids of every node in a value (non-type) position.- plain: set[int] = set()- pending: list[tuple[ast.AST, int, int | None, bool]] = [- (root, 0, None, False)+ pending: list[tuple[ast.AST, str, str | None, int, int | None]] = [+ (root, _TYPE, _TYPE_SLOT, 0, None)]while pending:- current, depth, line, in_value = pending.pop()+ current, base, base_slot, depth, line = pending.pop()+ # Contexts and approved-path slots by node id. ast.walk is+ # breadth first, so a node's parent (or the subscript or call+ # whose key or arguments hold it) sets both before the node is+ # reached; a node with no slot is off the path.+ contexts = {id(current): base}+ slots = {id(current): base_slot} if base_slot else {}for node in ast.walk(current):nodes.append((node, line))- if _is_annotated_head(node, annotated) and isinstance(- node.slice, ast.Tuple- ):- values.update(id(meta) for meta in node.slice.elts[1:])- for meta in node.slice.elts[1:]:- plain.update(id(n) for n in ast.walk(meta))- if _is_literal_head(node):- plain.update(id(n) for n in ast.walk(node.slice))- if isinstance(node, ast.Call):- for arg in [*node.args, *node.keywords]:- plain.update(id(n) for n in ast.walk(arg))- if (- not (- isinstance(node, ast.Constant)- and isinstance(node.value, str)- )- or id(node) in values+ context = contexts.get(id(node), _TYPE)+ slot = slots.get(id(node))+ if slot in (_TYPE_SLOT, _METADATA_SLOT):+ slots.update(_approved_children(node, slot, proven))+ for child, given in _child_contexts(+ node, context, annotated, forward_refs, proven):+ contexts.setdefault(id(child), given)+ if slot == _EXEMPT or not _is_string(node):continuehere = node.lineno if line is None else line- is_value = in_value or id(node) in plainif depth >= _MAX_QUOTE_DEPTH:unparsable = True- if not is_value:- unchecked.append(here)+ unchecked.append(here)continue- try:- parsed = ast.parse(node.value.strip(), mode="eval")- except (SyntaxError, ValueError, RecursionError, MemoryError):+ trees = _parse_string(node.value, star=context == _ARGUMENT)+ if not trees:unparsable = True- if not is_value:+ if context == _TYPE:unchecked.append(here)continue- pending.append((parsed.body, depth + 1, here, is_value))+ inner = _TYPE_SLOT if slot == _TYPE_SLOT else None+ for tree in trees:+ pending.append((tree, context, inner, depth + 1, here))return nodes, unparsable, unchecked@@ -557,26 +1325,30 @@ def _annotations(tree: ast.AST) -> list[tuple[ast.AST, bool]]:non-constant metadata element (``Annotated[class, dep]``), astarred element (``Annotated[*(class, dep)]``) or a slice that isnot a tuple (``Annotated[args]``);- * a string in it does not parse as an expression, or nests too- deep (fail closed; one in a type position is also reported- itself, see ``_string_annotation_hits``);+ * a string in it that is not exempt does not parse (see+ ``_annotation_nodes``), or nests too deep (fail closed; one in a type+ position, or nested too deep, is also reported itself, see+ ``_string_annotation_hits``);* it is a class field with no binding in its own class body, on aclass with a base other than ``object`` / ``Generic`` /``Protocol``: the field may inherit a non-constant default.- Every string in a type position is parsed and checked like unquoted- code, recursively (see ``_annotation_nodes``), so a wholly quoted- ``"Annotated[class, Depends()]"`` is not type-only either. A class+ Every string that is not exempt is parsed and checked like+ unquoted code, recursively (see ``_annotation_nodes``), so a wholly+ quoted ``"Annotated[class, Depends()]"`` is not type-only either. A classfield counts wherever it sits in the class body, also under ``if`` /``try`` / ``with`` / loops, and its default is any binding of itsname there (``svc: T`` then ``svc = Depends()``; see``_class_field_defaults``).- Callee names are not matched, so ``Depends`` imported under another- name cannot hide a dependency (fail closed). Return annotations and- module- or function-level variable annotations have no default.+ Callee names are not matched here, so ``Depends`` imported under+ another name cannot hide a dependency (fail closed). Return+ annotations and module- or function-level variable annotations have+ no default."""- annotated = _annotated_names(tree)+ annotated = _annotation_names(tree, "Annotated")+ forward_refs = _annotation_names(tree, "ForwardRef")+ proven = _proven_names(tree)defaults: dict[int, ast.AST] = {}for node in ast.walk(tree):if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):@@ -603,7 +1375,9 @@ def _annotations(tree: ast.AST) -> list[tuple[ast.AST, bool]]:root, default = node.annotation, defaults.get(id(node))else:continue- nodes, unparsable, _unchecked = _annotation_nodes(root, annotated)+ nodes, unparsable, _unchecked = _annotation_nodes(+ root, annotated, forward_refs, proven+ )type_only = ((default is None or isinstance(default, ast.Constant))and not unparsable@@ -634,15 +1408,19 @@ def _string_annotation_hits(Depends()``, or a wholly quoted ``"Annotated[NoteService,Depends()]"``) in the module globals, so a quoted constructor nameis as live there as a bare one. Strings are parsed recursively (see- ``_annotation_nodes``); one in a type position that does not parse- (or nests too deep) is reported itself, as an annotation string that- cannot be checked."""- annotated = _annotated_names(tree)+ ``_annotation_nodes``); one in a type position that does not parse,+ or any that nests too deep, is reported itself, as an annotation+ string that cannot be checked."""+ annotated = _annotation_names(tree, "Annotated")+ forward_refs = _annotation_names(tree, "ForwardRef")+ proven = _proven_names(tree)hits: list[tuple[int, str]] = []for root, type_only in _annotations(tree):if type_only:continue- nodes, _unparsable, unchecked = _annotation_nodes(root, annotated)+ nodes, _unparsable, unchecked = _annotation_nodes(+ root, annotated, forward_refs, proven+ )hits.extend((line, _UNCHECKED_STRING) for line in unchecked)for inner, line in nodes:if line is None:diff --git a/.pre-commit-hooks/check-reports-dir-not-served.py b/.pre-commit-hooks/check-reports-dir-not-served.pyindex a14f11af8d..e0494c2ea8 100755--- a/.pre-commit-hooks/check-reports-dir-not-served.py+++ b/.pre-commit-hooks/check-reports-dir-not-served.py@@ -118,16 +118,76 @@ reliably, so the fence is deliberately coarse. Underslice, any call, walrus or lambda inside it, a class field with nobinding in its own class body on a class with a base other than``object`` / ``Generic`` / ``Protocol`` (it may inherit a- ``Depends()`` default), or a string that does not parse. In every- scanned file, a string in a type position that does not parse as an- expression (``"*[FileResponse]"`` is a valid ForwardRef but not an- expression) or nests deeper than ``_MAX_QUOTE_DEPTH`` is reported on- its own, as an annotation string that cannot be checked (strings- that are plain values -- call arguments, ``Literal`` members,- ``Annotated`` metadata -- are not). Every string in a type position is- parsed and checked like unquoted code, recursively, since FastAPI+ ``Depends()`` default), or a string, other than an exempt one+ (below), that does not parse. Every string inside such an annotation+ is parsed and checked like unquoted code, recursively, since FastAPIevaluates it (a wholly quoted ``"Annotated[T,- Depends(static_file_response)]"`` is as live as the unquoted form).+ Depends(static_file_response)]"`` is as live as the unquoted form),+ unless it is exempt. Exemption is an allowlist of shapes (see+ ``_approved_children``), so whatever it does not name fails closed: a+ string is exempt only if every step of its path from the annotation's+ root is approved -- subscripts of a proven generic head+ (``Optional``, ``Union``, ``list`` ...) and the first element of a+ proven ``Annotated`` whose metadata is inert (each element a+ constant, a call of a proven listed callee or a dict display:+ pydantic hands the first element to any other metadata object's+ ``__get_pydantic_core_schema__``), then one last step -- and it ends+ as a string member of a proven ``Literal[...]``; as metadata of such+ an ``Annotated`` (an element after the first, where the key has two+ or more elements and none is starred); as a string passed directly,+ in that metadata or in a type slot, to an argument+ ``VALUE_ARGUMENTS`` lists, of a proven callee+ (``Query(description="...")``, ``NewType("Name", str)``,+ ``ForwardRef("T", module="...")``); or as a string key or value of a+ dict display in that metadata. Any other node on the path -- an+ attribute read, a subscript of another head, an operator or+ comparison, an unlisted call, a lambda, walrus, conditional, starred+ or formatted value -- ends it, and every string below it is checked,+ whatever reads the string back out:+ ``Literal["FileResponse"].__args__[0]``, ``G |+ Literal["FileResponse"]``, ``G[Literal["FileResponse"]]``,+ ``f"{Literal['FileResponse']}"``, ``Annotated[*(), "FileResponse",+ Depends()]`` and ``Annotated[Literal["FileResponse"], G]`` can each+ hand the string on to a type position, which FastAPI resolves.+ ``Literal`` and ``Annotated`` are proven only when imported from+ ``typing`` or ``typing_extensions`` (``PLAIN_FORMS``), a+ ``VALUE_ARGUMENTS`` callee only when imported from its own module+ (``from fastapi import Query [as Q]``, or ``fastapi.Query`` after+ ``import fastapi``), and a generic head only from ``typing``,+ ``typing_extensions`` or ``collections.abc`` or as an unbound+ builtin, each under a name nothing else in the file binds (after+ ``from typing import Annotated as Literal``,+ ``Literal["FileResponse", Depends()]`` is checked as the+ ``Annotated`` it is). Nothing in a file is proven if it could change+ what a proven name denotes (see ``_proven_names``): a star import; a+ reference to a name that can look up or rewrite a namespace+ dynamically (such as ``setattr``, ``vars``, ``globals``, ``locals``,+ ``__dict__``, ``sys.modules``, ``importlib``, ``exec`` or ``eval``);+ an attribute or item store or delete rooted in an imported name+ (``typing.Literal = ...``), in an unbound name or in an expression;+ on any object, a store or delete whose target attribute is named like+ something a proof rests on (``mod.Literal = ...``), or whose target+ goes through a dunder or a private attribute of anything but ``self``+ / ``cls``; a proven module, or one a proof rests on reached as an+ attribute, used other than to read an attribute off it (``mod =+ typing``, ``mod = typing_extensions.typing``), or a private name of+ one; or a proven form, listed callee or subscripted generic head used+ outside a type position (``L = Literal``, ``type(typing.List)``).+ Every other call argument is checked, so an unknown call fails+ closed: ``typing.cast(object, "FileResponse")`` hands its string on+ to a type position, which FastAPI resolves. ``ForwardRef``'s type+ argument is a type position, under any name it is imported as or+ qualified. A string is parsed as it is (as ``ForwardRef`` compiles+ it, so ``"FileResponse"`` followed by a line continuation is checked)+ and stripped. In every scanned file, a string in a type position that+ parses neither way (``"*[FileResponse]"`` is a valid ForwardRef but+ not an expression), or one nested deeper than ``_MAX_QUOTE_DEPTH``,+ is reported on its own, as an annotation string that cannot be+ checked; elsewhere -- a call argument, or a ``Literal`` member or+ ``Annotated`` metadata that is not exempt -- a string is also parsed+ the way ``ForwardRef`` reads ``"*[FileResponse]"``, and one that+ parses no way is not reported (``typing`` cannot resolve it; it may+ be a regex).In an allowlisted file a serving name insuch an annotation is a non-call reference (rule 4); outside theallowlist every reference is already flagged by rules 1 and 2. In@@ -167,8 +227,18 @@ name is not in ``SERVING_HELPERS``; a primitive, wrapper or helperwrapped, renamed or re-exported by a module outside ``web/`` (whichthis hook does not scan) and imported from there; ``Annotated`` reachedthrough an assignment alias (``A = Annotated``) with non-call metadata-in an allowlisted file; and dynamic lookups (``getattr``,-``importlib``, ``__import__``, ``module.__dict__[...]``, ``eval``).+in an allowlisted file; a ``VALUE_ARGUMENTS`` callee, ``PLAIN_FORMS``+form or generic head changed from another module, through a dynamic+lookup that uses none of the names under rule 5 (``getattr(m, "Lit" ++"eral")``), through a name used only inside a quoted annotation, or+through an object derived from it at runtime (``type(Literal["x"])``),+whose exempt strings stay unparsed; code that rewrites+``__annotations__`` after the fact, such as a decorator, which no check+of an annotation as written can see; a serving name assembled from+pieces as an annotation is evaluated (``"File" + "Response"``,+``f"{'File'}Response"``), since each string is checked on its own; and+dynamic lookups (``getattr``, ``importlib``, ``__import__``,+``module.__dict__[...]``, ``eval``).The companion contract (tests/security/test_architecture_fences.py)runs this same scanner over the same tree, pre-commit style (repo-root@@ -519,25 +589,26 @@ def _renaming_imports(tree: ast.AST) -> list[tuple[int, str]]:_EVALUATED = (ast.Call, ast.NamedExpr, ast.Lambda)-def _annotated_names(tree: ast.AST) -> set[str]:- """``Annotated`` plus every local name it is imported as."""- names = {"Annotated"}+def _annotation_names(tree: ast.AST, name: str) -> set[str]:+ """``name`` plus every local name it is imported as."""+ names = {name}for node in ast.walk(tree):if isinstance(node, ast.ImportFrom):names.update(alias.asnamefor alias in node.names- if alias.name == "Annotated" and alias.asname+ if alias.name == name and alias.asname)return names#: Nesting bound for quoted annotations (a string inside a string ...):#: a string nested deeper than this counts as evaluated (fail closed)-#: and, in a type position, is reported as unchecked.+#: and is reported as unchecked (an exempt string is never parsed)._MAX_QUOTE_DEPTH = 8-#: Offender text for a string in a type position the hook cannot check.+#: Offender text for a string the hook cannot check: one in a type+#: position that does not parse, or one nested too deep._UNCHECKED_STRING = ("annotation string that cannot be checked (it does not parse as an ""expression, or quotes nest deeper than "@@ -547,8 +618,10 @@ _UNCHECKED_STRING = (def _is_literal_head(node: ast.AST) -> bool:- """True if ``node`` is ``Literal[...]`` (bare or qualified): its- strings are values, never evaluated as types."""+ """True if ``node`` is a subscript of a name spelled ``Literal`` (bare+ or qualified), whatever that name is bound to. Only a ``Literal``+ that ``_plain_form`` proves can hold exempt strings (see+ ``_approved_children``)."""if not isinstance(node, ast.Subscript):return Falsehead = node.value@@ -558,8 +631,12 @@ def _is_literal_head(node: ast.AST) -> bool:def _is_annotated_head(node: ast.AST, annotated: set[str]) -> bool:- """True if ``node`` is a subscript of ``Annotated`` (under any import- alias, or qualified as ``typing.Annotated``)."""+ """True if ``node`` is a subscript of a name spelled ``Annotated``+ (under any import alias, or qualified as ``typing.Annotated``),+ whatever that name is bound to. ``_has_evaluated_metadata`` checks+ every such subscript (fail closed); only an ``Annotated`` that+ ``_plain_form`` proves can hold exempt strings (see+ ``_approved_children``)."""if not isinstance(node, ast.Subscript):return Falsehead = node.value@@ -568,81 +645,778 @@ def _is_annotated_head(node: ast.AST, annotated: set[str]) -> bool:)+#: Call arguments that only ever hold a plain value -- documentation, an+#: alias, a regex, example values, a ``NewType`` name or a module name --+#: which the callee (from FastAPI, pydantic or ``typing``) itself never+#: evaluates as a type and never calls, as ``{callee: positions}`` (an+#: index for a positional argument, a name for a keyword). A string+#: literal passed there directly is exempt from parsing only where the+#: call sits on an approved path and the callee is provably the listed+#: one (see ``_approved_children`` and ``_proven_names``); every other+#: argument is parsed and checked, so an unknown call fails closed. The+#: entries match the signatures of FastAPI 0.136, pydantic 2.13 and+#: Python 3.12 to 3.14; ``test_value_arguments_match_the_signatures`` in+#: tests/security/test_architecture_fences.py checks them against the+#: installed ones. ``ForwardRef``'s position 2 is ``module`` before+#: Python 3.14, which makes it keyword-only.+_PARAMETER_TEXT = frozenset(+ {"alias", "title", "description", "pattern", "regex", "example", "examples"}+)+VALUE_ARGUMENTS: dict[str, frozenset[int | str]] = {+ **{+ f"fastapi.{name}": _PARAMETER_TEXT+ for name in (+ "Query",+ "Path",+ "Header",+ "Cookie",+ "Body",+ "Form",+ "File",+ )+ },+ "fastapi.Depends": frozenset({"scope"}),+ "pydantic.Field": frozenset(+ {"alias", "title", "description", "pattern", "examples"}+ ),+ "pydantic.constr": frozenset({"pattern"}),+ "typing.NewType": frozenset({0, "name"}),+ "typing.ForwardRef": frozenset({2, "module"}),+}++#: Modules whose import makes ``module.callee`` a ``VALUE_ARGUMENTS`` callee.+_VALUE_MODULES = frozenset(+ callee.rpartition(".")[0] for callee in VALUE_ARGUMENTS+)++#: Subscript forms that can hold exempt strings, as ``module.name``: the+#: string members of ``Literal[...]`` and the metadata of+#: ``Annotated[...]`` (its elements after the first), which ``typing``+#: and FastAPI keep as values. Like a ``VALUE_ARGUMENTS`` callee, a form+#: counts only under a name ``_proven_names`` proves is imported from+#: its module, and only on an approved path (see ``_approved_children``).+PLAIN_FORMS = frozenset(+ f"{module}.{form}"+ for module in ("typing", "typing_extensions")+ for form in ("Literal", "Annotated")+)++#: Modules whose import makes ``module.Literal`` / ``module.Annotated`` a+#: ``PLAIN_FORMS`` form.+_FORM_MODULES = frozenset(form.rpartition(".")[0] for form in PLAIN_FORMS)++#: Modules whose subscriptable names (``Optional``, ``List``,+#: ``Sequence``, ``Literal`` ...) keep the key of a subscript a type+#: argument: subscripting one never hands its key to the project's code,+#: so it is a step of an approved path (see ``_approved_children``).+_GENERIC_MODULES = frozenset({"typing", "typing_extensions", "collections.abc"})++#: Builtins that keep the key of a subscript a type argument+#: (``list[T]``), where nothing in the file binds the name. Their types+#: cannot be changed, only the names rebound.+_GENERIC_BUILTINS = frozenset(+ {"list", "dict", "set", "frozenset", "tuple", "type"}+)++#: What ``_proven_names`` can prove a name denotes (and any name of a+#: ``_GENERIC_MODULES`` module).+_PROVABLE = frozenset(+ {+ *VALUE_ARGUMENTS,+ *_VALUE_MODULES,+ *PLAIN_FORMS,+ *_FORM_MODULES,+ *_GENERIC_MODULES,+ }+)++#: The modules a proof can rest on, and the last part of each module's+#: name, by which an attribute read can reach the module from another+#: one (``typing_extensions.typing``).+_PROOF_MODULES = _VALUE_MODULES | _FORM_MODULES | _GENERIC_MODULES+_PROOF_MODULE_NAMES = frozenset(+ module.rpartition(".")[2] for module in _PROOF_MODULES+)++#: Names through which a file can reach or rewrite a namespace -- a+#: module's, a class's, the builtins or ``sys.modules`` -- without naming+#: what it replaces (``setattr(typing, "Literal", ...)``,+#: ``vars(typing)[...]``, ``typing.__dict__[...]``, ``sys.modules[...]``,+#: ``importlib.import_module("typing")``, ``exec(...)``). A reference to+#: one, as a name, an attribute of anything or a part of an import,+#: voids every proof in the file (see ``_proven_names``).+_DYNAMIC_NAMES = frozenset(+ {+ "__builtins__",+ "__delattr__",+ "__dict__",+ "__import__",+ "__setattr__",+ "delattr",+ "eval",+ "exec",+ "globals",+ "import_module",+ "importlib",+ "locals",+ "modules",+ "setattr",+ "vars",+ }+)++#: Definitions that bind their own name.+_NAMED_DEFINITIONS = (+ ast.FunctionDef,+ ast.AsyncFunctionDef,+ ast.ClassDef,+ ast.ExceptHandler,+ ast.MatchAs,+ ast.MatchStar,+ ast.TypeVar,+ ast.ParamSpec,+ ast.TypeVarTuple,+)+++def _proven_names(tree: ast.AST) -> dict[str, str]:+ """Local names that provably denote a ``VALUE_ARGUMENTS`` callee, a+ ``PLAIN_FORMS`` form, a name of a ``_GENERIC_MODULES`` module, a+ ``_GENERIC_BUILTINS`` builtin, or one of these modules: ``{"Q":+ "fastapi.Query", "fastapi": "fastapi", "Literal": "typing.Literal",+ "list": "builtins.list"}``.++ A name counts only if each import binding it in the file is the same+ ``from <module> import <name> [as <local>]`` (or ``import <module>+ [as <local>]``; a builtin, only if nothing imports it) and nothing+ else in the file binds it -- an assignment or ``del``, a ``def``,+ ``class``, parameter, ``for`` / ``with`` / ``except`` / ``match``+ target, walrus, ``global`` / ``nonlocal`` or type parameter (no+ scope tracking; fail closed) -- so a local pass-through that happens+ to be called ``Query`` is an unknown callee, and ``Literal =+ typing.Annotated`` is not a ``Literal``.++ Nothing in the file is proven at all (fail closed: every string is+ then checked) if it contains any of these, through which it could+ change what a proven name denotes:++ * a star import;+ * a ``_DYNAMIC_NAMES`` name, as a name, as an attribute of anything+ or imported by name (``setattr(typing, "Literal", ...)``,+ ``vars(typing)[...]``, ``typing.__dict__[...]``,+ ``sys.modules[...]``, ``exec(...)``, ``from importlib import+ import_module``);+ * a store or delete (an assignment, augmented assignment or+ ``del``, a loop or ``with`` target) of an attribute or item that+ is rooted in an imported name (``typing.Literal = ...``,+ ``builtins.list = ...``, ``Query.__code__ = ...``), in a name the+ file never binds, or in anything but a name+ (``type(Literal).__getitem__ = ...``);+ * a store or delete, on any object, of an attribute named like+ anything a proof could rest on -- the last part of a+ ``PLAIN_FORMS`` or ``VALUE_ARGUMENTS`` name, a+ ``_GENERIC_BUILTINS`` name, or the last part of a name proven here+ or read off a proven module (``mod.Literal = ...``, ``b.list =+ ...``, ``t.Optional = ...``) -- or one whose target reads a dunder+ attribute (``c.__getitem__ = ...``, ``a.__class__.x = ...``) or a+ ``_``-private attribute of anything but ``self`` or ``cls``+ (``L._getitem = ...``);+ * a proven module referenced other than as the object of an+ attribute read (``mod = typing``, ``getattr(typing, ...)``), an+ attribute named like a module a proof rests on (``typing``,+ ``typing_extensions``, ``fastapi``, ``pydantic``, ``abc``) read+ other than as the object of another attribute read+ (``t = typing_extensions.typing``), or a ``_``-private name read+ off a proven module or imported from a module a proof rests on+ (``typing._SpecialForm``, ``from typing import _GenericAlias``);+ * a ``PLAIN_FORMS`` form, a ``VALUE_ARGUMENTS`` callee or a generic+ head the file subscripts, referenced -- under a name proven to+ denote it, or as an attribute of a proven module -- other than in+ a type position: the head of a subscript, the callee of a call, a+ whole annotation (``-> Dict``), or the key, or an element of the+ key, of a subscript whose head is proven (``List[Dict]``,+ ``dict[str, Dict]``). So ``L = Literal``, ``type(typing.List)``,+ ``partial(Query, ...)`` or ``isinstance(x, Mapping)`` in a file+ that subscripts ``Mapping`` voids every proof.++ Not seen (deliberate evasion, beyond a per-file syntax check): a+ form, callee or generic head changed from another module, through a+ dynamic lookup (``getattr(m, "Lit" + "eral")``), through a name used+ only inside a quoted annotation, or through an object derived from it+ at runtime (``type(Literal["x"])``) whose public attributes are then+ replaced."""+ imported: dict[str, set[str]] = {}+ bound: set[str] = set()+ # Attribute and item store / delete targets; every load of a name or+ # attribute with the node holding it; annotation roots; and each+ # tuple that is a subscript's key, with the subscript.+ targets: list[ast.AST] = []+ loads: list[tuple[ast.AST, ast.AST]] = []+ annotations: set[int] = set()+ keys: dict[int, ast.Subscript] = {}+ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom):+ module = f"{'.' * node.level}{node.module or ''}"+ for alias in node.names:+ if (+ alias.name == "*"+ or alias.name in _DYNAMIC_NAMES+ or (alias.name.startswith("_") and module in _PROOF_MODULES)+ ):+ return {}+ imported.setdefault(alias.asname or alias.name, set()).add(+ f"{module}.{alias.name}"+ )+ elif isinstance(node, ast.Import):+ for alias in node.names:+ local = alias.asname or alias.name.partition(".")[0]+ source = alias.name if alias.asname else local+ imported.setdefault(local, set()).add(source)+ elif isinstance(node, ast.arg):+ bound.add(node.arg)+ if node.annotation is not None:+ annotations.add(id(node.annotation))+ elif isinstance(node, (ast.Global, ast.Nonlocal)):+ bound.update(node.names)+ elif isinstance(node, ast.MatchMapping):+ if node.rest:+ bound.add(node.rest)+ elif isinstance(node, ast.AnnAssign):+ annotations.add(id(node.annotation))+ elif isinstance(node, ast.Subscript) and isinstance(+ node.slice, ast.Tuple+ ):+ keys[id(node.slice)] = node+ if isinstance(node, _NAMED_DEFINITIONS) and node.name:+ bound.add(node.name)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and (+ node.returns is not None+ ):+ annotations.add(id(node.returns))+ for child in ast.iter_child_nodes(node):+ if isinstance(child, ast.Name):+ spelled = child.id+ elif isinstance(child, ast.Attribute):+ spelled = child.attr+ elif isinstance(child, ast.Subscript):+ if not isinstance(child.ctx, ast.Load):+ targets.append(child)+ continue+ else:+ continue+ if spelled in _DYNAMIC_NAMES:+ return {}+ if isinstance(child.ctx, ast.Load):+ loads.append((child, node))+ elif isinstance(child, ast.Name):+ bound.add(child.id)+ else:+ targets.append(child)+ names: dict[str, str] = {}+ for name, sources in imported.items():+ if len(sources) != 1 or name in bound:+ continue+ (source,) = sources+ if source in _PROVABLE or source.rpartition(".")[0] in _GENERIC_MODULES:+ names[name] = source+ for name in _GENERIC_BUILTINS - imported.keys() - bound:+ names[name] = f"builtins.{name}"+ modules = {+ name for name, source in names.items() if source in _PROOF_MODULES+ }++ def denotes(node: ast.AST) -> str:+ """What ``node`` denotes by ``names``, or ``""``."""+ return _proven_name(node, names, _PROOF_MODULES) or ""++ # The last part of everything a proof here could rest on, and of the+ # forms, callees and generic heads to be used only in type positions.+ relied = {+ source.rpartition(".")[2]+ for source in (*VALUE_ARGUMENTS, *PLAIN_FORMS, *names.values())+ } | _GENERIC_BUILTINS+ used = {+ source.rpartition(".")[2] for source in (*VALUE_ARGUMENTS, *PLAIN_FORMS)+ }+ for node, parent in loads:+ if (+ isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and node.value.id in modules+ ):+ relied.add(node.attr)+ if node.attr.startswith("_"):+ return {}+ if isinstance(parent, ast.Subscript) and parent.value is node:+ source = denotes(node)+ if (+ source+ and source not in _PROOF_MODULES+ and not (source.startswith("builtins."))+ ):+ used.add(source.rpartition(".")[2])+ for target in targets:+ root = target+ while isinstance(root, (ast.Attribute, ast.Subscript)):+ root = root.value+ if (+ not isinstance(root, ast.Name)+ or root.id in imported+ or root.id not in bound+ ):+ return {}+ if isinstance(target, ast.Attribute) and target.attr in relied:+ return {}+ step = target+ while isinstance(step, (ast.Attribute, ast.Subscript)):+ if (+ isinstance(step, ast.Attribute)+ and step.attr.startswith("_")+ and (step.attr.endswith("__") or root.id not in ("self", "cls"))+ ):+ return {}+ step = step.value+ for node, parent in loads:+ if isinstance(parent, ast.Attribute) and parent.value is node:+ if isinstance(node, ast.Name) and node.id in modules:+ continue+ elif isinstance(node, ast.Name) and node.id in modules:+ return {}+ elif (+ isinstance(node, ast.Attribute) and node.attr in _PROOF_MODULE_NAMES+ ):+ return {}+ source = denotes(node)+ if (+ not source+ or source in _PROOF_MODULES+ or source.startswith("builtins.")+ or source.rpartition(".")[2] not in used+ ):+ continue+ subscript = keys.get(id(parent), parent)+ if not (+ (isinstance(parent, ast.Subscript) and parent.value is node)+ or (isinstance(parent, ast.Call) and parent.func is node)+ or id(node) in annotations+ or (+ isinstance(subscript, ast.Subscript)+ and node is not subscript.value+ and denotes(subscript.value)+ )+ ):+ return {}+ return names+++def _proven_name(+ node: ast.AST, proven: dict[str, str], modules: frozenset[str]+) -> str | None:+ """What ``node`` provably denotes (see ``_proven_names``): a proven+ name, or an attribute of a name proven to be one of ``modules``+ (``fastapi.Query``), as ``module.name``; else None."""+ if isinstance(node, ast.Name):+ return proven.get(node.id)+ if (+ isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and proven.get(node.value.id) in modules+ ):+ return f"{proven[node.value.id]}.{node.attr}"+ return None+++def _value_callee(func: ast.AST, proven: dict[str, str]) -> str | None:+ """The ``VALUE_ARGUMENTS`` callee ``func`` provably names (``Query``,+ an alias ``Q``, or ``fastapi.Query``; see ``_proven_names``), or+ None."""+ callee = _proven_name(func, proven, _VALUE_MODULES)+ return callee if callee in VALUE_ARGUMENTS else None+++def _plain_form(node: ast.AST, proven: dict[str, str]) -> str | None:+ """``"Literal"`` or ``"Annotated"`` if ``node`` is a subscript of that+ ``PLAIN_FORMS`` form under a name ``_proven_names`` proves+ (``Literal``, an alias ``L``, or ``typing.Literal``), else None."""+ if not isinstance(node, ast.Subscript):+ return None+ form = _proven_name(node.value, proven, _FORM_MODULES)+ return form.rpartition(".")[2] if form in PLAIN_FORMS else None+++def _generic_head(head: ast.AST, proven: dict[str, str]) -> bool:+ """True if ``head`` provably names something of a ``_GENERIC_MODULES``+ module or a ``_GENERIC_BUILTINS`` builtin (``Optional``,+ ``typing.List``, ``list``; see ``_proven_names``), whose subscript+ keeps its key a type argument."""+ name = _proven_name(head, proven, _GENERIC_MODULES)+ return name is not None and (+ name.rpartition(".")[0] in _GENERIC_MODULES+ or name.startswith("builtins.")+ )+++def _is_forward_ref(func: ast.AST, forward_refs: set[str]) -> bool:+ """True if ``func`` is named ``ForwardRef``: bare, under any name it+ is imported as, or qualified (``typing.ForwardRef``)."""+ return (isinstance(func, ast.Name) and func.id in forward_refs) or (+ isinstance(func, ast.Attribute) and func.attr == "ForwardRef"+ )+++def _call_arguments(call: ast.Call) -> list[tuple[ast.AST, int | str | None]]:+ """Each argument of ``call`` with the parameter it binds: an index, a+ keyword, or None where that is unknown.++ Literal unpacking is followed, nested too: ``*("a", "b")`` binds+ indexes and ``**{"k": v}`` binds keyword ``k``. Anything else that is+ unpacked (``*args``, ``**dict(k=v)``, a key that is not a string+ constant) binds None, and so does every positional argument after a+ ``*`` of unknown length. The unpacking syntax itself (the starred+ node, the unpacked tuple, list or dict, and a dict's keys) is listed+ with None too."""+ found: list[tuple[ast.AST, int | str | None]] = []+ index: int | None = 0+ positional = list(reversed(call.args))+ while positional:+ arg = positional.pop()+ if isinstance(arg, ast.Starred):+ found.extend([(arg, None), (arg.value, None)])+ if isinstance(arg.value, (ast.Tuple, ast.List)):+ positional.extend(reversed(arg.value.elts))+ else:+ index = None+ continue+ found.append((arg, index))+ if index is not None:+ index += 1+ mappings: list[ast.AST] = []+ for kw in call.keywords:+ if kw.arg is None:+ mappings.append(kw.value)+ else:+ found.append((kw.value, kw.arg))+ while mappings:+ mapping = mappings.pop()+ found.append((mapping, None))+ if not isinstance(mapping, ast.Dict):+ continue+ for key, value in zip(mapping.keys, mapping.values):+ if key is None:+ mappings.append(value)+ continue+ found.append((key, None))+ named = isinstance(key, ast.Constant) and isinstance(key.value, str)+ found.append((value, key.value if named else None))+ return found+++def _parse_expression(text: str) -> ast.AST | None:+ """``text`` parsed as an expression, or None if it does not parse."""+ try:+ return ast.parse(text, mode="eval").body+ except (SyntaxError, ValueError, RecursionError, MemoryError):+ return None+++def _parse_string(text: str, star: bool) -> list[ast.AST]:+ """The distinct trees ``text`` parses to as an expression, trying it+ as it is (``ForwardRef`` compiles the raw string, so one ending in a+ line continuation -- a backslash and a newline -- is valid there)+ and with surrounding whitespace stripped (``eval`` strips leading+ spaces). With ``star``, each of the two that does not parse is also+ tried the way ``ForwardRef`` reads a string starting with ``*``, as+ ``({text},)[0]`` (``"*[T]"``), which also tolerates leading+ whitespace before a line continuation. Empty only if every attempt+ fails."""+ trees: dict[str, ast.AST] = {}+ for form in (text, text.strip()):+ parsed = _parse_expression(form)+ if parsed is None and star:+ parsed = _parse_expression(f"({form},)[0]")+ if parsed is not None:+ trees.setdefault(ast.dump(parsed), parsed)+ return list(trees.values())+++def _is_string(node: ast.AST) -> bool:+ """True if ``node`` is a string literal."""+ return isinstance(node, ast.Constant) and isinstance(node.value, str)+++#: Where a node sits on an approved path from an annotation's root (see+#: ``_approved_children``): a type slot, an ``Annotated`` metadata slot,+#: or an exempt string. A node that has none is off the path.+_TYPE_SLOT, _METADATA_SLOT, _EXEMPT = "type slot", "metadata slot", "exempt"+++def _listed_arguments(call: ast.Call, proven: dict[str, str]) -> list[ast.AST]:+ """The arguments ``VALUE_ARGUMENTS`` lists for the callee that+ ``_value_callee`` proves ``call`` names, passed directly: a keyword+ by its name, a positional argument by its index before any ``*``+ unpacking (nothing inside a ``*`` or ``**`` is listed)."""+ listed = VALUE_ARGUMENTS.get(_value_callee(call.func, proven), frozenset())+ found: list[ast.AST] = []+ for index, argument in enumerate(call.args):+ if isinstance(argument, ast.Starred):+ break+ if index in listed:+ found.append(argument)+ found.extend(kw.value for kw in call.keywords if kw.arg in listed)+ return found+++def _inert_metadata(node: ast.AST, proven: dict[str, str]) -> bool:+ """True if ``node``, as ``Annotated`` metadata, is an object FastAPI+ and pydantic never hand the annotated type to project code through:+ a constant, a call of a callee ``_value_callee`` proves, or a dict+ display with no ``**`` unpacking. Any other object may define+ ``__get_pydantic_core_schema__``, which pydantic calls with the+ type (``Annotated[Literal["T"], G]`` hands ``Literal["T"]`` to+ ``G``, which can read ``"T"`` back out into the type it validates+ with), so its ``Annotated`` approves nothing."""+ return (+ isinstance(node, ast.Constant)+ or (+ isinstance(node, ast.Call)+ and _value_callee(node.func, proven) is not None+ )+ or (isinstance(node, ast.Dict) and None not in node.keys)+ )+++def _approved_children(+ node: ast.AST, slot: str, proven: dict[str, str]+) -> dict[int, str]:+ """The allowlist: ``{id(descendant): slot}`` for what ``node``, on an+ approved path in ``slot`` (see ``_annotation_nodes``), passes the+ path on to. A string literal is exempt from parsing only where a+ rule here makes it ``_EXEMPT``. Whatever no rule names is off the+ path, and so is everything below it, whatever the node kind -- an+ attribute read, an operator, a comparison, an unlisted call, a+ subscript of another head, a lambda, a walrus, a conditional, a+ starred or formatted value -- so every string there is parsed and+ checked. The rules, where proven means provably the ``typing``,+ ``typing_extensions``, ``collections.abc``, builtin, FastAPI or+ pydantic name (see ``_proven_names``):++ * in a type slot, a subscript of a proven ``Literal``: each string+ member of its key is exempt;+ * in a type slot, a subscript of a proven ``Annotated`` whose key is+ a tuple of two or more elements, none starred, with only inert+ metadata (see ``_inert_metadata``): the first element is a type+ slot, and each later one is exempt if it is a string, else a+ metadata slot;+ * in a type slot, a subscript of another proven generic head+ (``Optional``, ``Union``, ``list`` ...; see ``_generic_head``):+ each element of its key is a type slot;+ * in a type or metadata slot, a call of a proven ``VALUE_ARGUMENTS``+ callee: each string passed directly in a listed position is exempt+ (see ``_listed_arguments``);+ * in a metadata slot, a dict display: each string key and value is+ exempt (one with ``**`` unpacking is not inert metadata, so its+ ``Annotated`` approves nothing)."""+ if slot == _TYPE_SLOT and isinstance(node, ast.Subscript):+ key = node.slice+ elements = key.elts if isinstance(key, ast.Tuple) else [key]+ form = _plain_form(node, proven)+ if form == "Literal":+ return {+ id(member): _EXEMPT for member in elements if _is_string(member)+ }+ if form == "Annotated":+ if (+ not isinstance(key, ast.Tuple)+ or len(elements) < 2+ or any(isinstance(e, ast.Starred) for e in elements)+ or not all(_inert_metadata(m, proven) for m in elements[1:])+ ):+ return {}+ return {+ id(elements[0]): _TYPE_SLOT,+ **{+ id(meta): _EXEMPT if _is_string(meta) else _METADATA_SLOT+ for meta in elements[1:]+ },+ }+ if _generic_head(node.value, proven):+ return {id(element): _TYPE_SLOT for element in elements}+ return {}+ if isinstance(node, ast.Call):+ return {+ id(argument): _EXEMPT+ for argument in _listed_arguments(node, proven)+ if _is_string(argument)+ }+ if slot == _METADATA_SLOT and isinstance(node, ast.Dict):+ return {+ id(item): _EXEMPT+ for item in (*node.keys, *node.values)+ if _is_string(item)+ }+ return {}+++#: How ``_annotation_nodes`` checks a string that is not exempt, by where+#: it sits: in a type position it must parse (it is reported if it does+#: not); in the argument context -- a call argument, a ``Literal``+#: member or ``Annotated`` metadata -- it is also parsed the way+#: ``ForwardRef`` reads a starred string, and not reported if it does+#: not parse at all, since it may be a value such as a regex.+_TYPE, _ARGUMENT = "type", "argument"+++def _child_contexts(+ node: ast.AST,+ context: str,+ annotated: set[str],+ forward_refs: set[str],+ proven: dict[str, str],+) -> list[tuple[ast.AST, str]]:+ """``(descendant, context)`` pairs for what ``node``, seen in+ ``context``, contains. The caller keeps the first pair given for a+ node, so the specific ones come first: the string members of a+ ``Literal`` and the metadata of an ``Annotated`` (the form+ ``_plain_form`` proves, else the name it is spelled with; see+ ``_is_literal_head`` and ``_is_annotated_head``) and every argument+ of a call are in the argument context, except a ``ForwardRef``'s+ type argument, which is a type position; a call's callee is in the+ call's context. Every other child inherits ``context``."""+ given: list[tuple[ast.AST, str]] = []+ form = _plain_form(node, proven)+ if form == "Literal" or (form is None and _is_literal_head(node)):+ members = (+ node.slice.elts+ if isinstance(node.slice, ast.Tuple)+ else [node.slice]+ )+ given.extend(+ (member, _ARGUMENT) for member in members if _is_string(member)+ )+ elif (+ form == "Annotated"+ or (form is None and _is_annotated_head(node, annotated))+ ) and isinstance(node.slice, ast.Tuple):+ given.extend((meta, _ARGUMENT) for meta in node.slice.elts[1:])+ elif isinstance(node, ast.Call):+ forward_ref = _is_forward_ref(node.func, forward_refs)+ given.append((node.func, context))+ for argument, position in _call_arguments(node):+ if forward_ref and position in (0, "arg", None):+ given.append((argument, _TYPE))+ else:+ given.append((argument, _ARGUMENT))+ given.extend((child, context) for child in ast.iter_child_nodes(node))+ return given++def _annotation_nodes(- root: ast.AST, annotated: set[str]+ root: ast.AST,+ annotated: set[str],+ forward_refs: set[str],+ proven: dict[str, str],) -> tuple[list[tuple[ast.AST, int | None]], bool, list[int]]:"""Every node of an annotation, quoted parts included.Returns ``(nodes, unparsable, unchecked)``. ``nodes`` holds- ``(node, line)``- pairs: ``line`` is None for a node of ``root`` itself and, for a node- parsed out of a string, the line of the outermost string literal- holding it. FastAPI (via ``typing.get_type_hints``) evaluates a- quoted annotation, so every string in a type position is parsed as- an expression, recursively (``"Annotated[NoteService, Depends()]"``,- ``Optional["NoteService"]``), and the parsed tree is inspected- exactly like an unquoted one. ``unparsable`` is True if any such- string does not parse or nests deeper than ``_MAX_QUOTE_DEPTH`` (fail- closed: the caller treats the annotation as evaluated).- ``unchecked`` lists, by the line of its outermost string literal,- each such string that sits in a type position, which the caller- reports as an offender: a string that is a plain value -- anywhere- inside ``Annotated`` metadata, a ``Literal[...]`` or the arguments- of a call (``Query(description="...")``) -- is never evaluated as a- type, so it is not reported. ``"*[NoteService]"`` is valid as a- ``ForwardRef`` but not as an expression, so it is unchecked.-- Not parsed: the metadata strings of an ``Annotated[T, "doc"]``- (elements after the first), which are kept as plain values and- never evaluated.+ ``(node, line)`` pairs: ``line`` is None for a node of ``root``+ itself and, for a node parsed out of a string, the line of the+ outermost string literal holding it. FastAPI (via+ ``typing.get_type_hints``) evaluates a quoted annotation, so every+ string in it is parsed as an expression, recursively+ (``"Annotated[NoteService, Depends()]"``, ``Optional["NoteService"]``),+ and the parsed tree is inspected exactly like an unquoted one --+ unless the string is exempt.++ A string is exempt only if every step of its path from the+ annotation's root is one ``_approved_children`` approves (an+ allowlist: what it does not name fails closed). ``root`` is a type+ slot, and a string in a type slot is parsed into a tree whose root+ is a type slot again; the path ends at any other node. So+ ``Literal["NoteService"]``, ``Optional[Literal["NoteService"]]``,+ ``Annotated[str, "NoteService"]``, ``Annotated[str,+ Query(description="NoteService")]`` and ``Annotated[str,+ {"description": "NoteService"}]`` hold exempt strings, and the+ wholly quoted ``"Annotated[Literal['NoteService'], Query()]"`` too,+ while ``Literal["NoteService"].__args__[0]``, ``G |+ Literal["NoteService"]``, ``G[Literal["NoteService"]]`` (``G`` not a+ proven generic head), ``f"{Literal['NoteService']}"``,+ ``Annotated[*(), "NoteService", Depends()]``,+ ``Annotated[Literal["NoteService"], G]`` (see ``_inert_metadata``)+ and ``typing.cast(object, "NoteService")`` do not: below a node no+ rule approves, every string is checked, whatever reads it out, and a+ tree parsed out of a string that is not exempt is off the path as a+ whole.++ A string that is not exempt is parsed (see ``_parse_string``) and+ checked in one of two contexts (see ``_child_contexts``). In a type+ position -- ``root``, and whatever is reached from one other than as+ a call argument, a ``Literal`` member or ``Annotated`` metadata, and+ a ``ForwardRef``'s type argument (the first positional, ``arg=``, or+ an argument whose position is unknown; under any name it is imported+ as or qualified) wherever the call sits -- it is parsed as it is and+ stripped, and one that parses neither way, or that nests deeper than+ ``_MAX_QUOTE_DEPTH``, makes ``unparsable`` True (fail closed: the+ caller treats the annotation as evaluated) and is listed in+ ``unchecked`` by the line of its outermost string literal, which the+ caller reports as an offender. ``"*[NoteService]"`` is valid as a+ ``ForwardRef`` but not as an expression, so in a type position it is+ unchecked. In the argument context it is also parsed the way+ ``ForwardRef`` reads it, as ``(*[NoteService],)[0]``+ (``typing.cast(object, "*[NoteService]")`` hands it on to a type+ position); one that parses no way at all makes ``unparsable`` True+ but is not reported, since ``typing`` cannot resolve it and it may+ be a value, such as a regex, and one nested too deep is reported.+ Literal ``*`` / ``**`` unpacking of call arguments is followed to+ find a ``ForwardRef``'s type argument (see ``_call_arguments``).++ Not seen: a name assembled from pieces as the annotation is+ evaluated (``"Note" + "Service"``, ``f"{'Note'}Service"``), since+ each string is checked on its own; a form, callee or generic head+ changed in a way ``_proven_names`` does not see; and code that+ rewrites ``__annotations__`` after the fact, such as a decorator,+ which no check of the annotation as written can see."""nodes: list[tuple[ast.AST, int | None]] = []unparsable = Falseunchecked: list[int] = []- values: set[int] = set()- # ids of every node in a value (non-type) position.- plain: set[int] = set()- pending: list[tuple[ast.AST, int, int | None, bool]] = [- (root, 0, None, False)+ pending: list[tuple[ast.AST, str, str | None, int, int | None]] = [+ (root, _TYPE, _TYPE_SLOT, 0, None)]while pending:- current, depth, line, in_value = pending.pop()+ current, base, base_slot, depth, line = pending.pop()+ # Contexts and approved-path slots by node id. ast.walk is+ # breadth first, so a node's parent (or the subscript or call+ # whose key or arguments hold it) sets both before the node is+ # reached; a node with no slot is off the path.+ contexts = {id(current): base}+ slots = {id(current): base_slot} if base_slot else {}for node in ast.walk(current):nodes.append((node, line))- if _is_annotated_head(node, annotated) and isinstance(- node.slice, ast.Tuple- ):- values.update(id(meta) for meta in node.slice.elts[1:])- for meta in node.slice.elts[1:]:- plain.update(id(n) for n in ast.walk(meta))- if _is_literal_head(node):- plain.update(id(n) for n in ast.walk(node.slice))- if isinstance(node, ast.Call):- for arg in [*node.args, *node.keywords]:- plain.update(id(n) for n in ast.walk(arg))- if (- not (- isinstance(node, ast.Constant)- and isinstance(node.value, str)- )- or id(node) in values+ context = contexts.get(id(node), _TYPE)+ slot = slots.get(id(node))+ if slot in (_TYPE_SLOT, _METADATA_SLOT):+ slots.update(_approved_children(node, slot, proven))+ for child, given in _child_contexts(+ node, context, annotated, forward_refs, proven):+ contexts.setdefault(id(child), given)+ if slot == _EXEMPT or not _is_string(node):continuehere = node.lineno if line is None else line- is_value = in_value or id(node) in plainif depth >= _MAX_QUOTE_DEPTH:unparsable = True- if not is_value:- unchecked.append(here)+ unchecked.append(here)continue- try:- parsed = ast.parse(node.value.strip(), mode="eval")- except (SyntaxError, ValueError, RecursionError, MemoryError):+ trees = _parse_string(node.value, star=context == _ARGUMENT)+ if not trees:unparsable = True- if not is_value:+ if context == _TYPE:unchecked.append(here)continue- pending.append((parsed.body, depth + 1, here, is_value))+ inner = _TYPE_SLOT if slot == _TYPE_SLOT else None+ for tree in trees:+ pending.append((tree, context, inner, depth + 1, here))return nodes, unparsable, unchecked@@ -841,26 +1615,30 @@ def _annotations(tree: ast.AST) -> list[tuple[ast.AST, bool]]:non-constant metadata element (``Annotated[class, dep]``), astarred element (``Annotated[*(class, dep)]``) or a slice that isnot a tuple (``Annotated[args]``);- * a string in it does not parse as an expression, or nests too- deep (fail closed; one in a type position is also reported- itself, see ``_string_annotation_hits``);+ * a string in it that is not exempt does not parse (see+ ``_annotation_nodes``), or nests too deep (fail closed; one in a type+ position, or nested too deep, is also reported itself, see+ ``_string_annotation_hits``);* it is a class field with no binding in its own class body, on aclass with a base other than ``object`` / ``Generic`` /``Protocol``: the field may inherit a non-constant default.- Every string in a type position is parsed and checked like unquoted- code, recursively (see ``_annotation_nodes``), so a wholly quoted- ``"Annotated[class, Depends()]"`` is not type-only either. A class+ Every string that is not exempt is parsed and checked like+ unquoted code, recursively (see ``_annotation_nodes``), so a wholly+ quoted ``"Annotated[class, Depends()]"`` is not type-only either. A classfield counts wherever it sits in the class body, also under ``if`` /``try`` / ``with`` / loops, and its default is any binding of itsname there (``svc: T`` then ``svc = Depends()``; see``_class_field_defaults``).- Callee names are not matched, so ``Depends`` imported under another- name cannot hide a dependency (fail closed). Return annotations and- module- or function-level variable annotations have no default.+ Callee names are not matched here, so ``Depends`` imported under+ another name cannot hide a dependency (fail closed). Return+ annotations and module- or function-level variable annotations have+ no default."""- annotated = _annotated_names(tree)+ annotated = _annotation_names(tree, "Annotated")+ forward_refs = _annotation_names(tree, "ForwardRef")+ proven = _proven_names(tree)defaults: dict[int, ast.AST] = {}for node in ast.walk(tree):if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):@@ -887,7 +1665,9 @@ def _annotations(tree: ast.AST) -> list[tuple[ast.AST, bool]]:root, default = node.annotation, defaults.get(id(node))else:continue- nodes, unparsable, _unchecked = _annotation_nodes(root, annotated)+ nodes, unparsable, _unchecked = _annotation_nodes(+ root, annotated, forward_refs, proven+ )type_only = ((default is None or isinstance(default, ast.Constant))and not unparsable@@ -920,14 +1700,18 @@ def _string_annotation_hits(Depends()]"``) in the module globals, so a quoted serving name is aslive there as a bare one, and no other rule sees it. Strings areparsed recursively (see ``_annotation_nodes``); one in a type- position that does not parse (or nests too deep) is reported- itself, as an annotation string that cannot be checked."""- annotated = _annotated_names(tree)+ position that does not parse, or any that nests too deep, is+ reported itself, as an annotation string that cannot be checked."""+ annotated = _annotation_names(tree, "Annotated")+ forward_refs = _annotation_names(tree, "ForwardRef")+ proven = _proven_names(tree)hits: list[tuple[int, str]] = []for root, type_only in _annotations(tree):if type_only:continue- nodes, _unparsable, unchecked = _annotation_nodes(root, annotated)+ nodes, _unparsable, unchecked = _annotation_nodes(+ root, annotated, forward_refs, proven+ )hits.extend((line, _UNCHECKED_STRING) for line in unchecked)for inner, line in nodes:if line is None:diff --git a/changelog.d/6634.security.md b/changelog.d/6634.security.mdindex d708b901fb..5acad4a43a 100644--- a/changelog.d/6634.security.md+++ b/changelog.d/6634.security.md@@ -1 +1 @@-Preventive hardening: the `_generate_report_path` helper (which has no production caller; saved reports are named by research ID) now appends a random segment, so the same query in the same second can no longer yield identical filenames in the install-wide reports directory. Two new pre-commit syntax checks, which fence accidental and idiomatic code; deliberate evasion by a contributor is out of scope and left to code review: `check-per-user-isolation` is a fast smoke check that constructions of user-data services/sessions (`NoteService`, `LibraryService`, `DownloadService`, `get_user_db_session`, the three library deletion services, `NoteAIService` and `FollowUpResearchService`) under `web/routers/`, `research_library/` and `web/services/` pass a username explicitly, as a username-named positional argument or a `*username*` keyword, with any such keyword bound to a literal such as `None` flagged (where that username comes from is enforced for router call sites by the cross-user isolation census tests), and `check-reports-dir-not-served` flags, under `web/`, any `FileResponse`, `StaticFiles` or `StreamingResponse` reference or star import outside a per-file allowlist (all of `web/fastapi_app.py`, `web/dependencies/threadpool.py` and `web/static_files.py`), any call to LDR's streaming-response wrapper whose body is not a direct call to an undecorated function defined in the same module (not inside a class) that itself yields, where a non-generator or decorated definition, any other binding, of that name anywhere in the module, or a `from x import *` anywhere in the module (which can rebind any name without the scanner being able to tell which) disqualifies it (so `open(path)`, a helper returning `open(path)`, `iter(...)`, a decorated generator or a path is flagged; the arguments of the generator call are not inspected, so `W(passthru(open(path)))` is accepted), and any serving call, including a call to the `static_file_response` helper, that references the outputs directory inline (also under an import alias), allowlisted files included. Within its scanned tree, neither check lets a fenced callable leave a module under a name it does not recognise: an import alias that drops the role (`WorkerCleanupStreamingResponse as CleanupStream`, `static_file_response as serve`, `get_user_db_session as open_session`; a leading underscore is fine) and any non-call reference (`Download = WorkerCleanupStreamingResponse`, also in an allowlisted file, where only type-only annotations and subclasses named `...StreamingResponse`/`...FileResponse` are exempt) are flagged, so a re-export cannot be imported and called unchecked elsewhere; an attribute read off a fenced callable (`NoteService.__call__`, `get_user_db_session.__wrapped__`, `WorkerCleanupStreamingResponse.__call__`) is such a non-call reference, whether bound or called, and the isolation check exempts only type-only annotations, ALL_CAPS constant reads (`NoteAIService.MAX_CLAIMS_PER_NOTE`) and one pinned staticmethod read (`NoteService._rollback_quietly`); an annotation is not type-only, so a fenced name in it (or quoted in a string in it) is flagged, when it is evaluated into more than a type: a parameter or class-field annotation with a non-constant default (`svc: NoteService = Depends()`, where FastAPI itself constructs the class with `username` taken from the request; a class field counts wherever it sits in the class body, including under `if`/`try`, and takes as its default any binding of its name there, such as `svc: NoteService` followed by `svc = Depends()`), an `Annotated[...]` with non-constant metadata (`Annotated[T, Depends(get_user_db_session)]`), a starred element (`Annotated[*(NoteService, dep)]`) or a non-tuple slice, a call, walrus or lambda inside it, a class field with no binding in its own class body on a class with a base other than `object`/`Generic`/`Protocol` (it may inherit a `Depends()` default), or a string that does not parse; a string in a type position that does not parse as an expression (such as `"*[NoteService]"`, a valid forward reference but not an expression) or nests too deep is itself reported as an annotation string that cannot be checked (call arguments, `Literal` members and `Annotated` metadata are plain values and are exempt); every string in a type position is parsed and checked like unquoted code, recursively, because FastAPI evaluates it, so a wholly quoted `"Annotated[NoteService, Depends()]"` is caught too (`Annotated` metadata strings, which are never evaluated, are not parsed); a symlink inside a scanned directory is scanned even if its target lies elsewhere. The cross-user isolation census additionally flags any router `Depends(...)`/`Security(...)` target (for a bare `Depends()`, the annotated class; qualified `fastapi.Depends`, `dependency=`, `__wrapped__`-style reads, wholly quoted annotations and starred `Annotated` elements included) that takes a username/user_id/owner and is not itself an auth dependency. Both checks report a file they cannot read or parse (including nesting too deep for the parser) instead of skipping it or crashing. It does not cover responses built from file content already read into memory (`Response(content=path.read_bytes())`, `PlainTextResponse(path.read_text())`), a same-module generator that itself reads a file or is handed an open file as an argument, serving helpers defined outside `web/`, renames, re-exports, wrappers or dependency factories in modules outside the scanned directories, `Annotated` reached through an assignment alias (`A = Annotated`) with non-call metadata, constant-valued non-literal `username=` expressions such as `username=str(None)`, dynamic lookups (`getattr`, `importlib`, `__import__`, `module.__dict__[...]`, `eval`), or deliberate evasion such as a default set after the class body or signature (`Cls.attr = Depends()`, `f.__defaults__ = ...`) or by a metaclass, decorator or `__init_subclass__`, walrus bindings in subscript targets or in other annotations, and module-level string or type aliases of a fenced name (`Svc = "NoteService"`); these examples are not exhaustive.+Preventive hardening: the `_generate_report_path` helper (which has no production caller; saved reports are named by research ID) now appends a random segment, so the same query in the same second can no longer yield identical filenames in the install-wide reports directory. Two new pre-commit syntax checks, which fence accidental and idiomatic code; deliberate evasion by a contributor is out of scope and left to code review: `check-per-user-isolation` is a fast smoke check that constructions of user-data services/sessions (`NoteService`, `LibraryService`, `DownloadService`, `get_user_db_session`, the three library deletion services, `NoteAIService` and `FollowUpResearchService`) under `web/routers/`, `research_library/` and `web/services/` pass a username explicitly, as a username-named positional argument or a `*username*` keyword, with any such keyword bound to a literal such as `None` flagged (where that username comes from is enforced for router call sites by the cross-user isolation census tests), and `check-reports-dir-not-served` flags, under `web/`, any `FileResponse`, `StaticFiles` or `StreamingResponse` reference or star import outside a per-file allowlist (all of `web/fastapi_app.py`, `web/dependencies/threadpool.py` and `web/static_files.py`), any call to LDR's streaming-response wrapper whose body is not a direct call to an undecorated function defined in the same module (not inside a class) that itself yields, where a non-generator or decorated definition, any other binding, of that name anywhere in the module, or a `from x import *` anywhere in the module (which can rebind any name without the scanner being able to tell which) disqualifies it (so `open(path)`, a helper returning `open(path)`, `iter(...)`, a decorated generator or a path is flagged; the arguments of the generator call are not inspected, so `W(passthru(open(path)))` is accepted), and any serving call, including a call to the `static_file_response` helper, that references the outputs directory inline (also under an import alias), allowlisted files included. Within its scanned tree, neither check lets a fenced callable leave a module under a name it does not recognise: an import alias that drops the role (`WorkerCleanupStreamingResponse as CleanupStream`, `static_file_response as serve`, `get_user_db_session as open_session`; a leading underscore is fine) and any non-call reference (`Download = WorkerCleanupStreamingResponse`, also in an allowlisted file, where only type-only annotations and subclasses named `...StreamingResponse`/`...FileResponse` are exempt) are flagged, so a re-export cannot be imported and called unchecked elsewhere; an attribute read off a fenced callable (`NoteService.__call__`, `get_user_db_session.__wrapped__`, `WorkerCleanupStreamingResponse.__call__`) is such a non-call reference, whether bound or called, and the isolation check exempts only type-only annotations, ALL_CAPS constant reads (`NoteAIService.MAX_CLAIMS_PER_NOTE`) and one pinned staticmethod read (`NoteService._rollback_quietly`); an annotation is not type-only, so a fenced name in it (or quoted in a string in it) is flagged, when it is evaluated into more than a type: a parameter or class-field annotation with a non-constant default (`svc: NoteService = Depends()`, where FastAPI itself constructs the class with `username` taken from the request; a class field counts wherever it sits in the class body, including under `if`/`try`, and takes as its default any binding of its name there, such as `svc: NoteService` followed by `svc = Depends()`), an `Annotated[...]` with non-constant metadata (`Annotated[T, Depends(get_user_db_session)]`), a starred element (`Annotated[*(NoteService, dep)]`) or a non-tuple slice, a call, walrus or lambda inside it, a class field with no binding in its own class body on a class with a base other than `object`/`Generic`/`Protocol` (it may inherit a `Depends()` default), or a string, other than an exempt one (below), that does not parse; every string in such an annotation is parsed and checked like unquoted code, recursively, because FastAPI evaluates it, so a wholly quoted `"Annotated[NoteService, Depends()]"` is caught too, except exempt strings, which are an allowlist of shapes, so anything it does not name fails closed: a string is exempt only if its whole path from the annotation's root runs through subscripts of a proven generic head (such as `Optional`, `Union` or `list`) and the first element of a proven `Annotated` whose metadata elements are each a constant, a call of a proven listed callee or a dict display (pydantic hands that first element to any other metadata object's `__get_pydantic_core_schema__`, so `Annotated[Literal["NoteService"], G]` is checked), and ends as a string member of a proven `Literal`, as metadata of such an `Annotated` (an element after the first, none of them starred), as a string passed directly to an argument listed for a proven callee from FastAPI, pydantic or `typing` (such as `Query(description=...)`, `NewType("Name", ...)` and `ForwardRef(..., module=...)`), or as a string key or value of a dict without `**` unpacking in that metadata; any other node on the path, such as an attribute read, a subscript of another head, an operator or comparison, an unlisted call, a conditional, a lambda, a walrus, unpacking or an f-string, ends it, so a string that such an expression could read back out into a type position (`Literal["NoteService"].__args__[0]`, `G | Literal["NoteService"]`, `G[Literal["NoteService"]]`, `Query(description="NoteService").description`, `Annotated[*(), "NoteService", Depends()]`) is checked; `Literal` and `Annotated` are proven only when imported from `typing` or `typing_extensions`, a listed callee only when imported from its own module, and a generic head only from `typing`, `typing_extensions` or `collections.abc` or as an unbound builtin, each under a name nothing else in the file binds (so after `from typing import Annotated as Literal`, `Literal["NoteService", Depends()]` is checked as the `Annotated` it is), and nothing in a file is proven if the file could change what a proven name denotes: a star import, a reference to a name that can look up or rewrite a namespace dynamically (such as `setattr`, `vars`, `globals`, `locals`, `__dict__`, `sys.modules`, `importlib`, `exec` or `eval`), an attribute or item store or delete rooted in an imported name (`typing.Literal = typing.Annotated`), in an unbound name or in an expression, a store or delete on any object whose target attribute is named like something a proof rests on (`mod.Literal = ...`) or whose target goes through a dunder or a private attribute of anything but `self` or `cls`, a proven module, or one a proof rests on reached as an attribute, used other than to read an attribute off it (`mod = typing`, `mod = typing_extensions.typing`), a private name of one (`typing._GenericAlias`), or a proven form, listed callee or subscripted generic head used outside a type position (`L = Literal`, `type(typing.List)`); the arguments of any other call are checked as well, so an unknown call that can hand a string on to a type position (`typing.cast(object, "NoteService")`) is caught; a string is parsed both as written, as `ForwardRef` compiles it (so one ending in a line continuation is checked), and stripped of surrounding whitespace; a string in a type position that parses neither way (such as `"*[NoteService]"`, a valid forward reference but not an expression), or any checked string nested too deep, is itself reported as an annotation string that cannot be checked, while a string elsewhere is also read the way `ForwardRef` reads a starred string; a symlink inside a scanned directory is scanned even if its target lies elsewhere. The cross-user isolation census additionally flags any router `Depends(...)`/`Security(...)` target (for a bare `Depends()`, the annotated class; qualified `fastapi.Depends`, `dependency=`, `__wrapped__`-style reads, wholly quoted annotations and starred `Annotated` elements included) that takes a username/user_id/owner and is not itself an auth dependency. Both checks report a file they cannot read or parse (including nesting too deep for the parser) instead of skipping it or crashing. It does not cover responses built from file content already read into memory (`Response(content=path.read_bytes())`, `PlainTextResponse(path.read_text())`), a same-module generator that itself reads a file or is handed an open file as an argument, serving helpers defined outside `web/`, renames, re-exports, wrappers or dependency factories in modules outside the scanned directories, `Annotated` reached through an assignment alias (`A = Annotated`) with non-call metadata, constant-valued non-literal `username=` expressions such as `username=str(None)`, dynamic lookups (`getattr`, `importlib`, `__import__`, `module.__dict__[...]`, `eval`), or deliberate evasion such as a default set after the class body or signature (`Cls.attr = Depends()`, `f.__defaults__ = ...`) or by a metaclass, decorator or `__init_subclass__`, walrus bindings in subscript targets or in other annotations, module-level string or type aliases of a fenced name (`Svc = "NoteService"`), a fenced name assembled from pieces in an annotation (`"Note" + "Service"`, an f-string), a listed callee, `Literal`, `Annotated` or generic subscript head changed from another module, through a dynamic lookup that uses none of the names above (`getattr(m, "Lit" + "eral")`), through a name used only inside a quoted annotation, or through an object derived from it at runtime (`type(Literal["x"])`), and code that rewrites `__annotations__` after the fact, such as a decorator; these examples are not exhaustive.diff --git a/tests/security/test_architecture_fences.py b/tests/security/test_architecture_fences.pyindex c4bcebf711..227540de45 100644--- a/tests/security/test_architecture_fences.py+++ b/tests/security/test_architecture_fences.py@@ -207,6 +207,97 @@ class TestFenceCoverageFloors:"ALLOWED_FILES changed; a new file-serving site needs review ""and a conscious update of this pinned list")+ parameter_text = {+ "alias",+ "description",+ "example",+ "examples",+ "pattern",+ "regex",+ "title",+ }+ for hook in (_isolation_hook, _reports_hook):+ assert {+ callee: set(positions)+ for callee, positions in hook.VALUE_ARGUMENTS.items()+ } == {+ **{+ f"fastapi.{name}": parameter_text+ for name in (+ "Body",+ "Cookie",+ "File",+ "Form",+ "Header",+ "Path",+ "Query",+ )+ },+ "fastapi.Depends": {"scope"},+ "pydantic.Field": {+ "alias",+ "description",+ "examples",+ "pattern",+ "title",+ },+ "pydantic.constr": {"pattern"},+ "typing.ForwardRef": {2, "module"},+ "typing.NewType": {0, "name"},+ }, (+ "VALUE_ARGUMENTS changed; a string passed to a listed "+ "argument is exempt from parsing where its call is proven "+ "and on an approved path, so a new entry needs review and "+ "a conscious update of this pinned table"+ )+ assert hook.PLAIN_FORMS == {+ "typing.Annotated",+ "typing.Literal",+ "typing_extensions.Annotated",+ "typing_extensions.Literal",+ }, (+ "PLAIN_FORMS changed; a listed form's string members or "+ "metadata are exempt from parsing where it is proven and on "+ "an approved path, so a new entry needs review and a "+ "conscious update of this pinned set"+ )+ assert hook._GENERIC_MODULES == {+ "collections.abc",+ "typing",+ "typing_extensions",+ } and hook._GENERIC_BUILTINS == {+ "dict",+ "frozenset",+ "list",+ "set",+ "tuple",+ "type",+ }, (+ "the generic subscript heads changed; a subscript of one "+ "is a step of an approved path, so a new entry needs "+ "review and a conscious update of these pinned sets"+ )+ assert hook._DYNAMIC_NAMES == {+ "__builtins__",+ "__delattr__",+ "__dict__",+ "__import__",+ "__setattr__",+ "delattr",+ "eval",+ "exec",+ "globals",+ "import_module",+ "importlib",+ "locals",+ "modules",+ "setattr",+ "vars",+ }, (+ "_DYNAMIC_NAMES changed; a reference to one voids every "+ "proof in the file, so dropping one lets a file rewrite a "+ "proven form unseen and needs review"+ )class TestPerUserIsolationFence:@@ -730,9 +821,10 @@ class TestPerUserIsolationFence:``_MAX_QUOTE_DEPTH``) is an offender in itself. A class fieldwith no binding in its own body, on a class with a base otherthan ``object`` / ``Generic`` / ``Protocol``, may inherit a- ``Depends()`` default, so it is a reference. Strings that are- plain values (call arguments, ``Literal``, ``Annotated``- metadata) and fields of base-less classes stay accepted."""+ ``Depends()`` default, so it is a reference. Exempt strings (a+ listed ``Query(description=...)`` argument, a ``Literal`` member,+ ``Annotated`` metadata) and fields of base-less classes stay+ accepted."""hooks = _mirror_hooks(tmp_path)deep = "NoteService"for _ in range(_isolation_hook._MAX_QUOTE_DEPTH + 1):@@ -1909,6 +2001,1189 @@ class TestReportsDirNotServedFence:assert result.returncode == 0, "the out-of-scope target is skipped"+ "script,name",+ [(ISOLATION_HOOK, "NoteService"), (REPORTS_HOOK, "FileResponse")],+ ids=["isolation", "reports"],+)[email protected]("quoted", [False, True], ids=["unquoted", "quoted"])+class TestAnnotationPlainValues:+ @pytest.mark.parametrize(+ "annotation",+ [+ 'Annotated[Literal["{name}"], Query()]',+ 'Annotated[str, Query(description="{name}")]',+ 'Annotated[Literal["{name}()"], Query()]',+ 'Annotated[str, {"description": "{name}"}, Query()]',+ 'Annotated[NewType("{name}", str), Query()]',+ 'Annotated[constr(pattern=r"^[A-Z]+$"), Query()]',+ 'Annotated[ForwardRef("str", module="{name}"), Query()]',+ 'Annotated[Optional[Literal["{name}"]], Query()]',+ 'Annotated[list[Literal["{name}"]], Query()]',+ 'Annotated[dict[str, Optional[Literal["{name}"]]], Query()]',+ 'Annotated[str, "{name}", Query()]',+ 'Annotated[str, {"{name}": "a key"}, Query()]',+ 'Annotated[str, Query(None, description="{name}"), "{name}"]',+ "Annotated[Optional[\"Literal['{name}']\"], Query()]",+ ],+ ids=[+ "literal",+ "description",+ "call-text",+ "metadata",+ "newtype-name",+ "constraint-pattern",+ "forward-ref-module",+ "literal-in-a-subscript",+ "literal-in-a-builtin-generic",+ "literal-in-nested-generics",+ "metadata-string",+ "metadata-key",+ "listed-argument-after-a-positional",+ "literal-quoted-in-a-type-slot",+ ],+ )+ def test_plain_strings_do_not_become_references(+ self, tmp_path, script, name, quoted, annotation+ ):+ """Parseable value strings stay data, even in quoted annotations:+ each shape is a path ``_approved_children`` approves, step by+ step, from the annotation's root to the string."""+ hooks = _mirror_hooks(tmp_path)+ annotation = annotation.replace("{name}", name)+ if quoted:+ annotation = repr(annotation)+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/annotation_values.py",+ "from typing import Annotated, ForwardRef, Literal, NewType\n"+ "from typing import Optional\n"+ "from fastapi import Query\n"+ "from pydantic import constr\n"+ f"def route(value: {annotation}):\n"+ " return value\n",+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ assert result.returncode == 0, result.stdout + result.stderr++ def test_quoted_type_references_remain_fenced(+ self, tmp_path, script, name, quoted+ ):+ """A quoted dependency type is still a reference, not a value."""+ hooks = _mirror_hooks(tmp_path)+ annotation = f'Annotated["{name}", Depends()]'+ if quoted:+ annotation = repr(annotation)+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/annotation_dependency.py",+ "from typing import Annotated\n"+ "from fastapi import Depends\n"+ f"def route(value: {annotation}):\n"+ " return value\n",+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ assert result.returncode == 1, result.stdout + result.stderr+ assert f"{router}:3:" in result.stdout+ assert name in result.stdout+++ "script,name",+ [+ (ISOLATION_HOOK, "NoteService"),+ (REPORTS_HOOK, "FileResponse"),+ (REPORTS_HOOK, "static_file_response"),+ ],+ ids=["isolation", "reports-primitive", "reports-helper"],+)[email protected]("quoted", [False, True], ids=["unquoted", "quoted"])+class TestAnnotationForwardReferences:+ @pytest.mark.parametrize(+ "call",+ [+ "ForwardRef({reference})",+ "typing.ForwardRef({reference})",+ "FR({reference})",+ "ForwardRef(arg={reference})",+ "typing.cast(object, ForwardRef({reference}))",+ "ForwardRef(*({reference},))",+ "ForwardRef(**{{'arg': {reference}}})",+ "ForwardRef(*(*({reference},),))",+ "ForwardRef(**{{**{{'arg': {reference}}}}})",+ ],+ ids=[+ "bare",+ "qualified",+ "alias",+ "keyword",+ "nested-call",+ "unpacked-positional",+ "unpacked-keyword",+ "nested-unpacked-positional",+ "nested-unpacked-keyword",+ ],+ )+ def test_forward_reference_type_arguments_remain_fenced(+ self, tmp_path, script, name, quoted, call+ ):+ """ForwardRef arguments are types, including through import aliases."""+ hooks = _mirror_hooks(tmp_path)+ reference = call.format(reference=repr(name))+ annotation = f"Annotated[{reference}, Depends()]"+ if quoted:+ annotation = repr(annotation)+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/forward_reference.py",+ "from __future__ import annotations\n"+ "import typing\n"+ "from typing import Annotated, ForwardRef\n"+ "from typing import ForwardRef as FR\n"+ "from fastapi import Depends\n"+ f"def route(value: {annotation}):\n"+ " return value\n",+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ assert result.returncode == 1, result.stdout + result.stderr+ assert f"{router}:6:" in result.stdout+ assert name in result.stdout++ @pytest.mark.parametrize("invalid", ["syntax", "depth"])+ def test_unchecked_forward_reference_strings_are_rejected(+ self, tmp_path, script, name, quoted, invalid+ ):+ """ForwardRef strings retain the parser's fail-closed checks."""+ hooks = _mirror_hooks(tmp_path)+ reference = "not a ) type" if invalid == "syntax" else name+ if invalid == "depth":+ for _ in range(_isolation_hook._MAX_QUOTE_DEPTH + 1):+ reference = repr(reference)+ annotation = f"Annotated[ForwardRef({reference!r}), Depends()]"+ if quoted:+ annotation = repr(annotation)+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/unchecked_forward_ref.py",+ "from __future__ import annotations\n"+ "from typing import Annotated, ForwardRef\n"+ "from fastapi import Depends\n"+ f"def route(value: {annotation}):\n"+ " return value\n",+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ assert result.returncode == 1, result.stdout + result.stderr+ assert f"{router}:4: annotation string that cannot be checked" in (+ result.stdout+ )+++def _reported(+ result: subprocess.CompletedProcess, router: str, line: int, name: str+) -> bool:+ """True if the hook reported ``name`` on line ``line`` of ``router``."""+ prefix = f"{router}:{line}:"+ return any(+ out.lstrip().startswith(prefix) and name in out+ for out in result.stdout.splitlines()+ )+++#: Fenced names quoted where ``typing`` can resolve them although no rule+#: knows the call: an argument a call may hand on to a type position, a+#: ``Literal`` member other than a plain string, or a ``ForwardRef`` that+#: is evaluated by calling it (even in metadata, where FastAPI then gets+#: the ``Depends``). ``{ref}`` is the quoted name, ``{name}`` the bare one.+_TYPE_STRING_CALLS = {+ "cast": "Annotated[typing.cast(object, {ref}), Depends()]",+ "cast-union": (+ "Annotated[typing.cast(type, typing.Union[{ref}]), Depends()]"+ ),+ "str": "Annotated[str({ref}), Depends()]",+ "unknown-callee": "Annotated[convert({ref}), Depends()]",+ "unknown-callee-in-metadata": "Annotated[str, Depends(convert({ref}))]",+ "non-literal-mapping": (+ "Annotated[ForwardRef(**dict(arg={ref})), Depends()]"+ ),+ "type-check": 'Annotated[typing._type_check({ref}, ""), Depends()]',+ "dunder-call": "Annotated[ForwardRef.__call__({ref}), Depends()]",+ "literal-forward-ref": "Annotated[Literal[ForwardRef({ref})], Depends()]",+ "literal-generic": "Annotated[Literal[Optional[{ref}]], Depends()]",+ "star-form": 'Annotated[typing.cast(object, "*[{name}]"), Depends()]',+ "evaluated-forward-ref": (+ 'Annotated[str, ForwardRef("Depends({name})", module=__name__)'+ ".evaluate()]"+ ),+}++#: VALUE_ARGUMENTS callees that build a type: fixtures call them in the+#: annotation's type position, the others in its metadata.+_TYPE_CONSTRUCTORS = frozenset(+ {"typing.NewType", "typing.ForwardRef", "pydantic.constr"}+)+++def _value_argument_calls(+ callee: str, position: int | str, probe: str+) -> tuple[str, str]:+ """``(listed, neighbour)`` calls of ``callee``: ``probe`` in the+ listed argument ``position``, then in a neighbouring argument that+ VALUE_ARGUMENTS does not list."""+ if callee == "typing.NewType" and position == 0:+ return f"NewType({probe}, str)", f"NewType('Label', {probe})"+ if callee == "typing.NewType" and position == "name":+ return (+ f"NewType(name={probe}, tp=str)",+ f"NewType(name='Label', tp={probe})",+ )+ if callee == "typing.ForwardRef" and position == 2:+ return (+ f"ForwardRef('str', True, {probe})",+ f"ForwardRef('str', {probe}, 'builtins')",+ )+ if callee == "typing.ForwardRef" and position == "module":+ return (+ f"ForwardRef('str', module={probe})",+ f"ForwardRef({probe}, module='builtins')",+ )+ if callee == "pydantic.constr" and isinstance(position, str):+ return f"constr({position}={probe})", f"constr(max_length={probe})"+ if callee.startswith(("fastapi.", "pydantic.")) and isinstance(+ position, str+ ):+ # A keyword after the positional default (or dependency).+ local = callee.rpartition(".")[2]+ return (+ f"{local}(None, {position}={probe})",+ f"{local}({probe}, {position}=None)",+ )+ raise AssertionError(f"no fixture for {callee} {position!r}")+++#: ``(lines before the route, annotation, accepted)``: a VALUE_ARGUMENTS+#: exemption needs the callee imported from its own module under a name+#: nothing else in the file binds, in a file that cannot change it (see+#: ``_proven_names``); any other callee's arguments are parsed.+_VALUE_CALLEE_BINDINGS = {+ "import-alias": (+ "from fastapi import Query as Q\n",+ "Annotated[str, Q(description={ref})]",+ True,+ ),+ "module-attribute": (+ "import fastapi\n",+ "Annotated[str, fastapi.Query(description={ref})]",+ True,+ ),+ "module-alias": (+ "import typing as t\n",+ "Annotated[t.NewType({ref}, str), Depends()]",+ True,+ ),+ "local-def": (+ "def Query(**kw):\n return kw['description']\n",+ "Annotated[Query(description={ref}), Depends()]",+ False,+ ),+ "rebound": (+ "from fastapi import Query\nQuery = lambda **kw: kw['description']\n",+ "Annotated[Query(description={ref}), Depends()]",+ False,+ ),+ "relative-import": (+ "from .compat import Query\n",+ "Annotated[Query(description={ref}), Depends()]",+ False,+ ),+ "two-imports": (+ "from fastapi import Query\nfrom .compat import Query\n",+ "Annotated[Query(description={ref}), Depends()]",+ False,+ ),+ "star-import": (+ "from fastapi import Query\nfrom .compat import *\n",+ "Annotated[Query(description={ref}), Depends()]",+ False,+ ),+ "unlisted-module": (+ "from fastapi import params\n",+ "Annotated[str, params.Query(description={ref})]",+ False,+ ),+ "forward-ref-elsewhere": (+ "from compat import ForwardRef\n",+ "Annotated[str, {{'r': ForwardRef({ref})}}]",+ False,+ ),+ "module-replaced": (+ "import fastapi\n"+ "fastapi.Query = lambda **kw: kw['description']\n"+ "from fastapi import Query\n",+ "Annotated[Query(description={ref}), Depends()]",+ False,+ ),+ "callee-mutated": (+ "from fastapi import Query\n"+ "Query.__code__ = (lambda **kw: kw['description']).__code__\n",+ "Annotated[Query(description={ref}), Depends()]",+ False,+ ),+}+++ "script,name",+ [(ISOLATION_HOOK, "NoteService"), (REPORTS_HOOK, "FileResponse")],+ ids=["isolation", "reports"],+)[email protected]("quoted", [False, True], ids=["unquoted", "quoted"])+class TestAnnotationCallArguments:+ @pytest.mark.parametrize(+ "shape", list(_TYPE_STRING_CALLS), ids=list(_TYPE_STRING_CALLS)+ )+ def test_strings_a_call_may_hand_to_a_type_are_rejected(+ self, tmp_path, script, name, quoted, shape+ ):+ """An argument of a call no rule knows is parsed and checked (fail+ closed): the callee may return it into a type position, which+ FastAPI resolves (``typing.cast(object, "NoteService")`` builds+ NoteService with ``username`` from the request). A ``Literal``+ member other than a plain string is resolved by ``typing`` too,+ and a call no rule lists ends the approved path, so a+ ``ForwardRef`` evaluated in metadata is checked."""+ hooks = _mirror_hooks(tmp_path)+ annotation = _TYPE_STRING_CALLS[shape].format(ref=repr(name), name=name)+ if quoted:+ annotation = repr(annotation)+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/call_arguments.py",+ "import typing\n"+ "from typing import Annotated, ForwardRef, Literal, Optional\n"+ "from fastapi import Depends\n"+ f"def route(value: {annotation}):\n"+ " return value\n",+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, 4, name), result.stdout++ def test_value_arguments_are_exempt_only_where_listed(+ self, tmp_path, script, name, quoted+ ):+ """For every VALUE_ARGUMENTS entry, the fenced name quoted in the+ listed argument is exempt, and the same string in a neighbouring+ argument that is not listed is parsed and reported."""+ hooks = _mirror_hooks(tmp_path)+ lines = [+ "from typing import Annotated, ForwardRef, NewType",+ "from fastapi import Body, Cookie, Depends, File, Form, Header",+ "from fastapi import Path, Query",+ "from pydantic import Field, constr",+ ]+ listed: list[tuple[int, str, int | str]] = []+ neighbours: list[tuple[int, str, int | str]] = []+ for callee, positions in sorted(+ _isolation_hook.VALUE_ARGUMENTS.items()+ ):+ for position in sorted(positions, key=str):+ calls = _value_argument_calls(callee, position, repr(name))+ for call, found in zip(calls, (listed, neighbours)):+ if callee in _TYPE_CONSTRUCTORS:+ annotation = f"Annotated[{call}, Query()]"+ else:+ annotation = f"Annotated[str, {call}]"+ if quoted:+ annotation = repr(annotation)+ lineno = len(lines) + 1+ lines.append(+ f"def route_{lineno}(value: {annotation}): return value"+ )+ found.append((lineno, callee, position))+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/value_arguments.py",+ "\n".join(lines) + "\n",+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ assert result.returncode == 1, result.stdout + result.stderr+ for lineno, callee, position in listed:+ assert f"{router}:{lineno}:" not in result.stdout, (+ f"{callee} {position!r} is listed, so its string is a value"+ )+ for lineno, callee, position in neighbours:+ assert _reported(result, router, lineno, name), (+ f"{callee}: the argument next to {position!r} was not parsed"+ )++ @pytest.mark.parametrize(+ "binding",+ list(_VALUE_CALLEE_BINDINGS),+ ids=list(_VALUE_CALLEE_BINDINGS),+ )+ def test_value_arguments_need_the_callee_imported_from_its_module(+ self, tmp_path, script, name, quoted, binding+ ):+ """A listed argument is exempt only for a callee provably the+ listed one: imported from its module (or read off the imported+ module) under a name nothing else binds, in a file that cannot+ change it. A local pass-through named ``Query``, a rebinding, a+ relative or star import, another module's ``Query``, another+ ``ForwardRef``, a ``Query`` replaced on its module or with an+ attribute assigned is an unknown callee, whose arguments are+ parsed."""+ hooks = _mirror_hooks(tmp_path)+ prelude, template, accepted = _VALUE_CALLEE_BINDINGS[binding]+ annotation = template.format(ref=repr(name))+ if quoted:+ annotation = repr(annotation)+ source = (+ "import typing\n"+ "from typing import Annotated\n"+ "from fastapi import Depends\n"+ f"{prelude}"+ f"def route(value: {annotation}):\n"+ " return value\n"+ )+ lineno = source.count("\n", 0, source.index("def route(")) + 1+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/value_callees.py",+ source,+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ if accepted:+ assert result.returncode == 0, result.stdout + result.stderr+ else:+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, lineno, name), result.stdout++ def test_call_arguments_nested_too_deep_are_rejected(+ self, tmp_path, script, name, quoted+ ):+ """``typing`` resolves nested quotes one level at a time, so a call+ argument quoted deeper than ``_MAX_QUOTE_DEPTH`` cannot be checked+ and is reported, as in a type position."""+ hooks = _mirror_hooks(tmp_path)+ reference = name+ for _ in range(_isolation_hook._MAX_QUOTE_DEPTH + 1):+ reference = repr(reference)+ annotation = f"Annotated[typing.cast(object, {reference}), Depends()]"+ if quoted:+ annotation = repr(annotation)+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/deep_argument.py",+ "import typing\n"+ "from typing import Annotated\n"+ "from fastapi import Depends\n"+ f"def route(value: {annotation}):\n"+ " return value\n",+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ assert result.returncode == 1, result.stdout + result.stderr+ assert f"{router}:4: annotation string that cannot be checked" in (+ result.stdout+ )+++#: Strings read back out of their ``Literal``, ``Annotated`` or listed+#: call -- through an attribute read, a subscript, a call, or a subscript+#: of a head that is not a proven generic, whose ``__class_getitem__``+#: gets the key -- into a type position, and ``Annotated`` metadata after+#: a starred first element, which may be the type. ``_approved_children``+#: approves none of these paths, so each string is checked.+#: ``typing.get_type_hints`` resolves each to the class or to a type+#: holding it, a type position the hooks check as they check+#: ``Optional["NoteService"]``; the fixtures default the parameter to+#: ``Depends()``, and most of these then make FastAPI build the class+#: with ``username`` taken from the request. ``{ref}`` is the quoted+#: name, ``{name}`` the bare one, ``{literal}`` the quoted+#: ``Literal[...]`` of it; ``G`` reads the string out of its key or an+#: operand.+_READ_OUT_VALUES = {+ "literal-args": "Literal[{ref}].__args__[0]",+ "get-args": "typing.get_args(Literal[{ref}])[0]",+ "metadata-list": "Annotated[str, [{ref}]].__metadata__[0][0]",+ "metadata-string": "Annotated[int, {ref}].__metadata__[0]",+ "metadata-forward-ref": (+ "Annotated[str, ForwardRef({ref})].__metadata__[0]"+ ),+ "description": "Query(description={ref}).description",+ "getattr": "getattr(Query(description={ref}), 'description')",+ "newtype-name": "NewType({ref}, str).__name__",+ "forward-ref-module": (+ "ForwardRef('str', module={ref}).__forward_module__"+ ),+ "through-a-tuple": "(Literal[{ref}],)[0].__args__[0]",+ "in-a-type": "Optional[Literal[{ref}].__args__[0]]",+ "as-annotated-type": "Annotated[Literal[{ref}].__args__[0], Depends()]",+ "parsed-string": "eval({literal}).__args__[0]",+ "class-getitem-literal": "G[Literal[{ref}]]",+ "class-getitem-description": "G[Query(description={ref})]",+ "starred-first-element": "Annotated[*(), {ref}, Depends()]",+}++#: Off-path shapes whose string stays a value or never reaches a type+#: position, checked all the same (fail closed): the allowlist approves+#: paths, not outcomes, so a form read out inside metadata or a listed+#: argument, and the object of a subscript whose head is not a proven+#: generic, are checked whatever the expression does with them.+_READ_OUT_FAIL_CLOSED = {+ "in-metadata": "Annotated[str, Literal[{ref}].__args__[0]]",+ "in-a-listed-argument": (+ "Annotated[str, Query(description=Literal[{ref}].__args__[0])]"+ ),+ "forward-ref-in-metadata": (+ "Annotated[str, ForwardRef({ref}).__forward_arg__]"+ ),+ "subscript-object": "Annotated[List[T], {ref}][int]",+}++#: Strings on a path ``_approved_children`` does not approve, whatever+#: the node that ends it: an operator, comparison, boolean or unary+#: operator, conditional, walrus, lambda, f-string, a subscript of a head+#: that is not a proven generic, a list, a ``Literal`` in metadata, an+#: ``Annotated`` whose metadata holds an object pydantic hands the type+#: to, a dict outside metadata or with ``**``, literal unpacking into a+#: listed callee, a ``ForwardRef`` held in metadata, a starred+#: ``Literal`` member, or a string parsed out of a call argument. Several+#: read the string back out into a type position (``G |+#: Literal["NoteService"]`` runs ``G``'s ``__or__``, and+#: ``Annotated[Literal["NoteService"], G]`` its+#: ``__get_pydantic_core_schema__``), and each is checked.+_UNAPPROVED_PATHS = {+ "or": "G | Literal[{ref}]",+ "add": "Literal[{ref}] + G",+ "add-description": "Query(description={ref}) + G",+ "compare": "G < Literal[{ref}]",+ "matmul": "G @ Annotated[int, {ref}]",+ "boolean": "G or Literal[{ref}]",+ "unary": "~Literal[{ref}]",+ "conditional": "Literal[{ref}] if G else G",+ "walrus": "(alias := Literal[{ref}])",+ "lambda": "(lambda: Literal[{ref}])()",+ "f-string": "f\"{{Literal[{ref}]}}{{str('.__args__[0]')}}\"",+ "f-string-description": 'f"{{Query(description={ref}).description}}"',+ "metadata-subscript": "Annotated[str, G[{ref}]]",+ "metadata-object": "Annotated[Literal[{ref}], G]",+ "metadata-unlisted-call": "Annotated[Literal[{ref}], G()]",+ "metadata-list": "Annotated[str, [{ref}]]",+ "metadata-literal": "Annotated[str, Literal[{ref}]]",+ "metadata-forward-ref": "Annotated[str, {{'r': ForwardRef({ref})}}]",+ "dict-unpacking": "Annotated[str, {{**{{}}, 'd': {ref}}}]",+ "dict-in-a-type-slot": "Annotated[{{'d': {ref}}}, Query()]",+ "unpacked-positional": (+ "Annotated[ForwardRef(*('str', True, {ref})), Query()]"+ ),+ "unpacked-keyword": (+ "Annotated[ForwardRef(**{{'arg': 'str', 'module': {ref}}}), Query()]"+ ),+ "unpacked-description": "Annotated[str, Query(**{{'description': {ref}}})]",+ "starred-literal-member": "Literal[*({ref},)]",+ "parsed-out-of-an-argument": "typing.cast(object, {literal}).__args__[0]",+}++#: ``{change: (lines before the route, annotation)}``: in-file code+#: through which a file could change what a proven name denotes, each+#: caught by a different rule of ``_proven_names``. The annotation alone+#: holds an exempt string; after the change nothing in the file is+#: proven, so the string is checked. ``G`` stands for any replacement.+_PROOF_CHANGES = {+ "star-import": ("from compat import *\n", "Literal[{ref}]"),+ "setattr": (+ "setattr(typing, 'Literal', typing.Annotated)\n",+ "Literal[{ref}]",+ ),+ "vars": ("vars(typing)['Literal'] = typing.Annotated\n", "Literal[{ref}]"),+ "globals": ("globals()['Literal'] = typing.Annotated\n", "Literal[{ref}]"),+ "locals": ("locals()['Literal'] = typing.Annotated\n", "Literal[{ref}]"),+ "sys-modules": (+ "import sys\nalias = sys.modules['typing']\nalias.Union = G\n",+ "Optional[Literal[{ref}]]",+ ),+ "exec": (+ "exec('import typing; typing.Literal = typing.Annotated')\n",+ "Literal[{ref}]",+ ),+ "import-module": (+ "from importlib import import_module as load\n"+ "alias = load('typing')\nalias.Union = G\n",+ "Optional[Literal[{ref}]]",+ ),+ "imported-root": (+ "try:\n"+ " import fastapi.params as params\n"+ "except ImportError:\n"+ " params = None\n"+ "params.Query.default = G\n",+ "Annotated[str, Query(description={ref})]",+ ),+ "unbound-root": (+ "bound_elsewhere.copy_with = G\n",+ "List[Literal[{ref}]]",+ ),+ "expression-root": ("get_alias().copy_with = G\n", "List[Literal[{ref}]]"),+ "attribute-named-like-a-form": (+ "def rebind(module):\n module.Literal = G\n",+ "Literal[{ref}]",+ ),+ "dunder-in-a-target": (+ "class Patch:\n"+ " def apply(self):\n"+ " self.__class__.copy_with = G\n",+ "List[Literal[{ref}]]",+ ),+ "private-attribute": (+ "def patch(form):\n form._getitem = G\n",+ "Literal[{ref}]",+ ),+ "module-alias": ("alias = typing\n", "Literal[{ref}]"),+ "module-through-a-module": (+ "import typing_extensions\nalias = typing_extensions.typing\n",+ "Literal[{ref}]",+ ),+ "private-module-attribute": (+ "alias = typing._SpecialGenericAlias\n",+ "List[Literal[{ref}]]",+ ),+ "private-import": (+ "from typing import _GenericAlias\n",+ "List[Literal[{ref}]]",+ ),+ "form-alias": ("alias = Literal\n", "Literal[{ref}]"),+ "callee-alias": (+ "alias = ForwardRef\n",+ "Annotated[ForwardRef('str', module={ref}), Query()]",+ ),+ "head-class": (+ "alias = type(List)\nRows = List[int]\n",+ "List[Literal[{ref}]]",+ ),+}++#: Ordinary code that leaves every proof standing: a subscripted generic+#: head used as a whole annotation or in the key of a proven head,+#: ``typing.TYPE_CHECKING``, a builtin passed to ``isinstance``, ``from+#: importlib import resources``, and stores on objects the file binds+#: (attributes of ``self``, private ones included, and of a local).+_PROOF_KEEPING = (+ "from typing import Dict\n"+ "from importlib import resources\n"+ "Rows = List[Dict]\n"+ "Table = dict[str, Dict]\n"+ "Cells = Dict[str, int]\n"+ "def helper(value: Dict) -> Dict:\n"+ " if typing.TYPE_CHECKING or isinstance(value, dict):\n"+ " return value\n"+ " return resources\n"+ "class Holder:\n"+ " def __init__(self):\n"+ " self._cache = {}\n"+ " self._cache['key'] = 1\n"+ " self.items = []\n"+ "record = Holder()\n"+ "record.items = [1]\n"+)++#: The lines before the route in the read-out fixtures: ``G`` reads the+#: string back out of its key, of the other operand of an operator, and+#: of the type pydantic hands it as ``Annotated`` metadata.+_READ_OUT_PRELUDE = (+ "import typing\n"+ "from typing import Annotated, ForwardRef, List, Literal, NewType\n"+ "from typing import Optional, TypeVar\n"+ "from fastapi import Depends, Query\n"+ 'T = TypeVar("T")\n'+ "def _read(value):\n"+ " return getattr(value, 'description', None) or (\n"+ " typing.get_args(value)[0]\n"+ " )\n"+ "class _Reader(type):\n"+ " def __or__(cls, other):\n"+ " return _read(other)\n"+ " __ror__ = __add__ = __radd__ = __lt__ = __gt__ = __or__\n"+ " __matmul__ = __rmatmul__ = __or__\n"+ "class G(metaclass=_Reader):\n"+ " def __class_getitem__(cls, key):\n"+ " return _read(key)\n"+ " @classmethod\n"+ " def __get_pydantic_core_schema__(cls, source, handler):\n"+ " return handler(_read(source))\n"+)++#: ``(lines before the route, annotation, accepted)``: ``Literal`` and+#: ``Annotated`` hold exempt strings only as the forms ``typing`` and+#: ``typing_extensions`` define, imported under a name nothing else in+#: the file binds, in a file that cannot change them; a head merely+#: named like one is checked.+_FORM_BINDINGS = {+ "typing": (+ "from typing import Literal\n",+ "Annotated[Literal[{ref}], Depends()]",+ True,+ ),+ "import-alias": (+ "from typing import Literal as L\n",+ "Annotated[L[{ref}], Depends()]",+ True,+ ),+ "module-attribute": (+ "import typing as t\n",+ "Annotated[t.Literal[{ref}], Depends()]",+ True,+ ),+ "typing-extensions": (+ "from typing_extensions import Literal\n",+ "Annotated[Literal[{ref}], Depends()]",+ True,+ ),+ "typing-extensions-annotated": (+ "from typing_extensions import Annotated as A\n",+ "A[str, {ref}, Depends()]",+ True,+ ),+ "annotated-as-literal": (+ "from typing import Annotated as Literal\n",+ "Literal[{ref}, Depends()]",+ False,+ ),+ "optional-as-literal": (+ "from typing import Optional as Literal\n",+ "Literal[{ref}, Depends()]",+ False,+ ),+ "assigned": (+ "Literal = typing.Annotated\n",+ "Literal[{ref}, Depends()]",+ False,+ ),+ "other-module": (+ "from compat import Literal\n",+ "Literal[{ref}, Depends()]",+ False,+ ),+ "other-module-attribute": (+ "import compat\n",+ "compat.Literal[{ref}, Depends()]",+ False,+ ),+ "two-imports": (+ "from typing import Literal\nfrom typing_extensions import Literal\n",+ "Literal[{ref}, Depends()]",+ False,+ ),+ "star-import": (+ "from typing import Literal\nfrom .compat import *\n",+ "Literal[{ref}, Depends()]",+ False,+ ),+ "rebound-annotated": (+ "Annotated = typing.Annotated\n",+ "Annotated[str, {ref}, Depends()]",+ False,+ ),+ "module-replaced": (+ "typing.Literal = typing.Annotated\nfrom typing import Literal\n",+ "Literal[{ref}, Depends()]",+ False,+ ),+ "module-item-replaced": (+ "typing.__dict__['Literal'] = typing.Annotated\n"+ "from typing import Literal\n",+ "Literal[{ref}, Depends()]",+ False,+ ),+}+++#: ``(lines before the route, annotation, accepted)``: a subscript is a+#: step of an approved path only under a head provably from ``typing``,+#: ``typing_extensions`` or ``collections.abc`` or a builtin generic;+#: ``G`` reads the string out of its key, and ``typing`` resolves the+#: annotation to a type holding the class wherever ``G`` stands in.+_GENERIC_HEAD_BINDINGS = {+ "builtin": ("", "Annotated[list[Literal[{ref}]], Depends()]", True),+ "typing": ("", "Annotated[typing.List[Literal[{ref}]], Depends()]", True),+ "builtin-rebound": (+ "list = G\n",+ "Annotated[list[Literal[{ref}]], Depends()]",+ False,+ ),+ "builtins-replaced": (+ "import builtins\nbuiltins.list = G\n",+ "Annotated[list[Literal[{ref}]], Depends()]",+ False,+ ),+ "dunder-builtins-replaced": (+ "__builtins__['list'] = G\n",+ "Annotated[list[Literal[{ref}]], Depends()]",+ False,+ ),+ "typing-replaced": (+ "typing.List = G\n",+ "Annotated[typing.List[Literal[{ref}]], Depends()]",+ False,+ ),+ "user-generic": (+ "class Page(typing.Generic[T]):\n pass\n",+ "Annotated[Page[Literal[{ref}]], Depends()]",+ False,+ ),+}+++def _read_out_route(+ tmp_path: Path,+ script: str,+ template: str,+ name: str,+ quoted: bool,+ extra: str = "",+) -> tuple[subprocess.CompletedProcess, str, int]:+ """Run ``script`` on a router whose route parameter is annotated with+ ``template`` and defaults to ``Depends()``, after the read-out+ prelude and ``extra``; ``(result, router, line of the route)``."""+ hooks = _mirror_hooks(tmp_path)+ annotation = template.format(+ ref=repr(name), name=name, literal=repr(f"Literal[{name!r}]")+ )+ if quoted:+ annotation = repr(annotation)+ source = (+ f"{_READ_OUT_PRELUDE}"+ f"{extra}"+ f"def route(value: {annotation} = Depends()):\n"+ " return value\n"+ )+ lineno = source.count("\n", 0, source.index("def route(")) + 1+ router = _write(+ tmp_path, "src/local_deep_research/web/routers/read_out.py", source+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ return result, router, lineno+++ "script,name",+ [(ISOLATION_HOOK, "NoteService"), (REPORTS_HOOK, "FileResponse")],+ ids=["isolation", "reports"],+)[email protected]("quoted", [False, True], ids=["unquoted", "quoted"])+class TestAnnotationPlainValueProvenance:+ @pytest.mark.parametrize(+ "shape", list(_READ_OUT_VALUES), ids=list(_READ_OUT_VALUES)+ )+ def test_plain_values_read_out_are_rejected(+ self, tmp_path, script, name, quoted, shape+ ):+ """A ``Literal``, ``Annotated`` or listed call holds exempt strings+ only on an approved path, and none of these is one:+ ``Literal["NoteService"].__args__[0]``,+ ``typing.get_args(Literal["NoteService"])[0]``,+ ``Query(description="NoteService").description`` or a subscript+ whose ``__class_getitem__`` reads its key hands the string on to+ a type position, which FastAPI resolves (with a ``Depends()``+ default it builds NoteService, ``username`` taken from the+ request), so those strings are checked. So is ``Annotated``+ metadata after a starred first element, which may be the type."""+ result, router, lineno = _read_out_route(+ tmp_path, script, _READ_OUT_VALUES[shape], name, quoted+ )+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, lineno, name), result.stdout++ @pytest.mark.parametrize(+ "shape", list(_READ_OUT_FAIL_CLOSED), ids=list(_READ_OUT_FAIL_CLOSED)+ )+ def test_read_out_values_are_checked_where_they_stay_plain(+ self, tmp_path, script, name, quoted, shape+ ):+ """Fail closed: the allowlist approves paths, not outcomes, so a+ form read out is checked even where what it yields stays a value+ -- inside metadata or a listed argument -- and so is the object+ of a subscript whose head is not a proven generic+ (``Annotated[List[T], "NoteService"][int]`` keeps the string as+ metadata)."""+ result, router, lineno = _read_out_route(+ tmp_path, script, _READ_OUT_FAIL_CLOSED[shape], name, quoted+ )+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, lineno, name), result.stdout++ @pytest.mark.parametrize(+ "binding",+ list(_GENERIC_HEAD_BINDINGS),+ ids=list(_GENERIC_HEAD_BINDINGS),+ )+ def test_subscript_keys_stay_plain_only_under_a_generic_head(+ self, tmp_path, script, name, quoted, binding+ ):+ """A subscript hands its key to ``__class_getitem__``, which can+ read a string back out of it (``G[Literal["NoteService"]]``+ resolves to the class), so a subscript is a step of an approved+ path only under a head provably from ``typing``,+ ``typing_extensions`` or ``collections.abc`` or a builtin+ generic: not one rebound or replaced in the file (``list =+ G``, ``builtins.list = G``, ``typing.List = G``), and not a+ class of the project's own (fail closed)."""+ hooks = _mirror_hooks(tmp_path)+ prelude, template, accepted = _GENERIC_HEAD_BINDINGS[binding]+ annotation = template.format(ref=repr(name))+ if quoted:+ annotation = repr(annotation)+ source = (+ f"{_READ_OUT_PRELUDE}"+ f"{prelude}"+ f"def route(value: {annotation}):\n"+ " return value\n"+ )+ lineno = source.count("\n", 0, source.index("def route(")) + 1+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/generic_heads.py",+ source,+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ if accepted:+ assert result.returncode == 0, result.stdout + result.stderr+ else:+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, lineno, name), result.stdout++ @pytest.mark.parametrize(+ "binding", list(_FORM_BINDINGS), ids=list(_FORM_BINDINGS)+ )+ def test_plain_forms_need_the_form_imported_from_typing(+ self, tmp_path, script, name, quoted, binding+ ):+ """``Literal`` and ``Annotated`` hold exempt strings only where the+ head is provably the form ``typing`` or ``typing_extensions``+ defines, as a VALUE_ARGUMENTS callee must be: after ``from typing+ import Annotated as Literal``, ``Literal["NoteService",+ Depends()]`` is an ``Annotated`` whose type FastAPI builds. A head+ merely named ``Literal`` or ``Annotated`` (another module's, an+ assignment or rebinding, a second import, a star import, or one+ whose module has ``Literal`` replaced in the file) is checked; a+ proven alias is not."""+ hooks = _mirror_hooks(tmp_path)+ prelude, template, accepted = _FORM_BINDINGS[binding]+ annotation = template.format(ref=repr(name))+ if quoted:+ annotation = repr(annotation)+ source = (+ "import typing\n"+ "from typing import Annotated\n"+ "from fastapi import Depends\n"+ f"{prelude}"+ f"def route(value: {annotation}):\n"+ " return value\n"+ )+ lineno = source.count("\n", 0, source.index("def route(")) + 1+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/plain_forms.py",+ source,+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ if accepted:+ assert result.returncode == 0, result.stdout + result.stderr+ else:+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, lineno, name), result.stdout++ @pytest.mark.parametrize(+ "shape", list(_UNAPPROVED_PATHS), ids=list(_UNAPPROVED_PATHS)+ )+ def test_strings_off_an_approved_path_are_checked(+ self, tmp_path, script, name, quoted, shape+ ):+ """Exemption is an allowlist of shapes, so any node it does not+ approve ends the path, whatever its kind, and the string under it+ is checked: ``G | Literal["NoteService"]`` runs ``G``'s+ ``__or__``, which reads the string back out into a type position+ (with a ``Depends()`` default FastAPI then builds NoteService,+ ``username`` taken from the request)."""+ result, router, lineno = _read_out_route(+ tmp_path, script, _UNAPPROVED_PATHS[shape], name, quoted+ )+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, lineno, name), result.stdout++ @pytest.mark.parametrize(+ "change", list(_PROOF_CHANGES), ids=list(_PROOF_CHANGES)+ )+ def test_a_file_that_may_change_a_proven_name_proves_nothing(+ self, tmp_path, script, name, quoted, change+ ):+ """Provenance fails closed: the annotation alone holds an exempt+ string, and after code through which the file could change what a+ proven name denotes (a dynamic namespace write, a store rooted in+ an import, an attribute store named like a form, an alias of a+ form or module ...) nothing in the file is proven, so the string+ is checked."""+ prelude, template = _PROOF_CHANGES[change]+ result, router, lineno = _read_out_route(+ tmp_path, script, template, name, quoted+ )+ assert result.returncode == 0, result.stdout + result.stderr+ result, router, lineno = _read_out_route(+ tmp_path, script, template, name, quoted, prelude+ )+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, lineno, name), result.stdout++ @pytest.mark.parametrize(+ "template",+ [+ "Literal[{ref}]",+ "Optional[Literal[{ref}]]",+ "Annotated[str, Query(description={ref})]",+ "Annotated[str, {{'description': {ref}}}]",+ ],+ ids=["literal", "generic-head", "listed-argument", "metadata-dict"],+ )+ def test_ordinary_code_keeps_the_proofs(+ self, tmp_path, script, name, quoted, template+ ):+ """A generic head used as a whole annotation or in the key of a+ proven head, ``typing.TYPE_CHECKING``, ``isinstance(x, dict)``,+ ``from importlib import resources`` and stores on objects the+ file binds leave every proof standing."""+ result, _router, _lineno = _read_out_route(+ tmp_path, script, template, name, quoted, _PROOF_KEEPING+ )+ assert result.returncode == 0, result.stdout + result.stderr+++#: ``{form: (annotation, string)}``: strings that parse as an expression+#: only as written or only stripped of surrounding whitespace -- a line+#: continuation at the end (FastAPI hands the raw string to+#: ``ForwardRef``, which compiles it as it is), leading whitespace, or+#: both (only the starred reading, ``({string},)[0]``, accepts that) --+#: in a call argument and in a type slot. ``{ref}`` is the string's+#: literal, and ``{name}`` the fenced name in the string.+_STRING_FORMS = {+ "continuation-in-an-argument": ("str({ref})", "{name} \\\n\t"),+ "continuation-in-cast": ("typing.cast(object, {ref})", "{name}\\\n "),+ "space-and-continuation-in-cast": (+ "typing.cast(object, {ref})",+ " {name}\\\n ",+ ),+ "continuation-in-a-type-slot": (+ "Annotated[{ref}, Depends()]",+ "{name}\\\n ",+ ),+ "space-in-a-type-slot": ("Annotated[{ref}, Depends()]", " {name}"),+}+++ "script,name",+ [+ (ISOLATION_HOOK, "NoteService"),+ (REPORTS_HOOK, "FileResponse"),+ (REPORTS_HOOK, "static_file_response"),+ ],+ ids=["isolation", "reports-primitive", "reports-helper"],+)[email protected]("quoted", [False, True], ids=["unquoted", "quoted"])+class TestAnnotationStringForms:+ @pytest.mark.parametrize(+ "form", list(_STRING_FORMS), ids=list(_STRING_FORMS)+ )+ def test_strings_are_checked_as_written_and_stripped(+ self, tmp_path, script, name, quoted, form+ ):+ """A string that parses only as written -- the fenced name, then a+ backslash and a newline -- is the class to ``ForwardRef``, which+ compiles the raw string (``str()`` of it as a ``Depends()``+ parameter's annotation builds NoteService from the request), and+ one that parses only stripped is read that way too, so each form+ of a string is parsed and checked."""+ template, string = _STRING_FORMS[form]+ hooks = _mirror_hooks(tmp_path)+ annotation = template.format(ref=repr(string.format(name=name)))+ if quoted:+ annotation = repr(annotation)+ router = _write(+ tmp_path,+ "src/local_deep_research/web/routers/string_forms.py",+ "import typing\n"+ "from typing import Annotated\n"+ "from fastapi import Depends\n"+ f"def route(value: {annotation} = Depends()):\n"+ " return value\n",+ )+ result = _run_hook(script, [router], cwd=tmp_path, hooks_dir=hooks)+ assert result.returncode == 1, result.stdout + result.stderr+ assert _reported(result, router, 4, name), result.stdout+++#: The parameter each VALUE_ARGUMENTS index stands for.+_INDEXED_VALUE_ARGUMENTS = {+ ("typing.NewType", 0): "name",+ ("typing.ForwardRef", 2): "module",+}+++class TestValueArgumentSignatures:+ def test_value_arguments_match_the_signatures(self):+ """Each VALUE_ARGUMENTS entry is a parameter of the installed+ callee: a keyword it accepts, or the index of the positional+ parameter named in ``_INDEXED_VALUE_ARGUMENTS``. On Python 3.14+ ``ForwardRef``'s ``module`` is keyword-only, so index 2 cannot be+ passed at all there. Both hooks share one table."""+ import inspect+ import typing++ import fastapi+ import pydantic++ assert _reports_hook.VALUE_ARGUMENTS == (+ _isolation_hook.VALUE_ARGUMENTS+ ), "the hooks' VALUE_ARGUMENTS diverged"+ modules = {"fastapi": fastapi, "pydantic": pydantic, "typing": typing}+ named_kinds = (+ inspect.Parameter.POSITIONAL_OR_KEYWORD,+ inspect.Parameter.KEYWORD_ONLY,+ )+ for callee, positions in _isolation_hook.VALUE_ARGUMENTS.items():+ module, _, attribute = callee.rpartition(".")+ parameters = inspect.signature(+ getattr(modules[module], attribute)+ ).parameters+ positional = [+ p.name+ for p in parameters.values()+ if p.kind+ in (+ inspect.Parameter.POSITIONAL_ONLY,+ inspect.Parameter.POSITIONAL_OR_KEYWORD,+ )+ ]+ for position in positions:+ if isinstance(position, str):+ assert position in parameters, f"{callee} has no {position}"+ assert parameters[position].kind in named_kinds, (+ f"{callee}'s {position} is not a keyword"+ )+ continue+ expected = _INDEXED_VALUE_ARGUMENTS[(callee, position)]+ if position < len(positional):+ assert positional[position] == expected, (+ f"{callee}'s index {position} is "+ f"{positional[position]}, not {expected}"+ )+ else:+ assert callee == "typing.ForwardRef" and (+ sys.version_info >= (3, 14)+ ), f"{callee} has no positional index {position}"+ assert parameters[expected].kind is (+ inspect.Parameter.KEYWORD_ONLY+ )++class TestReportFilenameCollisions:def test_same_query_same_second_yields_distinct_paths(self, tmp_path, monkeypatch