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.

fix(web): make cookie test mode independent of pytest import order (#7293)

LearningCircuit336151b040f4
diff --git a/changelog.d/+explicit-web-test-mode.bugfix.md b/changelog.d/+explicit-web-test-mode.bugfix.md
new file mode 100644
index 0000000000..1594643dad
--- /dev/null
+++ b/changelog.d/+explicit-web-test-mode.bugfix.md
@@ -0,0 +1 @@
+Make web test mode depend only on the explicit `LDR_TEST_MODE` setting, so pytest import order cannot change HTTPS session-cookie protection or API documentation exposure.
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index bd563dc49a..8d064b3091 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -2326,26 +2326,12 @@ def _setup_template_globals() -> None:
# the KDF floor on CI/TESTING for exactly this reason. The cookie path had not
# been given that treatment.
#
-# PYTEST_CURRENT_TEST is presence-based (pytest sets it to a descriptive
-# string); LDR_TEST_MODE is parsed as a real boolean so `LDR_TEST_MODE=0` does
-# not enable test mode.
-#
-# CAVEAT, measured rather than assumed: this is evaluated at IMPORT time, and
-# pytest sets PYTEST_CURRENT_TEST only while a test body runs -- not during
-# collection, which is when a test module's top-level `import fastapi_app`
-# actually happens. So under a normal run this half is False and
-# LDR_TEST_MODE is the only switch that reaches here. Contrast
-# sqlcipher_utils::_get_min_kdf_iterations, which reads the same variable
-# INSIDE a function and therefore does see it.
-#
-# That is deliberate rather than a gap worth "fixing": the effect of False is
-# that tests exercise the production cookie path, which is the stricter and
-# more realistic behaviour. Do not switch this to a lazy/per-request lookup
-# expecting tests to relax -- it would re-open exactly the hole the paragraph
-# above describes, just keyed on a different variable.
-is_testing = bool(os.getenv("PYTEST_CURRENT_TEST")) or to_bool(
- os.getenv("LDR_TEST_MODE")
-)
+# Only the explicit operator switch controls cookie test mode. Pytest's
+# per-test marker changes between collection and execution, so consulting it
+# here would make cookie protection and docs exposure depend on import order.
+# Keep the production cookie behavior by default, including under pytest.
+# LDR_TEST_MODE is parsed as a boolean, so "0" and "false" do not enable it.
+is_testing = to_bool(os.getenv("LDR_TEST_MODE"))
# Public API docs are disabled by default — a multi-user deployment
# shouldn't expose the full schema unauthenticated. Set LDR_EXPOSE_DOCS=true
diff --git a/tests/security/test_cookie_security.py b/tests/security/test_cookie_security.py
index e2cfa8d596..0b68ced65b 100644
--- a/tests/security/test_cookie_security.py
+++ b/tests/security/test_cookie_security.py
@@ -7,7 +7,7 @@ Security model (unchanged by the migration):
an HTTP response makes the browser drop the cookie entirely, so doing it
on an IP heuristic broke legitimate Docker/LAN access while providing no
cryptographic protection whatsoever (issue #3849).
-- TESTING mode: never Secure (for CI/development).
+- Explicit LDR_TEST_MODE: never Secure (for CI/development).
WHAT CHANGED, MECHANICALLY
--------------------------
@@ -55,9 +55,9 @@ add_src_to_path()
def _built_secure_cookie_middleware(app):
"""Walk the built middleware stack to the live SecureCookieMiddleware.
- ``fastapi_app`` constructs it with ``testing=True`` under pytest, which
- disables the Secure flag outright — so every assertion below would be
- vacuously satisfied until this instance is flipped.
+ Explicit ``LDR_TEST_MODE`` can disable the Secure flag. These checks
+ force production mode and restore the original value afterwards, so
+ they verify the scheme policy regardless of that startup setting.
"""
from local_deep_research.web.fastapi_app import SecureCookieMiddleware
diff --git a/tests/security/test_sqlcipher_key_lifecycle.py b/tests/security/test_sqlcipher_key_lifecycle.py
index 88333012b7..d0236ab794 100644
--- a/tests/security/test_sqlcipher_key_lifecycle.py
+++ b/tests/security/test_sqlcipher_key_lifecycle.py
@@ -209,15 +209,12 @@ class TestKdfFloorProductionReachability:
"KDF floor would be frozen at import time"
)
- def test_the_documented_inert_sibling_is_still_import_time(self):
- """Negative control for the check above, taken from the codebase.
-
- ``fastapi_app.is_testing`` is the SAME two-variable idiom evaluated at
- module scope, which the branch documents as deliberately inert under
- pytest (the production cookie path is the stricter one). Pinning it
- here means the two forms cannot silently converge: if someone makes
- ``is_testing`` lazy "so tests relax", this fails and points at the
- comment explaining why that re-opens a Secure-cookie hole.
+ def test_web_cookie_test_mode_is_still_import_time(self):
+ """The web cookie policy uses an explicit startup switch.
+
+ Unlike the KDF test helper, ``fastapi_app.is_testing`` must not change
+ per test or per request. Its default exercises production cookie
+ behavior, regardless of when pytest first imports the app.
"""
tree = ast.parse(_source_of("local_deep_research.web.fastapi_app"))
assigns = [
@@ -231,7 +228,7 @@ class TestKdfFloorProductionReachability:
]
assert len(assigns) == 1, (
"fastapi_app.is_testing is no longer a single module-level "
- "assignment — re-read the caveat comment above it before changing "
+ "assignment — re-read the startup-policy comment before changing "
"this test"
)
diff --git a/tests/test_config_env_var_contracts.py b/tests/test_config_env_var_contracts.py
index 619a214d31..ec311ff121 100644
--- a/tests/test_config_env_var_contracts.py
+++ b/tests/test_config_env_var_contracts.py
@@ -921,8 +921,7 @@ def test_empty_env_var_is_treated_as_unset_not_as_false(monkeypatch):
# matters for *pairs*, where the same variable is also read dynamically
# elsewhere and the two answers can disagree.
_KNOWN_IMPORT_TIME_READS = {
- # documented in-file as deliberate; the pytest half is inert at import
- ("web/fastapi_app.py", "PYTEST_CURRENT_TEST"),
+ # Cookie test mode is frozen from the explicit operator switch only.
("web/fastapi_app.py", "LDR_TEST_MODE"),
# docs_url / openapi_url are decided when FastAPI() is constructed
("web/fastapi_app.py", "LDR_EXPOSE_DOCS"),
diff --git a/tests/web/routers/test_fastapi_migration.py b/tests/web/routers/test_fastapi_migration.py
index 6c7c4e5d9f..deb9f6e45a 100644
--- a/tests/web/routers/test_fastapi_migration.py
+++ b/tests/web/routers/test_fastapi_migration.py
@@ -79,10 +79,10 @@ def test_health_endpoint(client):
assert "timestamp" in data
-def test_swagger_docs_disabled_in_testing(client):
- """Swagger UI is disabled during testing (PYTEST_CURRENT_TEST is set)."""
+def test_swagger_docs_disabled_by_default(client):
+ """Swagger UI requires the explicit LDR_EXPOSE_DOCS operator switch."""
resp = client.get("/api/docs")
- # Docs are disabled in test mode — 404 is expected
+ # Docs are disabled by default — 404 is expected
assert resp.status_code == 404
diff --git a/tests/web/test_security_headers_matrix.py b/tests/web/test_security_headers_matrix.py
index f18a6eaabc..9a9c506606 100644
--- a/tests/web/test_security_headers_matrix.py
+++ b/tests/web/test_security_headers_matrix.py
@@ -56,6 +56,10 @@ under test would mean weakening the code also weakens the test.
import ast
import asyncio
import inspect
+import json
+import os
+import subprocess
+import sys
from pathlib import Path
import pytest
@@ -693,8 +697,8 @@ class TestCookieSurface:
def test_secure_flag_is_wired_to_the_ldr_test_mode_toggle(self):
"""``SecureCookieMiddleware(testing=True)`` disables the Secure
flag outright, and the live app passes ``testing=is_testing``,
- which fastapi_app computes from ``PYTEST_CURRENT_TEST`` OR the
- operator-facing ``LDR_TEST_MODE`` env var. That makes
+ which fastapi_app computes from the explicit operator-facing
+ ``LDR_TEST_MODE`` env var. That makes
``LDR_TEST_MODE`` a production-affecting security toggle: setting
it on an HTTPS deployment silently drops ``Secure`` from every
session cookie. Pinned so the wiring cannot be changed — in
@@ -741,32 +745,109 @@ class TestCookieSurface:
f"browsers drop it: {kwargs!r}"
)
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT (latent, currently benign): fastapi_app.py computes "
- "`is_testing` at IMPORT time from PYTEST_CURRENT_TEST, but "
- "pytest sets that variable only while a test is executing — "
- "never during collection, which is when every test module that "
- "imports fastapi_app (including this one) triggers the import. "
- "So the PYTEST_CURRENT_TEST arm never fires and the only live "
- "route into testing mode is the LDR_TEST_MODE env var. The "
- "docstring of `secure_cookie_mw_active` in tests/web/"
- "test_session_cookie_behavior.py states the opposite "
- "('fastapi_app constructs it with testing=True under pytest'), "
- "and that fixture exists solely to undo a state that never "
- "happens. Harmless today — Secure being ENABLED under test is "
- "the safe direction — but it is import-order dependent: a run "
- "whose first import of fastapi_app happens inside a test body "
- "flips it, silently changing cookie behaviour for the whole "
- "session. Remove this marker once is_testing is resolved per "
- "request, or once the dead PYTEST_CURRENT_TEST arm is dropped "
- "and the sibling fixture's docstring corrected."
- ),
+ @pytest.mark.parametrize(
+ ("test_env", "expected_testing"),
+ [
+ ({}, False),
+ ({"PYTEST_CURRENT_TEST": "test_probe.py::case (call)"}, False),
+ (
+ {
+ "PYTEST_CURRENT_TEST": "test_probe.py::case (call)",
+ "CI": "true",
+ "TESTING": "1",
+ },
+ False,
+ ),
+ (
+ {
+ "LDR_TEST_MODE": "0",
+ "PYTEST_CURRENT_TEST": "test_probe.py::case (call)",
+ },
+ False,
+ ),
+ (
+ {
+ "LDR_TEST_MODE": "false",
+ "PYTEST_CURRENT_TEST": "test_probe.py::case (call)",
+ },
+ False,
+ ),
+ ({"LDR_TEST_MODE": "true"}, True),
+ (
+ {
+ "LDR_TEST_MODE": "1",
+ "PYTEST_CURRENT_TEST": "test_probe.py::case (call)",
+ },
+ True,
+ ),
+ ],
+ ids=[
+ "collection",
+ "during-test",
+ "ci-during-test",
+ "explicit-zero",
+ "explicit-false",
+ "explicit-true",
+ "explicit-one-during-test",
+ ],
)
- def test_pytest_current_test_really_puts_the_app_in_testing_mode(self):
- assert _fastapi_app.is_testing is True, (
- "is_testing is False while running under pytest: the "
- "PYTEST_CURRENT_TEST arm of fastapi_app.py's is_testing did "
- "not fire"
+ def test_only_explicit_test_mode_changes_cookie_and_docs_policy(
+ self, tmp_path, test_env, expected_testing
+ ):
+ """A fresh app import has the same policy before and during a test."""
+ env = os.environ.copy()
+ for key in ("LDR_TEST_MODE", "PYTEST_CURRENT_TEST", "CI", "TESTING"):
+ env.pop(key, None)
+ env.update(
+ LDR_DATA_DIR=str(tmp_path),
+ LDR_BOOTSTRAP_DATA_DIR=str(tmp_path),
+ LDR_EXPOSE_DOCS="true",
+ LDR_BOOTSTRAP_ALLOW_UNENCRYPTED="true",
+ **test_env,
+ )
+ probe = """
+import json
+from fastapi.testclient import TestClient
+from local_deep_research.web.fastapi_app import app, is_testing
+
+client = TestClient(app, base_url="https://testserver")
+try:
+ response = client.get("/auth/csrf-token")
+ print(json.dumps({
+ "testing": is_testing,
+ "status": response.status_code,
+ "cookies": response.headers.get_list("set-cookie"),
+ "docs_url": app.docs_url,
+ "openapi_url": app.openapi_url,
+ }))
+finally:
+ client.close()
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", probe],
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=90,
+ )
+ assert result.returncode == 0, result.stderr[-3000:]
+ observed = json.loads(result.stdout.strip().splitlines()[-1])
+ assert observed["status"] == 200
+ assert observed["testing"] is expected_testing
+ cookies = [
+ value
+ for value in observed["cookies"]
+ if value.lower().startswith("session=")
+ ]
+ assert len(cookies) == 1, observed
+ attributes = {
+ part.strip().lower() for part in cookies[0].split(";")[1:]
+ }
+ assert ("secure" in attributes) is (not expected_testing), observed
+ assert "httponly" in attributes
+ assert observed["docs_url"] == (
+ None if expected_testing else "/api/docs"
+ )
+ assert observed["openapi_url"] == (
+ None if expected_testing else "/openapi.json"
)
diff --git a/tests/web/test_session_cookie_behavior.py b/tests/web/test_session_cookie_behavior.py
index 8c1d9124b6..c03a406bfa 100644
--- a/tests/web/test_session_cookie_behavior.py
+++ b/tests/web/test_session_cookie_behavior.py
@@ -220,8 +220,8 @@ def _built_secure_cookie_middleware(app):
@pytest.fixture
def secure_cookie_mw_active(app, monkeypatch):
"""Force one request so the middleware stack is built, then flip the
- live SecureCookieMiddleware out of testing mode (monkeypatch restores
- it afterwards, so other tests keep the Secure-suppressed behavior)."""
+ live SecureCookieMiddleware to production mode regardless of the explicit
+ LDR_TEST_MODE setting. Monkeypatch restores its original value afterwards."""
_fresh_client(app).get("/auth/login")
mw = _built_secure_cookie_middleware(app)
assert mw is not None, (
diff --git a/tests/web/test_startup_ordering_contracts.py b/tests/web/test_startup_ordering_contracts.py
index b67e6fba5f..dbafedb99c 100644
--- a/tests/web/test_startup_ordering_contracts.py
+++ b/tests/web/test_startup_ordering_contracts.py
@@ -11,11 +11,10 @@ stack, constructs the rate limiter, registers the template globals, imports
and mounts twenty routers and validates the link table -- all at module
scope, before any lifespan runs and before any caller can influence a thing.
Whatever configuration those statements read is therefore frozen for the life
-of the process. One instance of that is already documented in the source
-(``is_testing`` is computed at import, so ``PYTEST_CURRENT_TEST`` -- which
-pytest only sets while a test body runs -- is always absent there). The
-inventory below pins the other twelve, across five modules, so that adding a
-fourteenth is a visible diff rather than a silent restart-only setting.
+of the process. For example, ``LDR_TEST_MODE`` determines cookie test mode
+once at import; pytest's per-test marker does not affect that policy. The
+inventory below pins these reads across five modules, so adding another
+restart-only setting is a visible diff.
**Which startup failures still serve traffic.** Twelve of the lifespan's
steps sit inside a ``try/except Exception`` that logs and continues (ten
@@ -351,10 +350,6 @@ def test_the_guard_scanner_separates_swallowing_from_reraising():
#: embedding process sets after the first import.
_IMPORT_TIME_CONFIG = {
"web/fastapi_app.py": {
- # Confirmed and documented in the source: PYTEST_CURRENT_TEST is
- # unset during collection, when this module is imported, so this
- # half of `is_testing` is always False under a normal pytest run.
- "PYTEST_CURRENT_TEST",
"LDR_TEST_MODE",
# Gates /api/docs AND /openapi.json.
"LDR_EXPOSE_DOCS",
@@ -407,16 +402,16 @@ def test_the_import_time_configuration_inventory_is_pinned():
}
total = sum(len(v) for v in actual.values())
- assert total >= 13, (
+ assert total >= 12, (
"the import-time sweep found only "
f"{total} module-scope configuration reads across "
- f"{len(_IMPORT_TIME_CONFIG)} modules. It should find at least 13; a "
+ f"{len(_IMPORT_TIME_CONFIG)} modules. It should find at least 12; a "
"near-empty result means the scanner stopped matching, not that the "
f"port stopped freezing configuration. Found: {actual}"
)
must_include = {
- "web/fastapi_app.py": {"PYTEST_CURRENT_TEST", "LDR_EXPOSE_DOCS"},
+ "web/fastapi_app.py": {"LDR_TEST_MODE", "LDR_EXPOSE_DOCS"},
"web/dependencies/rate_limit.py": {
"TRUST_PROXY_HEADERS",
"is_rate_limiting_enabled()",