Skip to content

~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.

test: resolve census forward references (#7323)

LearningCircuit863cabea459e
diff --git a/changelog.d/7097.misc.md b/changelog.d/7097.misc.md
new file mode 100644
index 0000000000..20af486b48
--- /dev/null
+++ b/changelog.d/7097.misc.md
@@ -0,0 +1 @@
+Extend the cross-user isolation census to recognize literal typing.ForwardRef dependency types, including imported aliases, while keeping annotation metadata and ordinary strings out of callable resolution.
diff --git a/tests/security/test_cross_user_isolation_census.py b/tests/security/test_cross_user_isolation_census.py
index d1054a7849..e1749de0ae 100644
--- a/tests/security/test_cross_user_isolation_census.py
+++ b/tests/security/test_cross_user_isolation_census.py
@@ -298,12 +298,43 @@ def _depends_target(default, annotation=None) -> str | None:
_MAX_QUOTE_DEPTH = 8
-def _unquote(annotation):
+def _unquote(annotation, imports=None):
"""A wholly quoted annotation parsed the way FastAPI evaluates it:
``"Annotated[NoteService, Depends()]"`` -> the ``Annotated`` subscript
- (recursively, up to ``_MAX_QUOTE_DEPTH``). Anything else, or a string
- that does not parse, is returned as is."""
+ (recursively, up to ``_MAX_QUOTE_DEPTH``). A literal ``typing.ForwardRef``
+ type argument is handled the same way, using the module's import bindings
+ for both constructor and module aliases. Other call arguments and
+ annotation metadata remain data. Unresolvable expressions are left as is.
+ """
+ imports = imports or {}
for _ in range(_MAX_QUOTE_DEPTH):
+ if isinstance(annotation, ast.Call):
+ constructor = annotation.func
+ is_forward_ref = (
+ isinstance(constructor, ast.Name)
+ and imports.get(constructor.id) == ("typing", "ForwardRef")
+ ) or (
+ isinstance(constructor, ast.Attribute)
+ and constructor.attr == "ForwardRef"
+ and isinstance(constructor.value, ast.Name)
+ and imports.get(constructor.value.id) == ("typing", None)
+ )
+ if not is_forward_ref:
+ break
+ argument = (
+ annotation.args[0]
+ if annotation.args
+ else next(
+ (kw.value for kw in annotation.keywords if kw.arg == "arg"),
+ None,
+ )
+ )
+ if not (
+ isinstance(argument, ast.Constant)
+ and isinstance(argument.value, str)
+ ):
+ break
+ annotation = argument
if not (
isinstance(annotation, ast.Constant)
and isinstance(annotation.value, str)
@@ -365,7 +396,7 @@ def _annotated_metadata(annotation):
yield from _annotated_elements(annotation)[1:]
-def _depends_targets(default, annotation) -> list:
+def _depends_targets(default, annotation, imports=None) -> list:
"""Every ``Depends(...)``/``Security(...)`` callable name for one
parameter, whichever spelling is used.
@@ -377,8 +408,8 @@ def _depends_targets(default, annotation) -> list:
FastAPI, so it is parsed first (see ``_unquote``).
"""
targets = []
- annotation = _unquote(annotation)
- wrapped = _annotated_type(annotation)
+ annotation = _unquote(annotation, imports)
+ wrapped = _unquote(_annotated_type(annotation), imports)
t = _depends_target(default, wrapped)
if t is not None:
targets.append(t)
@@ -536,16 +567,24 @@ def _auth_dependency_names(router_tree: ast.Module) -> set:
for n in auth_tree.body
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
}
+ candidates = [
+ (name, fn, imports)
+ for definitions, imports in (
+ (local, _resolve_imports(router_tree, "")),
+ (shared, _resolve_imports(auth_tree, "")),
+ )
+ for name, fn in definitions.items()
+ ]
resolved = {"require_auth"}
changed = True
while changed:
changed = False
- for name, fn in list(local.items()) + list(shared.items()):
+ for name, fn, imports in candidates:
if name in resolved:
continue
for _, default, annotation in _params(fn):
- targets = _depends_targets(default, annotation)
+ targets = _depends_targets(default, annotation, imports)
if any(t in resolved for t in targets):
resolved.add(name)
changed = True
@@ -556,6 +595,7 @@ def _auth_dependency_names(router_tree: ast.Module) -> set:
def _routes_in(tree: ast.Module, module_label: str) -> list:
prefix = _router_prefix(tree)
auth_names = _auth_dependency_names(tree)
+ imports = _resolve_imports(tree, "")
routes = []
for node in ast.walk(tree):
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
@@ -573,7 +613,8 @@ def _routes_in(tree: ast.Module, module_label: str) -> list:
name
for name, default, annotation in _params(node)
if any(
- t in auth_names for t in _depends_targets(default, annotation)
+ t in auth_names
+ for t in _depends_targets(default, annotation, imports)
)
)
for dec in decorators:
@@ -754,12 +795,13 @@ def identity_from_request_input(route: Route) -> list:
``request.query_params`` / ``path_params`` / ``headers`` / ``cookies``.
"""
problems = []
+ imports = _resolve_imports(route.tree, route.module_path)
for name, default, annotation in _params(route.node):
if name not in IDENTITY_PARAMS:
continue
if name in route.auth_params:
continue
- if _depends_targets(default, annotation):
+ if _depends_targets(default, annotation, imports):
continue
detail = ast.unparse(default) if default is not None else "<no default>"
problems.append(("parameter", name, detail, route.lineno))
@@ -855,7 +897,7 @@ def injected_identity_callables(tree: ast.Module, current_module: str) -> list:
for _, default, annotation in _params(node):
targets.extend(
(node.lineno, t)
- for t in _depends_targets(default, annotation)
+ for t in _depends_targets(default, annotation, imports)
)
elif isinstance(node, ast.Call):
t = _depends_target(node)
diff --git a/tests/security/test_cross_user_isolation_forward_refs.py b/tests/security/test_cross_user_isolation_forward_refs.py
new file mode 100644
index 0000000000..5d3af465ef
--- /dev/null
+++ b/tests/security/test_cross_user_isolation_forward_refs.py
@@ -0,0 +1,157 @@
+"""Runtime positive controls for the companion isolation census (#7097)."""
+
+import ast
+
+import pytest
+from fastapi.testclient import TestClient
+
+from tests.security import test_cross_user_isolation_census as census
+
+# allow: no-sut-import — the census reads the production package's AST; the
+# runtime controls below import and construct the real NoteService through
+# the same source text supplied to that analyzer. No database is accessed.
+_HEADER = """
+from __future__ import annotations
+import typing
+import typing as t
+from typing import Annotated, ForwardRef, ForwardRef as FR
+from fastapi import Depends, FastAPI
+from local_deep_research.research_library.notes.services.note_service import NoteService
+
+app = FastAPI()
+
+def require_auth() -> str:
+ return "alice"
+"""
+_MODULE = "local_deep_research.web.routers.control"
+
+
+def _probe_source(declaration):
+ return (
+ _HEADER
+ + f"""
+def probe(*, {declaration}, auth_username: Annotated[str, Depends(require_auth)]):
+ return {{"authenticated_username": auth_username, "service_username": svc.username}}
+"""
+ )
+
+
+ "declaration",
+ [
+ "svc: Annotated[NoteService, Depends()]",
+ "svc: \"Annotated[ForwardRef('NoteService'), Depends()]\"",
+ "svc: \"Annotated[typing.ForwardRef('NoteService'), Depends()]\"",
+ "svc: \"Annotated[t.ForwardRef('NoteService'), Depends()]\"",
+ "svc: \"Annotated[FR('NoteService'), Depends()]\"",
+ "svc: \"ForwardRef('NoteService')\" = Depends()",
+ "svc: \"FR('NoteService')\" = Depends()",
+ "svc: \"Annotated[ForwardRef(arg='NoteService'), Depends()]\"",
+ ],
+)
+def test_runtime_valid_forward_refs_are_reported(declaration):
+ source = _probe_source(declaration)
+ namespace = {"__name__": __name__}
+ # Every source fragment is a fixed local test fixture, never user input.
+ exec(compile(source, "<census-forward-ref-control>", "exec"), namespace) # noqa: S102
+
+ # Prove these annotations actually construct the identity-taking service
+ # from request input, rather than merely looking suspicious to the AST.
+ with TestClient(namespace["app"]) as client:
+ response = client.get("/probe", params={"username": "mallory"})
+ assert response.status_code == 200
+ assert response.json() == {
+ "authenticated_username": "alice",
+ "service_username": "mallory",
+ }
+ assert {
+ target
+ for _, target in census.injected_identity_callables(
+ ast.parse(source), _MODULE
+ )
+ } == {"NoteService"}
+
+
+def test_auth_derived_forward_ref_remains_scoped():
+ source = (
+ _HEADER
+ + """
+def authenticated_identity(username: Annotated[str, Depends(require_auth)]) -> str:
+ return username
+
+def probe(username: "Annotated[FR('authenticated_identity'), Depends()]"):
+ return {"username": username}
+"""
+ )
+ namespace = {"__name__": __name__}
+ # Every source fragment is a fixed local test fixture, never user input.
+ exec(compile(source, "<census-auth-control>", "exec"), namespace) # noqa: S102
+ with TestClient(namespace["app"]) as client:
+ response = client.get("/probe", params={"username": "mallory"})
+ assert response.status_code == 200
+ assert response.json() == {"username": "alice"}
+
+ (route,) = census._control_routes(source)
+ assert route.auth_params == {"username"}
+ assert census.identity_from_request_input(route) == []
+ assert census.injected_identity_callables(ast.parse(source), _MODULE) == []
+
+
+ "declaration",
+ [
+ "svc: Annotated[str, \"ForwardRef('NoteService')\"]",
+ "svc: Annotated[str, ForwardRef('NoteService')]",
+ "svc: Annotated[str, {'arg': 'NoteService'}]",
+ "svc: str = 'ForwardRef(\"NoteService\")'",
+ "svc: Annotated[ForwardRef('str', module='NoteService'), Depends()]",
+ ],
+)
+def test_annotation_metadata_and_value_strings_remain_data(declaration):
+ assert (
+ census.injected_identity_callables(
+ ast.parse(_probe_source(declaration)), _MODULE
+ )
+ == []
+ )
+
+
+ "imports, expression",
+ [
+ ("", "ForwardRef('NoteService')"),
+ ("from unrelated import ForwardRef", "ForwardRef('NoteService')"),
+ ("import unrelated as typing", "typing.ForwardRef('NoteService')"),
+ ("from unrelated import ForwardRef as FR", "FR('NoteService')"),
+ ],
+)
+def test_unrelated_forward_ref_names_are_not_evaluated(imports, expression):
+ source = f"""
+from fastapi import Depends
+from local_deep_research.research_library.notes.services.note_service import NoteService
+{imports}
+def probe(svc: {expression} = Depends()):
+ return svc
+"""
+ assert census.injected_identity_callables(ast.parse(source), _MODULE) == []
+
+
+ "argument",
+ ["target_name", "42", "'['", "''", "'NoteService' + suffix"],
+)
+def test_nonliteral_or_unparseable_references_remain_unresolved(argument):
+ source = _probe_source(f"svc: Annotated[FR({argument}), Depends()]")
+ assert census.injected_identity_callables(ast.parse(source), _MODULE) == []
+
+
+def test_nested_forward_references_are_bounded():
+ expression = "NoteService"
+ for _ in range(census._MAX_QUOTE_DEPTH + 1):
+ expression = f"FR({expression!r})"
+ node = ast.parse(expression, mode="eval").body
+ unresolved = census._unquote(node, {"FR": ("typing", "ForwardRef")})
+ assert isinstance(unresolved, ast.Call)
+ assert census._dependency_name(unresolved) is None