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: three documentation-reference guards (egress PEP table, frontend URLs, documented env vars) (#6045)

LearningCircuit7f4dbc57a60c
diff --git a/changelog.d/+docs-reference-guards.misc.md b/changelog.d/+docs-reference-guards.misc.md
new file mode 100644
index 0000000000..213859c6fa
--- /dev/null
+++ b/changelog.d/+docs-reference-guards.misc.md
@@ -0,0 +1,8 @@
+Add three documentation-reference guardian tests: the egress README's
+load-bearing PEP table (cited files and named functions must exist), every
+fully-literal frontend `fetch()`/XHR URL (must resolve to a real route —
+the Puppeteer suites only run at release, so URL drift was otherwise
+caught weeks late), and env vars documented in operator docs (must be
+referenced by `src/`, including reverse-mapped `LDR_*` settings-derived
+names). All three are stdlib-only static checks with anti-vacuity floors
+and mutation-verified detection.
diff --git a/tests/infrastructure_tests/README.md b/tests/infrastructure_tests/README.md
index 9d48f248e8..98128cfda7 100644
--- a/tests/infrastructure_tests/README.md
+++ b/tests/infrastructure_tests/README.md
@@ -8,6 +8,8 @@ This directory contains tests for infrastructure and architectural components of
- `test_route_registry.py` - Tests for the centralized route registry system
- `test_urls_js.py` - Python tests verifying JavaScript URL configuration matches backend routes
- `test_urls.test.js` - JavaScript unit tests for URL builder functionality
+- `test_hardcoded_fetch_urls.py` - Verifies every fully-literal `fetch()`/XHR URL in templates and static JS resolves to a real backend route (statically derived; complements `test_urls_js.py`, which covers the central URLS table)
+- `test_documented_env_vars.py` - Verifies every env var documented in `docs/deployment/` and `docs/troubleshooting.md` is actually referenced by `src/` (docs drift after renames would hand operators no-op variables)
### Future Test Categories (to be added)
- **Configuration Tests** - Tests for settings management and configuration loading
diff --git a/tests/infrastructure_tests/test_documented_env_vars.py b/tests/infrastructure_tests/test_documented_env_vars.py
new file mode 100644
index 0000000000..6c91678abd
--- /dev/null
+++ b/tests/infrastructure_tests/test_documented_env_vars.py
@@ -0,0 +1,218 @@
+"""Every environment variable the operator docs document must actually be
+read by the application.
+
+Why this guard exists
+---------------------
+
+``check-env-vars.py`` (pre-commit) polices *where* ``os.environ`` may be
+read — it does not compare documentation against code. The FastAPI
+migration renamed ``RATELIMIT_STORAGE_URL`` to ``RATE_LIMIT_STORAGE_URI``
+and made the old name a fallback; a docs page that keeps documenting only
+the old name hands operators a variable that silently does less than it
+claims. That drift class is invisible until someone copies the variable
+into a production deployment and nothing changes.
+
+This test scans the operator-facing docs (``docs/deployment/``,
+``docs/troubleshooting.md``) for backticked ALL_CAPS_WITH_UNDERSCORES
+tokens outside fenced code blocks, and requires each to appear somewhere
+under ``src/`` — as a literal the code reads (``os.environ``/``os.getenv``
+usage, env_registry definitions, or any other textual reference).
+
+Deliberately one-directional: the reverse direction (code reads a variable
+no doc mentions) is legitimate — internal and test-mode knobs outnumber
+documented ones and churn too fast for docs to track.
+"""
+
+# allow: no-sut-import — a documentation-reference guardian over
+# static files, not behaviour; importing the app would add side effects
+# this guard deliberately avoids (see module docstring).
+
+import re
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+SRC_ROOT = REPO_ROOT / "src"
+
+#: Docs whose env-var mentions are operator-facing claims.
+DOC_PATHS = sorted((REPO_ROOT / "docs" / "deployment").glob("*.md")) + [
+ REPO_ROOT / "docs" / "troubleshooting.md",
+]
+
+#: At least one underscore: excludes plain words like ``GET`` or ``HTTP``
+#: that happen to be backticked. All-caps-enforced by the same regex.
+#: Anchored (full-token) — used to validate backticked doc tokens.
+_ENV_VAR_RE = re.compile(r"^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$")
+
+#: Unanchored twin for scanning source files: finds every such token
+#: anywhere in a line (string literals, registry definitions, comments).
+_SRC_ENV_TOKEN_RE = re.compile(r"[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+")
+
+#: Documented variables that are legitimately NOT read from src/, each
+#: with the reason. Keep this list short and justified.
+_DOCKER_COMPOSE_ONLY = {
+ # Read by .github/workflows (CI), not by the application.
+}
+
+
+def _strip_fences(text: str) -> str:
+ return re.sub(r"```.*?```", "", text, flags=re.DOTALL)
+
+
+def _documented_env_vars() -> dict[str, list[str]]:
+ """{env_var: [doc file:line, ...]} for backticked candidates."""
+ found: dict[str, list[str]] = {}
+ for doc in DOC_PATHS:
+ if not doc.is_file():
+ continue
+ text = _strip_fences(doc.read_text(encoding="utf-8"))
+ for match in re.finditer(r"`([^`\n]+)`", text):
+ token = match.group(1).strip()
+ if not _ENV_VAR_RE.match(token):
+ continue
+ line = text.count("\n", 0, match.start()) + 1
+ found.setdefault(token, []).append(
+ f"{doc.relative_to(REPO_ROOT)}:{line}"
+ )
+ return found
+
+
+def _tokens_read_by_src() -> frozenset[str]:
+ """Every ALL_CAPS_UNDERSCORES token appearing anywhere under src/.
+
+ One regex pass per file; membership is a superset of "read via
+ os.environ" but that is the right direction for a docs-consistency
+ guard: a variable the source never mentions at all is certainly not
+ read, while one mentioned in a comment next to its ``os.getenv`` call
+ (the common style here) counts.
+ """
+ tokens: set[str] = set()
+ for py in SRC_ROOT.rglob("*.py"):
+ try:
+ text = py.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+ tokens.update(_SRC_ENV_TOKEN_RE.findall(text))
+ return frozenset(tokens)
+
+
+def _setting_key_candidates(var: str) -> set[str] | None:
+ """Every settings key whose LDR_-prefixed env name would be ``var``.
+
+ ``settings/env_settings.py`` derives env names dynamically as
+ ``"LDR_" + key.upper().replace(".", "_")`` — so ``LDR_LLM_PROVIDER``
+ is read, but never appears as a literal. The derivation is not
+ uniquely reversible (``llm.openai.api_key`` and ``llm.openai.api.key``
+ both map to ``LDR_LLM_OPENAI_API_KEY``), so return ALL dot/underscore
+ partitions of the lowercased remainder; a documented variable passes
+ the guard when ANY candidate appears literally in src.
+
+ Combinatorics are tiny (2^(n-1) for n segments; env names have ≤ 6) and
+ results are memoised by the caller.
+ """
+ if not var.startswith("LDR_"):
+ return None
+ parts = var[len("LDR_") :].lower().split("_")
+ candidates: set[str] = set()
+
+ def _build(index: int, acc: str) -> None:
+ if index == len(parts):
+ candidates.add(acc)
+ return
+ if not acc:
+ _build(index + 1, parts[index])
+ else:
+ _build(index + 1, acc + "." + parts[index])
+ _build(index + 1, acc + "_" + parts[index])
+
+ _build(0, "")
+ return candidates
+
+
+def _dotted_key_appears_in_src(key: str, cached: dict[str, bool] = {}) -> bool:
+ """Whether the dotted settings key appears literally in any src file.
+
+ Results are memoised in ``cached`` (a default-argument dict — the
+ classic read-only-cache idiom; this helper is module-private and
+ never mutated by callers).
+ """
+ if key not in cached:
+ cached[key] = any(
+ key in py.read_text(encoding="utf-8", errors="replace")
+ for py in SRC_ROOT.rglob("*.py")
+ )
+ return cached[key]
+
+
+def test_documented_env_vars_are_known_to_src():
+ documented = _documented_env_vars()
+ # Anti-vacuity: these docs demonstrably document a meaningful number of
+ # variables today; an extraction regression should not pass silently.
+ assert len(documented) >= 5, (
+ f"only {len(documented)} documented env vars found in "
+ f"{[str(p) for p in DOC_PATHS]} — the extractor is likely broken"
+ )
+
+ read_by_src = _tokens_read_by_src()
+ unknown = {}
+ for var, locations in documented.items():
+ if var in read_by_src or var in _DOCKER_COMPOSE_ONLY:
+ continue
+ # Dynamic LDR_* derivation: the env name is constructed from a
+ # settings key at runtime, so accept any reverse-mapped key
+ # candidate appearing literally (see _setting_key_candidates).
+ candidates = _setting_key_candidates(var)
+ if candidates is not None and any(
+ _dotted_key_appears_in_src(key) for key in candidates
+ ):
+ continue
+ unknown[var] = locations
+ assert not unknown, (
+ "Environment variables documented in operator docs but never "
+ "referenced anywhere under src/ (operators would set no-ops):\n"
+ + "\n".join(
+ f" {var} (documented at {', '.join(locs)})"
+ for var, locs in sorted(unknown.items())
+ )
+ + "\nEither the docs are stale (rename/remove the variable) or the "
+ "code lost its read — or, if it is genuinely consumed elsewhere "
+ "(docker-compose/CI), add it to _DOCKER_COMPOSE_ONLY with a reason."
+ )
+
+
+def test_dynamic_env_derivation_mechanism_still_exists():
+ """The reverse-mapping fallback above is only sound while
+ ``settings/env_settings.py`` still derives env names as
+ ``"LDR_" + key.upper().replace(".", "_")``. If that mechanism
+ changes, the fallback silently stops matching — so pin it."""
+ env_settings = (
+ SRC_ROOT / "local_deep_research" / "settings" / "env_settings.py"
+ )
+ assert env_settings.is_file(), (
+ "settings/env_settings.py moved — update "
+ "test_documented_env_vars.py's reverse-mapping fallback"
+ )
+ source = env_settings.read_text(encoding="utf-8")
+ assert "LDR_" in source and ".upper().replace" in source, (
+ "The LDR_* env-name derivation expression changed; the "
+ "reverse-mapping fallback in test_documented_env_vars.py is "
+ "now unsound and must be revisited"
+ )
+
+
+def test_scanned_docs_exist():
+ """The guard is only meaningful while it scans the files that carry the
+ operator claims — fail loudly if they move."""
+ existing = [p for p in DOC_PATHS if p.is_file()]
+ assert existing, (
+ f"none of the configured doc paths exist: {[str(p) for p in DOC_PATHS]} "
+ "— update DOC_PATHS in this test when operator docs move"
+ )
+ assert (REPO_ROOT / "docs" / "deployment").is_dir(), (
+ "docs/deployment/ no longer exists — update DOC_PATHS"
+ )
+
+
+if __name__ == "__main__": # pragma: no cover
+ pytest.main([__file__, "-v"])
diff --git a/tests/infrastructure_tests/test_hardcoded_fetch_urls.py b/tests/infrastructure_tests/test_hardcoded_fetch_urls.py
new file mode 100644
index 0000000000..a344b6cf16
--- /dev/null
+++ b/tests/infrastructure_tests/test_hardcoded_fetch_urls.py
@@ -0,0 +1,343 @@
+"""Every fully-literal frontend ``fetch()``/XHR URL must resolve to a real
+backend route.
+
+Why this guard exists
+---------------------
+
+``test_urls_js.py`` validates the central ``URLS`` table in
+``static/js/config/urls.js`` against the live app — but the frontend also
+contains ~75 hardcoded ``fetch('/...')`` calls across templates and component
+scripts (news-subscription-form.html alone has a dozen). Those literals have
+no guard at all today, and the browser-level Puppeteer suites run only in
+the release pipeline (``strict-mode``), so a renamed or removed route breaks
+the UI silently and is discovered weeks later at release time. PR #3299's
+own changelog shows the failure class is real: five legacy ``/api/news/*``
+endpoints were removed and every hardcoded client reference had to be found
+by hand.
+
+Scope, deliberately narrow
+--------------------------
+
+Only *fully literal* first arguments are checked — ``fetch('/news/api/subscribe')``.
+URLs built by interpolation (``fetch(`/api/research/${id}/status`)``), from
+variables, or via the ``URLS`` table are skipped: they are not resolvable
+statically, and the ``URLS`` table is already covered by ``test_urls_js.py``.
+String concatenation is skipped only when it extends the *path* itself
+(``fetch('/api/research/' + id + '/status')``) — the captured
+``/api/research/`` fragment is not itself a URL and matches no route by
+construction, so flagging it would be a false positive, not a caught bug.
+Query-string concatenation (``fetch('/news/api/feed?limit=' + n)``) is
+*not* skipped: the path portion before the ``?`` is already complete (the
+check ignores everything from ``?`` on regardless), so it is still
+resolvable and still checked.
+Generated bundles (``dist/``, ``*.min.js``) are excluded — they are build
+output, not sources.
+
+The route table is derived by AST/regex from the mounted routers rather
+than by importing the app, mirroring ``test_route_table_parity.py``'s
+approach: no import side effects, no dependency on a bootable environment,
+and it runs everywhere. A dynamically-registered route would be missed —
+the app registers none today (the parity test's snapshot pins the full
+table and would flag any that appears).
+
+A URL passes if it equals a route path (trailing-slash tolerant), matches a
+parameterized route (``{id}`` → one segment, ``{path:path}`` → any suffix),
+or falls under a mount prefix (``/ws``). Query strings and fragments are
+ignored, as are external and non-root-relative URLs.
+"""
+
+# allow: no-sut-import — a documentation-reference guardian over
+# static files, not behaviour; importing the app would add side effects
+# this guard deliberately avoids (see module docstring).
+
+import re
+from functools import lru_cache
+from pathlib import Path
+
+import pytest
+
+SRC_ROOT = Path(__file__).resolve().parents[2] / "src" / "local_deep_research"
+WEB_DIR = SRC_ROOT / "web"
+FASTAPI_APP_FILE = WEB_DIR / "fastapi_app.py"
+ROUTERS_DIR = WEB_DIR / "routers"
+
+#: Generated build output — never scanned.
+_EXCLUDED_DIR_NAMES = {"dist", "node_modules"}
+
+_HTTP_METHODS = r"get|post|put|patch|delete|head|options"
+
+# ``fetch('...')`` / ``fetch("...")`` / ``fetch(`...`)`` — first argument a
+# string literal. Backtick captures are kept only when they contain no
+# interpolation.
+_FETCH_RE = re.compile(r"\bfetch\(\s*([\"'`])([^\"'`]*)\1")
+
+# ``xhr.open('POST', '...')`` — method then URL, both quoted.
+_XHR_OPEN_RE = re.compile(
+ r"\.open\(\s*[\"'][A-Za-z]+[\"']\s*,\s*([\"'])([^\"']+)\1"
+)
+
+#: Backtick URL containing interpolation — dynamic, skipped by design.
+_INTERPOLATION_MARKERS = ("${", "{{", "{%")
+
+
+def _line_no(text: str, offset: int) -> int:
+ return text.count("\n", 0, offset) + 1
+
+
+def _is_concatenated(text: str, match: re.Match[str]) -> bool:
+ """True if the matched literal is a truncated *path* fragment continued
+ by string concatenation, e.g. the ``'/api/research/'`` in
+ ``fetch('/api/research/' + id + '/status')``.
+
+ Only a trailing ``+`` matters: the regexes above only ever capture the
+ *first* quoted fragment of the call's arguments, so the text
+ immediately before the captured quote is always ``(`` or ``,`` (the
+ call's opening paren, or the comma after the XHR method) — never
+ ``+``. A leading-``+`` check would therefore be dead code; it is
+ omitted rather than kept as a check that can never fire.
+
+ A trailing ``+`` alone is not enough, though: if the literal contains a
+ ``?``, everything before that ``?`` is already a *complete* path —
+ ``_normalise`` strips the query string, so ``'<path>?param=' + value``
+ (the standard query-string-concatenation idiom) still yields a fully
+ resolvable path and must still be checked, not skipped. Only when the
+ ``+`` extends the path itself — no ``?`` in the literal — is the
+ fragment genuinely unresolvable.
+ """
+ after = text[match.end() :].lstrip()
+ return after.startswith("+") and "?" not in match.group(2)
+
+
+@lru_cache(maxsize=None)
+def _route_paths() -> set[str]:
+ """All route paths the app serves, derived statically.
+
+ Mirrors what ``fastapi_app._mount_all`` registers: every
+ ``@router.<method>("...")`` decorator in the mounted router modules
+ (prefixed by each router's ``APIRouter(prefix=...)``), plus the routes
+ declared directly on the app (``/``, ``/favicon.ico``,
+ ``/static/{path:path}``).
+ """
+ app_source = FASTAPI_APP_FILE.read_text(encoding="utf-8")
+
+ paths: set[str] = set()
+
+ # Routes declared on the app object itself.
+ for match in re.finditer(
+ rf"@app\.({_HTTP_METHODS})\(\s*[\"']([^\"']+)[\"']", app_source
+ ):
+ paths.add(match.group(2))
+
+ # The mounted router modules: the _router_modules list literal plus the
+ # api_v1 import that _mount_all seeds the dict with.
+ router_names = set(
+ re.findall(
+ r"\(\s*[\"'][a-z_0-9]+[\"']\s*,\s*\"\.routers\.([a-z_0-9]+)\"\s*\)",
+ app_source,
+ )
+ )
+ api_v1 = re.search(r"from \.routers\.api_v1 import router", app_source)
+ if api_v1:
+ router_names.add("api_v1")
+ assert router_names, (
+ "no mounted routers found in fastapi_app.py — the extractor is "
+ "broken, not the frontend"
+ )
+
+ for name in sorted(router_names):
+ router_file = ROUTERS_DIR / f"{name}.py"
+ source = router_file.read_text(encoding="utf-8")
+ prefix_match = re.search(
+ r"APIRouter\(\s*[^)]*?prefix\s*=\s*[\"']([^\"']*)[\"']",
+ source,
+ flags=re.DOTALL,
+ )
+ prefix = prefix_match.group(1) if prefix_match else ""
+ for match in re.finditer(
+ rf"@router\.({_HTTP_METHODS})\(\s*[\"']([^\"']+)[\"']", source
+ ):
+ paths.add(prefix + match.group(2))
+
+ return paths
+
+
+def _route_pattern(route: str) -> re.Pattern[str]:
+ """Compile a route path into a matcher for concrete URLs.
+
+ ``{id}`` matches exactly one segment; ``{path:path}`` matches any
+ remainder including slashes. Everything else is literal.
+ """
+ parts = []
+ for segment in route.split("/"):
+ if not segment:
+ continue
+ path_param = re.fullmatch(r"\{([^:}]+):path\}", segment)
+ plain_param = re.fullmatch(r"\{[^}]+\}", segment)
+ if path_param:
+ parts.append("(?:/.+)?")
+ elif plain_param:
+ parts.append("/[^/]+")
+ else:
+ parts.append("/" + re.escape(segment))
+ body = "".join(parts) or "/"
+ # Trailing-slash tolerant.
+ return re.compile("^" + body + "/?$")
+
+
+@lru_cache(maxsize=None)
+def _route_matchers() -> tuple[re.Pattern[str], ...]:
+ return tuple(_route_pattern(route) for route in _route_paths())
+
+
+#: Mount prefixes that swallow arbitrary sub-paths (the Socket.IO ASGI app).
+_MOUNT_PREFIXES = ("/ws",)
+
+
+def _url_resolves(url: str) -> bool:
+ if any(
+ url == prefix or url.startswith(prefix + "/")
+ for prefix in _MOUNT_PREFIXES
+ ):
+ return True
+ return any(matcher.match(url) for matcher in _route_matchers())
+
+
+def _normalise(raw: str) -> str | None:
+ """Return the comparable path for a literal URL, or None to skip."""
+ url = raw.strip()
+ if not url.startswith("/"):
+ return None # external, relative, data:, etc.
+ url = url.split("#", 1)[0].split("?", 1)[0]
+ if not url or url == "/":
+ return url or None
+ return url
+
+
+def _iter_frontend_files() -> list[Path]:
+ files: list[Path] = []
+ for base in (WEB_DIR / "templates", WEB_DIR / "static" / "js"):
+ if not base.is_dir():
+ continue
+ for path in base.rglob("*"):
+ if not path.is_file():
+ continue
+ if path.suffix not in {".html", ".js"}:
+ continue
+ if any(part in _EXCLUDED_DIR_NAMES for part in path.parts):
+ continue
+ if path.name.endswith(".min.js"):
+ continue
+ files.append(path)
+ return sorted(files)
+
+
+def _collect_literals() -> dict[str, list[str]]:
+ """{normalised_url: [file:line, ...]} for every literal fetch/XHR URL."""
+ found: dict[str, list[str]] = {}
+ for path in _iter_frontend_files():
+ text = path.read_text(encoding="utf-8", errors="replace")
+ for regex in (_FETCH_RE, _XHR_OPEN_RE):
+ for match in regex.finditer(text):
+ raw = match.group(2)
+ if any(marker in raw for marker in _INTERPOLATION_MARKERS):
+ continue
+ if _is_concatenated(text, match):
+ continue
+ normalised = _normalise(raw)
+ if normalised is None:
+ continue
+ rel = path.relative_to(SRC_ROOT.parent.parent)
+ found.setdefault(normalised, []).append(
+ f"{rel}:{_line_no(text, match.start())}"
+ )
+ return found
+
+
+def test_frontend_literal_urls_resolve_to_routes():
+ literals = _collect_literals()
+ # Anti-vacuity: the extractor must find a substantial body of literals —
+ # a regex regression that matches nothing would otherwise pass silently.
+ assert len(literals) >= 40, (
+ f"only {len(literals)} distinct literal URLs found across "
+ "templates/static-js — the extractor is likely broken"
+ )
+
+ unresolved = {
+ url: locations
+ for url, locations in literals.items()
+ if not _url_resolves(url)
+ }
+ assert not unresolved, (
+ "Frontend literal fetch()/XHR URLs that no backend route "
+ "serves:\n"
+ + "\n".join(
+ f" {url} (used at {', '.join(locs)})"
+ for url, locs in sorted(unresolved.items())
+ )
+ + "\nEither fix the frontend reference or restore/rename the route."
+ )
+
+
+ "text,regex",
+ [
+ ("fetch('/api/research/' + id + '/status')", _FETCH_RE),
+ ('xhr.open("POST", "/api/upload/" + id)', _XHR_OPEN_RE),
+ ("fetch(`/library/api/document/` + id)", _FETCH_RE),
+ ],
+)
+def test_concatenated_url_fragment_is_skipped_not_flagged(text, regex):
+ """A ``+``-concatenated call must not be treated as if its first quoted
+ fragment were the whole URL: ``/api/research/`` alone matches no route
+ (``^/api/research/[^/]+/?$`` requires a following segment), so asserting
+ it resolves would be a false positive against perfectly valid frontend
+ code. It must be skipped instead."""
+ match = next(regex.finditer(text))
+ assert _is_concatenated(text, match), (
+ f"expected {match.group(2)!r} in {text!r} to be recognised as a "
+ "concatenation fragment"
+ )
+
+
+def test_standalone_bogus_literal_is_still_caught():
+ """The concatenation skip must not neuter the guard: a genuinely wrong,
+ non-concatenated literal still has to fail ``_url_resolves`` so the
+ guard can catch it."""
+ text = "fetch('/api/does-not-exist')"
+ match = next(_FETCH_RE.finditer(text))
+ assert not _is_concatenated(text, match)
+ assert not _url_resolves(match.group(2))
+
+
+def test_query_string_concatenation_is_not_skipped():
+ """Query-string concatenation (``'<path>?param=' + value``) must NOT be
+ treated as an unresolvable path fragment: ``_normalise`` already strips
+ everything from ``?`` onward, so the path portion of the literal is
+ complete and genuinely checkable. A bogus path hidden behind this idiom
+ (e.g. a removed ``/api/news/*`` route) must still be caught."""
+ text = "fetch('/api/news/feed?limit=' + n)"
+ match = next(_FETCH_RE.finditer(text))
+ assert not _is_concatenated(text, match), (
+ "query-string concatenation must still be checked, not skipped"
+ )
+ normalised = _normalise(match.group(2))
+ assert normalised == "/api/news/feed"
+ assert not _url_resolves(normalised)
+
+
+def test_route_extractor_finds_the_app_level_and_router_routes():
+ """The static route table must contain representatives of every shape it
+ is matched against — app-level, prefixed-router, and parameterized."""
+ routes = _route_paths()
+ assert "/" in routes, "app-level root route missing from extraction"
+ assert any(r.startswith("/api/v1") for r in routes), (
+ "prefixed router routes missing from extraction"
+ )
+ assert any("{" in r for r in routes), (
+ "parameterized routes missing from extraction"
+ )
+ assert "/static/{path:path}" in routes
+
+
+if __name__ == "__main__": # pragma: no cover
+ pytest.main([__file__, "-v"])
diff --git a/tests/security/test_egress_pep_table.py b/tests/security/test_egress_pep_table.py
new file mode 100644
index 0000000000..a30f6da2e1
--- /dev/null
+++ b/tests/security/test_egress_pep_table.py
@@ -0,0 +1,352 @@
+"""Guardian for ``security/egress/README.md``'s PEP tables.
+
+The README's own words: "**Keep this table accurate — it is load-bearing, not
+documentation.** ... the model-discovery gate was silently lost in a merge
+(its Flask file was deleted ...) and this table is the index an auditor uses
+to notice that an enforcement point has gone missing."
+
+That instruction — "If you add, move, or remove a PEP, update this row in the
+same commit" — is currently enforced by trust alone. This test automates it:
+
+1. Every source file the tables cite must exist on disk.
+2. Every function/class a table row names must be defined in a file cited on
+ that same row (for section 3's "Consults" column: somewhere in the egress
+ package, which is where the PDP lives).
+
+Pure stdlib AST — no app import, so it runs in every environment and fails
+for checkouts that could not even boot the app. Under-extraction is preferred
+over noise: tokens the parser does not understand (wildcards like
+``evaluate_*()``, ellipsis paths like ``…/implementations/…``) are skipped
+rather than guessed at.
+"""
+
+# allow: no-sut-import — a documentation-reference guardian over
+# static files, not behaviour; importing the app would add side effects
+# this guard deliberately avoids (see module docstring).
+
+import ast
+import re
+from functools import lru_cache
+from pathlib import Path
+
+import pytest
+
+SRC_ROOT = Path(__file__).resolve().parents[2] / "src" / "local_deep_research"
+PKG_DIR = SRC_ROOT / "security" / "egress"
+README = PKG_DIR / "README.md"
+
+# Backticked token that looks like a code identifier (no path separators,
+# no dots). Trailing call parens are stripped before matching, so both
+# `classify_engine` and `classify_engine()` are recognised.
+_BARE_IDENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+# Tokens that are deliberate prose references, not symbols the parser should
+# require. Every entry needs a reason.
+_PROSE_IDENTIFIERS = {
+ # Settings key named in the SearXNG row's prose ("a `url_setting`"),
+ # not a function or class.
+ "url_setting",
+ # Module named in audit_hook.py's prose ("new contributors using raw
+ # `requests`"), not a symbol defined in that file.
+ "requests",
+}
+
+
+def _is_abbreviated_path(token: str) -> bool:
+ """True for deliberately abbreviated paths like ``…/implementations/…``
+ (the embeddings row cites three files; the middle one is elided).
+ These are skipped rather than resolved — guessing the prefix would
+ trade a silent pass for a wrong failure.
+ """
+ return "…" in token
+
+
+def _strip_fences(text: str) -> str:
+ """Remove fenced code blocks — their contents are examples, not table
+ rows, and the Public API block lists import names that section 2 already
+ covers file-by-file."""
+ return re.sub(r"```.*?```", "", text, flags=re.DOTALL)
+
+
+def _split_table_row(line: str) -> list[str]:
+ parts = [p.strip() for p in line.strip().strip("|").split("|")]
+ return parts
+
+
+def _backticked(text: str) -> list[str]:
+ return re.findall(r"`([^`]+)`", text)
+
+
+def _split_call_suffix(token: str) -> str:
+ """``classify_engine()`` / ``set_active_context(ctx)`` -> bare name."""
+ return token.split("(", 1)[0].strip()
+
+
+def _iter_table_rows(lines: list[str], start_marker: str) -> list[str]:
+ """Rows (as raw strings) of the first markdown table after
+ ``start_marker``; the header and ``|---|`` separator are skipped."""
+ rows: list[str] = []
+ in_section = False
+ table_started = False
+ for line in lines:
+ stripped = line.strip()
+ if not in_section:
+ if start_marker in line:
+ in_section = True
+ continue
+ if stripped.startswith("|"):
+ if set(stripped) <= {"|", "-", ":", " "}:
+ table_started = True
+ continue
+ if rows or table_started or stripped.startswith("|---") is False:
+ rows.append(line)
+ elif rows:
+ break
+ elif stripped.startswith("#") and table_started is False and rows == []:
+ # a heading or paragraph before the table — keep scanning
+ continue
+ # Drop a leading header row (the first row is always the header).
+ return rows[1:] if rows else []
+
+
+@lru_cache(maxsize=None)
+def _defined_names(py_file: Path) -> frozenset[str]:
+ """All function/class names (including methods) plus module-level
+ assignment targets in ``py_file``."""
+ try:
+ tree = ast.parse(py_file.read_text(encoding="utf-8"))
+ except (OSError, SyntaxError):
+ return frozenset()
+
+ names: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(
+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
+ ):
+ names.add(node.name)
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
+ targets = (
+ node.targets if isinstance(node, ast.Assign) else [node.target]
+ )
+ for target in targets:
+ if isinstance(target, ast.Name):
+ names.add(target.id)
+ return frozenset(names)
+
+
+def _resolve_source_path(token: str) -> Path | None:
+ """Resolve a backticked path token to an existing file under src/.
+
+ Tries the token relative to the package root, the egress package dir,
+ and the security package dir (the README mixes all three conventions:
+ ``web/routers/research.py``, ``audit_hook.py``, ``egress/validators.py``,
+ ``security/__init__``). Returns None for deliberately unresolvable
+ tokens (ellipsis paths), which callers skip.
+ """
+ if "…" in token or token.startswith("…"):
+ return None
+ token = token.strip()
+ candidates = []
+ for base in (SRC_ROOT, PKG_DIR, SRC_ROOT / "security"):
+ candidate = (base / token).resolve()
+ candidates.append(candidate)
+ if not token.endswith(".py"):
+ candidates.append((base / (token + ".py")).resolve())
+ for candidate in candidates:
+ if candidate.is_file():
+ return candidate
+ return None
+
+
+def _is_pathish(token: str) -> bool:
+ return token.endswith(".py") or "/__init__" in token or "/" in token
+
+
+def _package_surface() -> frozenset[str]:
+ """Every name defined in any module of the egress package."""
+ surface: set[str] = set()
+ for py in PKG_DIR.glob("*.py"):
+ surface |= _defined_names(py)
+ return frozenset(surface)
+
+
+class TestPackageFileTable:
+ """Section 2 — "Files in this package": each cited file exists and the
+ names its role column mentions are defined in it."""
+
+ def test_cited_files_exist_and_named_symbols_are_defined(self):
+ text = _strip_fences(README.read_text(encoding="utf-8"))
+ rows = _iter_table_rows(text.splitlines(), "### Files in this package")
+ assert rows, "could not find the 'Files in this package' table"
+
+ failures: list[str] = []
+ for row in rows:
+ cols = _split_table_row(row)
+ if len(cols) < 2:
+ continue
+ file_tokens = [
+ t
+ for t in _backticked(cols[0])
+ if _is_pathish(t) and not _is_abbreviated_path(t)
+ ]
+ if not file_tokens:
+ continue
+ resolved = _resolve_source_path(file_tokens[0])
+ if resolved is None:
+ failures.append(
+ f"section 2 row cites {file_tokens[0]!r}, which does "
+ "not resolve to an existing file under src/"
+ )
+ continue
+ names = _defined_names(resolved)
+ for token in _backticked(cols[1]):
+ ident = _split_call_suffix(token)
+ if not _BARE_IDENT_RE.match(ident):
+ continue # dotted/wildcard/prose token — see docstring
+ if ident in _PROSE_IDENTIFIERS:
+ continue
+ if ident not in names:
+ failures.append(
+ f"{resolved.relative_to(SRC_ROOT.parent.parent)}: "
+ f"README section 2 cites {ident!r}, which is not "
+ "defined in that file"
+ )
+ assert not failures, "\n".join(failures)
+
+
+class TestPepLocationTable:
+ """Section 3 — "Where the PEPs live": every cited file exists, every
+ named enforcement function is defined in a file on the same row, and
+ every "Consults" name is part of the egress package surface."""
+
+ def test_pep_rows_resolve(self):
+ text = _strip_fences(README.read_text(encoding="utf-8"))
+ rows = _iter_table_rows(text.splitlines(), "## 3. Where the PEPs live")
+ assert rows, "could not find the 'Where the PEPs live' table"
+
+ package_names = _package_surface()
+ failures: list[str] = []
+
+ for row in rows:
+ cols = _split_table_row(row)
+ if len(cols) < 3:
+ continue
+ location, consults = cols[1], cols[2]
+
+ # Files cited in the PEP-location column.
+ row_files: list[Path] = []
+ for token in _backticked(location):
+ if "." in token and not token.endswith(".py"):
+ # dotted path.name form, e.g.
+ # `egress/validators.resolve_engine_allow_private_ips`
+ left, _, name = token.rpartition(".")
+ ident = _split_call_suffix(name)
+ target = _resolve_source_path(left)
+ if target is not None:
+ row_files.append(target)
+ if _BARE_IDENT_RE.match(ident) and (
+ ident not in _defined_names(target)
+ ):
+ failures.append(
+ f"README PEP table: {token!r} names "
+ f"{ident!r}, not defined in "
+ f"{target.name}"
+ )
+ continue
+ if _is_pathish(token) and not _is_abbreviated_path(token):
+ target = _resolve_source_path(token)
+ if target is None:
+ failures.append(
+ f"README PEP table cites {token!r}, which does "
+ "not resolve to an existing file under src/"
+ )
+ else:
+ row_files.append(target)
+
+ # Bare identifiers in the location column: enforcement call
+ # sites, which must live in one of the files cited on the row.
+ for token in _backticked(location):
+ ident = _split_call_suffix(token)
+ if "." in token or not _BARE_IDENT_RE.match(ident):
+ continue
+ if ident in _PROSE_IDENTIFIERS:
+ continue
+ if not any(ident in _defined_names(f) for f in row_files):
+ failures.append(
+ f"README PEP table names {ident!r} but it is not "
+ "defined in any file cited on the same row ("
+ f"{', '.join(f.name for f in row_files) or 'no files cited'})"
+ )
+
+ # Consults column: PDP surface — must exist somewhere in the
+ # egress package.
+ for token in _backticked(consults):
+ ident = _split_call_suffix(token)
+ if not _BARE_IDENT_RE.match(ident):
+ continue
+ if ident not in package_names:
+ failures.append(
+ f"README PEP table 'Consults' column cites "
+ f"{ident!r}, which is not defined anywhere in the "
+ "egress package (policy.py / fetch.py / validators.py)"
+ )
+
+ assert not failures, "\n".join(failures)
+
+
+class TestAdjacentReferences:
+ """The bullets after the PEP table cite general security utils; the
+ files must exist and the names they mention must be defined in them."""
+
+ def test_adjacent_util_files_and_names_resolve(self):
+ text = _strip_fences(README.read_text(encoding="utf-8"))
+ # Non-greedy .* stopping at the *first* blank line would end right
+ # after the heading (the heading is immediately followed by a blank
+ # line, before any bullets) and capture an empty block, making this
+ # test vacuous. Stop instead at the section's real terminator: the
+ # next heading or the "---" divider that follows the bullets and
+ # the orchestrator prose line.
+ match = re.search(
+ r"Adjacent \(general security utils.*?(?=\n---|\n#{1,6} )",
+ text,
+ flags=re.DOTALL,
+ )
+ assert match, "could not find the 'Adjacent' bullets paragraph"
+ block = match.group(0)
+
+ bullets = [
+ line for line in block.splitlines() if line.strip().startswith("- ")
+ ]
+ assert bullets, "found no 'Adjacent' bullet lines to check"
+
+ failures: list[str] = []
+ # The orchestrator mention is prose inside the same paragraph tail.
+ for line in block.splitlines():
+ tokens = _backticked(line)
+ current_file: Path | None = None
+ for token in tokens:
+ if _is_pathish(token) and not _is_abbreviated_path(token):
+ resolved = _resolve_source_path(token)
+ if resolved is None:
+ failures.append(
+ f"adjacent-references bullet cites {token!r}, "
+ "which does not resolve under src/"
+ )
+ else:
+ current_file = resolved
+ continue
+ ident = _split_call_suffix(token)
+ if not _BARE_IDENT_RE.match(ident):
+ continue
+ if current_file is not None and (
+ ident not in _defined_names(current_file)
+ ):
+ failures.append(
+ f"adjacent-references bullet: {ident!r} is not "
+ f"defined in {current_file.name}"
+ )
+ assert not failures, "\n".join(failures)
+
+
+if __name__ == "__main__": # pragma: no cover
+ pytest.main([__file__, "-v"])