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(security): gate releases on proxied login rate limits (#6901)

LearningCircuit44d5cc7a5cdb
diff --git a/.github/workflows/security-tests.yml b/.github/workflows/security-tests.yml
index a9e3039e58..f6eb679316 100644
--- a/.github/workflows/security-tests.yml
+++ b/.github/workflows/security-tests.yml
@@ -164,3 +164,95 @@ jobs:
path: |
bandit-report.json
bandit-results.sarif
+
+ # Real nginx + production uvicorn login regressions (#5787, #6442).
+ # A separate job rather than a step of security-tests: that job already
+ # uses ~22 of its 25 minutes on main (17 min of which is the parallel
+ # suite), so a trailing step would push a passing run past its timeout.
+ # Both jobs live in this reusable workflow, so release-gate.yml's
+ # `security-tests` caller job fails if either of them fails.
+ proxy-login-tests:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ permissions:
+ contents: read
+
+ steps:
+ - name: Harden the runner (Audit all outbound calls)
+ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1
+ with:
+ egress-policy: audit
+
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Set up PDM
+ uses: pdm-project/setup-pdm@544d7237314ee09c256785bd360f6b30add38b37 # v4.6
+ with:
+ python-version: '3.12'
+
+ - name: Install system dependencies for SQLCipher and nginx
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libsqlcipher-dev nginx
+
+ - name: Install dependencies
+ run: pdm sync -d
+
+ - name: Run proxied login security regressions
+ id: proxy-login-tests
+ shell: bash
+ env:
+ LDR_TESTING_WITH_MOCKS: 'false'
+ run: |
+ mkdir -p test-results
+ pdm run python -m pytest tests/integration/test_login_proxy_rate_limit.py \
+ -n 0 -p no:cov -v --tb=short --timeout=180 \
+ --basetemp=test-results/proxy-login \
+ --junitxml=test-results/proxy-login.xml \
+ 2>&1 | tee test-results/proxy-login.log
+
+ - name: Require every proxy login scenario to pass
+ id: validate-proxy-login
+ if: always()
+ shell: bash
+ run: |
+ python - <<'PYTHON'
+ from pathlib import Path
+ from xml.etree import ElementTree
+
+ report = Path("test-results/proxy-login.xml")
+ if not report.is_file():
+ raise SystemExit("Missing proxy login test report")
+ cases = list(ElementTree.parse(report).getroot().iter("testcase"))
+ expected = {
+ f"test_password_spray_hits_ip_limit[{trust}-{attack}-{mode}]"
+ for trust in ("trust-off", "trust-on")
+ for attack in ("control", "forged")
+ for mode in ("overwrite", "append", "separate-lines", "real-ip")
+ } | {
+ f"test_account_lockout_remains_separate[{trust}]"
+ for trust in ("trust-off", "trust-on")
+ }
+ if {case.get("name") for case in cases} != expected or len(cases) != len(expected):
+ raise SystemExit("Incomplete proxy login regression matrix")
+ unsuccessful = [
+ case.get("name") for case in cases
+ if any(child.tag in {"skipped", "failure", "error"} for child in case)
+ ]
+ if unsuccessful:
+ raise SystemExit(f"Unsuccessful proxy login tests: {unsuccessful}")
+ print(f"All {len(cases)} proxy login scenarios executed and passed")
+ PYTHON
+
+ - name: Upload proxy login reports
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: proxy-login-reports
+ path: |
+ test-results/proxy-login.xml
+ test-results/proxy-login.log
+ test-results/proxy-login/**/app.log
+ test-results/proxy-login/**/nginx.log
diff --git a/docs/developing/login-proxy-release-check.md b/docs/developing/login-proxy-release-check.md
new file mode 100644
index 0000000000..dbba85e4e3
--- /dev/null
+++ b/docs/developing/login-proxy-release-check.md
@@ -0,0 +1,54 @@
+# Login rate-limit release check
+
+The security release gate runs
+`tests/integration/test_login_proxy_rate_limit.py` through real nginx and the
+production uvicorn launcher. It verifies the single-proxy fix from #6442 for
+the password-spraying bypass reported in #5787.
+
+The 18 scenarios cover:
+
+- `TRUST_PROXY_HEADERS` enabled and disabled.
+- nginx overwriting both address headers, appending to X-Forwarded-For,
+ adding a separate X-Forwarded-For line, and setting only X-Real-IP while
+ clearing X-Forwarded-For.
+- Different usernames with no forged headers and with rotating, repeated
+ X-Forwarded-For headers plus a forged X-Real-IP.
+- A second client retaining its own budget after the first is blocked.
+- Repeated attempts against one username reaching account lockout before
+ the IP limit. The test sets the account threshold to three to distinguish
+ this from the five-attempt IP budget.
+
+The probe requires real HTTP 401 responses before the limit and the production
+IP limiter's JSON 429 body and retry headers afterwards. An account-lockout
+response, CSRF rejection, or proxy-wide shared bucket cannot satisfy it.
+All application state is temporary; the two servers listen only on loopback.
+No existing accounts, provider credentials, or Redis service are used.
+
+After installing development dependencies and nginx, run:
+
+```sh
+LDR_TESTING_WITH_MOCKS=false pdm run python -m pytest \
+ tests/integration/test_login_proxy_rate_limit.py \
+ -n 0 -p no:cov -v --tb=short --timeout=180
+```
+
+The proxy fixture skips mocked runs before checking for nginx or starting
+either server. The integration marker also lets ordinary CI deselect these
+tests. In `security-tests.yml`, the `proxy-login-tests` job runs them with
+its own 15-minute timeout, separate from the `security-tests` job. nginx is
+required there, and a separate report check rejects missing scenarios, skips,
+failures, and errors. Because `release-gate.yml` already requires the whole
+security workflow, a failed or timed-out probe blocks release publication.
+Its JUnit report, pytest output, and server logs are uploaded as the
+`proxy-login-reports` artifact.
+
+This verifies the supported single-proxy rate-limit behavior. It does not
+establish safe direct access from private peers, trust in arbitrary proxy
+chains, or safety when an X-Real-IP-only proxy passes untrusted X-Forwarded-For
+through. Those remain separate trust-policy concerns (#6849, #6850, #6851).
+
+For the security advisory, verify a release containing #6442 and this check
+before recording that version as patched. A passing run against `main` is
+not a released fix. Until that release exists, operators of v1.10.7 should
+overwrite both client-IP headers at their proxy and restrict access to the
+application port to that proxy.
diff --git a/tests/ci/test_login_proxy_release_gate.py b/tests/ci/test_login_proxy_release_gate.py
new file mode 100644
index 0000000000..907e7762cb
--- /dev/null
+++ b/tests/ci/test_login_proxy_release_gate.py
@@ -0,0 +1,164 @@
+"""The security release gate must execute every real-proxy login scenario."""
+
+# allow: no-sut-import — executes the security workflow's report and exit-status checks
+
+import os
+from pathlib import Path
+import subprocess
+import sys
+from xml.etree import ElementTree
+
+import pytest
+import yaml
+
+
+WORKFLOWS = Path(__file__).resolve().parents[2] / ".github" / "workflows"
+
+
[email protected](scope="module")
+def security_workflow():
+ return yaml.safe_load((WORKFLOWS / "security-tests.yml").read_text())
+
+
[email protected](scope="module")
+def security_job(security_workflow):
+ return security_workflow["jobs"]["proxy-login-tests"]
+
+
+def _step(job, step_id):
+ return next(step for step in job["steps"] if step.get("id") == step_id)
+
+
+def test_security_gate_requires_real_proxy_tests(security_job):
+ release = yaml.safe_load((WORKFLOWS / "release-gate.yml").read_text())
+ jobs = release["jobs"]
+ assert (
+ jobs["security-tests"]["uses"]
+ == "$/.github/workflows/security-tests.yml"
+ )
+ assert "security-tests" in jobs["release-gate-summary"]["needs"]
+ assert not security_job.get("continue-on-error", False)
+ run = _step(security_job, "proxy-login-tests")
+ assert "if" not in run
+ assert not run.get("continue-on-error", False)
+ assert run["shell"] == "bash"
+ assert run["env"]["LDR_TESTING_WITH_MOCKS"] == "false"
+ assert "tests/integration/test_login_proxy_rate_limit.py" in run["run"]
+ assert "-n 0" in run["run"]
+ validator = _step(security_job, "validate-proxy-login")
+ assert validator["if"] == "always()"
+ assert not validator.get("continue-on-error", False)
+
+
+def test_proxy_tests_have_their_own_job_and_timeout(security_workflow):
+ # The security-tests job already uses ~22 of its 25 minutes on main, so
+ # the proxy matrix must not share that job's timeout budget. Both jobs
+ # sit in the reusable workflow release-gate.yml calls, so a failure or
+ # timeout in either one fails the release gate's security-tests job.
+ jobs = security_workflow["jobs"]
+ suite = jobs["security-tests"]
+ proxy = jobs["proxy-login-tests"]
+ suite_ids = {step.get("id") for step in suite["steps"]}
+ assert not suite_ids & {"proxy-login-tests", "validate-proxy-login"}
+ assert "test_login_proxy_rate_limit" not in yaml.safe_dump(suite)
+ assert isinstance(proxy["timeout-minutes"], int)
+ assert 0 < proxy["timeout-minutes"] <= 30
+ # Independent of the suite job: no `needs` (it would wait out the suite
+ # and be skipped when the suite fails) and no job-level condition.
+ assert "needs" not in proxy
+ assert "if" not in proxy
+ assert not proxy.get("continue-on-error", False)
+ installs = " ".join(
+ step.get("run", "")
+ for step in proxy["steps"]
+ if "apt-get" in step.get("run", "")
+ )
+ assert "nginx" in installs and "libsqlcipher-dev" in installs
+
+
+def _report():
+ root = ElementTree.Element("testsuites")
+ suite = ElementTree.SubElement(root, "testsuite")
+ for trust in ("trust-off", "trust-on"):
+ for attack in ("control", "forged"):
+ for mode in ("overwrite", "append", "separate-lines", "real-ip"):
+ ElementTree.SubElement(
+ suite,
+ "testcase",
+ name=f"test_password_spray_hits_ip_limit[{trust}-{attack}-{mode}]",
+ )
+ ElementTree.SubElement(
+ suite,
+ "testcase",
+ name=f"test_account_lockout_remains_separate[{trust}]",
+ )
+ return root, suite
+
+
+def _run(script, tmp_path, path):
+ return subprocess.run(
+ ["bash", "-e", "-o", "pipefail", "-c", script],
+ cwd=tmp_path,
+ env={**os.environ, "PATH": f"{path}{os.pathsep}{os.environ['PATH']}"},
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+
+
+ "fault",
+ [
+ "none",
+ "missing",
+ "empty",
+ "malformed",
+ "partial",
+ "duplicate",
+ "skipped",
+ "failure",
+ "error",
+ ],
+)
+def test_report_checker_rejects_incomplete_or_failed_runs(
+ security_job, tmp_path, fault
+):
+ root, suite = _report()
+ report = tmp_path / "test-results" / "proxy-login.xml"
+ report.parent.mkdir()
+ if fault == "empty":
+ suite.clear()
+ elif fault == "partial":
+ suite.remove(suite[0])
+ elif fault == "duplicate":
+ suite.append(suite[0])
+ elif fault in {"skipped", "failure", "error"}:
+ ElementTree.SubElement(suite[0], fault)
+ if fault == "malformed":
+ report.write_text("<testsuites>")
+ elif fault != "missing":
+ ElementTree.ElementTree(root).write(report)
+ result = _run(
+ _step(security_job, "validate-proxy-login")["run"],
+ tmp_path,
+ Path(sys.executable).parent,
+ )
+ assert (result.returncode == 0) is (fault == "none"), (
+ result.stdout + result.stderr
+ )
+
+
+ "status", [0, 1, 5], ids=["pass", "failure", "no-tests"]
+)
+def test_logging_pipeline_preserves_pytest_exit_status(
+ security_job, tmp_path, status
+):
+ binary = tmp_path / "pdm"
+ binary.write_text(f"#!/bin/sh\nprintf 'pytest output\\n'\nexit {status}\n")
+ binary.chmod(0o755)
+ result = _run(
+ _step(security_job, "proxy-login-tests")["run"], tmp_path, tmp_path
+ )
+ assert result.returncode == status, result.stdout + result.stderr
diff --git a/tests/integration/test_login_proxy_rate_limit.py b/tests/integration/test_login_proxy_rate_limit.py
new file mode 100644
index 0000000000..ee7b979e24
--- /dev/null
+++ b/tests/integration/test_login_proxy_rate_limit.py
@@ -0,0 +1,277 @@
+"""Exercise #5787 through real nginx, uvicorn, and the production login route.
+
+Run with LDR_TESTING_WITH_MOCKS=false and nginx on PATH. No provider, Redis,
+or existing user database is needed. Both servers bind only to loopback and
+the application stores all state below pytest's temporary directory.
+"""
+
+# allow: no-sut-import — black-box HTTP test launches the production web application
+
+from contextlib import contextmanager
+import itertools
+import os
+from pathlib import Path
+import shutil
+import socket
+import subprocess
+import sys
+import time
+from uuid import uuid4
+
+import httpx
+import pytest
+
+
+pytestmark = pytest.mark.integration
+REPO_ROOT = Path(__file__).resolve().parents[2]
+LOGIN_BUDGET = 5
+ACCOUNT_BUDGET = 3
+MODES = ("overwrite", "append", "separate-lines", "real-ip")
+
+
+def _unused_port():
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ return listener.getsockname()[1]
+
+
+@contextmanager
+def _server(command, log_path, ready_url, *, env=None):
+ """Fail on startup errors and reap the process even if an assertion fails."""
+ with log_path.open("w") as log:
+ process = subprocess.Popen(
+ command,
+ cwd=REPO_ROOT,
+ env=env,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ )
+ try:
+ deadline = time.monotonic() + 90
+ with httpx.Client(trust_env=False, timeout=1) as client:
+ while time.monotonic() < deadline:
+ if process.poll() is not None:
+ pytest.fail(f"Server exited:\n{log_path.read_text()}")
+ try:
+ response = client.get(ready_url)
+ if response.status_code == 200:
+ break
+ except httpx.TransportError:
+ pass # Server is still starting; the deadline bounds retries.
+ time.sleep(0.1)
+ else:
+ pytest.fail(
+ f"Server did not start:\n{log_path.read_text()}"
+ )
+ yield
+ finally:
+ process.terminate()
+ try:
+ process.wait(timeout=15)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+
+
+ scope="module", params=[False, True], ids=["trust-off", "trust-on"]
+)
+def proxy(request, tmp_path_factory):
+ # Module fixtures run before the function-scoped integration skip.
+ if os.environ.get("LDR_TESTING_WITH_MOCKS", "true").lower() == "true":
+ pytest.skip(
+ "Integration test skipped in mock mode "
+ "(set LDR_TESTING_WITH_MOCKS=false to run)"
+ )
+ nginx = shutil.which("nginx")
+ if nginx is None:
+ pytest.fail("This integration test requires nginx on PATH")
+ root = tmp_path_factory.mktemp(f"login-proxy-{request.param}")
+ app_port, proxy_port = _unused_port(), _unused_port()
+ while proxy_port == app_port:
+ proxy_port = _unused_port()
+
+ # Do not inherit a real data directory, disabled throttling, external
+ # storage, or pytest's production-cookie bypass into the child process.
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if not key.startswith("LDR_")
+ and key
+ not in {
+ "PYTEST_CURRENT_TEST",
+ "TRUST_PROXY_HEADERS",
+ "DISABLE_RATE_LIMITING",
+ "RATE_LIMIT_STORAGE_URI",
+ "RATELIMIT_STORAGE_URL",
+ }
+ }
+ env.update(
+ PYTHONPATH=os.pathsep.join(
+ [str(REPO_ROOT / "src"), env.get("PYTHONPATH", "")]
+ ),
+ LDR_DATA_DIR=str(root / "data"),
+ LDR_TEST_MODE="false",
+ LDR_DISABLE_RATE_LIMITING="false",
+ LDR_SECURITY_RATE_LIMIT_LOGIN=f"{LOGIN_BUDGET} per 15 minutes",
+ LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD=str(ACCOUNT_BUDGET),
+ LDR_NEWS_SCHEDULER_ENABLED="false",
+ RATE_LIMIT_STORAGE_URI="memory://",
+ TRUST_PROXY_HEADERS=str(request.param).lower(),
+ )
+ # Use the production launcher so this includes uvicorn's actual
+ # proxy_headers/forwarded_allow_ips wiring, not a TestClient simulation.
+ command = [
+ sys.executable,
+ "-c",
+ "from local_deep_research.web.app import _run_with_uvicorn; "
+ f"_run_with_uvicorn('127.0.0.1', {app_port}, False)",
+ ]
+ headers = {
+ "overwrite": """
+ proxy_set_header X-Forwarded-For $remote_addr;
+ proxy_set_header X-Real-IP $remote_addr;
+ """,
+ "append": """
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ """,
+ "separate-lines": """
+ proxy_set_header X-Forwarded-For $http_x_forwarded_for;
+ proxy_set_header X-Forwarded-For $remote_addr;
+ """,
+ # A proxy using only X-Real-IP must clear the untrusted XFF header
+ # (#6849). This covers the supported fallback, not that open defect.
+ "real-ip": """
+ proxy_set_header X-Forwarded-For "";
+ proxy_set_header X-Real-IP $remote_addr;
+ """,
+ }
+ locations = "\n".join(
+ f"""location /{mode}/ {{
+ proxy_pass http://127.0.0.1:{app_port}/;
+ proxy_set_header Host $http_host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ {directives}
+ }}"""
+ for mode, directives in headers.items()
+ )
+ config = root / "nginx.conf"
+ config.write_text(
+ f"""daemon off;
+master_process off;
+error_log stderr;
+pid "{root / "nginx.pid"}";
+events {{ worker_connections 64; }}
+http {{
+ access_log off;
+ client_body_temp_path "{root / "client-body"}";
+ proxy_temp_path "{root / "proxy-temp"}";
+ fastcgi_temp_path "{root / "fastcgi-temp"}";
+ uwsgi_temp_path "{root / "uwsgi-temp"}";
+ scgi_temp_path "{root / "scgi-temp"}";
+ server {{
+ listen 127.0.0.1:{proxy_port};
+ location = /ready {{ return 200 'ready'; }}
+ {locations}
+ }}
+}}
+"""
+ )
+ with (
+ _server(
+ command,
+ root / "app.log",
+ f"http://127.0.0.1:{app_port}/auth/csrf-token",
+ env=env,
+ ),
+ _server(
+ [nginx, "-p", str(root), "-c", str(config), "-e", "stderr"],
+ root / "nginx.log",
+ f"http://127.0.0.1:{proxy_port}/ready",
+ ),
+ ):
+ yield f"http://127.0.0.1:{proxy_port}", itertools.count(2)
+
+
+@contextmanager
+def _client(proxy, mode):
+ address, addresses = proxy
+ # Actual socket source addresses give each scenario an independent bucket
+ # without resetting the limiter or letting a request header pick its key.
+ source = f"127.0.0.{next(addresses)}"
+ with httpx.Client(
+ base_url=f"{address}/{mode}/",
+ transport=httpx.HTTPTransport(local_address=source),
+ trust_env=False,
+ timeout=10,
+ ) as client:
+ response = client.get("auth/csrf-token")
+ assert response.status_code == 200, response.text
+ client.headers["X-CSRFToken"] = response.json()["csrf_token"]
+ yield client
+
+
+def _login(client, username, attempt, forged):
+ headers = []
+ if forged:
+ headers = [
+ ("X-Forwarded-For", f"9.9.9.{attempt + 1}, 8.8.8.8"),
+ ("X-Forwarded-For", f"1.1.1.{attempt + 1}"),
+ ("X-Real-IP", f"4.4.4.{attempt + 1}"),
+ ]
+ return client.post(
+ "auth/login",
+ data={"username": username, "password": "incorrect-password"},
+ headers=headers,
+ )
+
+
+def _assert_ip_limit(response):
+ # Account lockout is HTML; CSRF is 403. Require the production IP-limit
+ # handler's JSON and headers so neither can give a false positive.
+ assert response.status_code == 429, response.text
+ assert response.json() == {
+ "error": "Too many requests",
+ "message": "Too many attempts. Please try again later.",
+ }
+ assert int(response.headers["Retry-After"]) > 0
+ assert int(response.headers["X-RateLimit-Limit"]) == LOGIN_BUDGET
+ assert int(response.headers["X-RateLimit-Remaining"]) == 0
+
+
[email protected]("mode", MODES)
[email protected]("forged", [False, True], ids=["control", "forged"])
+def test_password_spray_hits_ip_limit(proxy, mode, forged):
+ prefix = uuid4().hex[:12]
+ with _client(proxy, mode) as client:
+ for attempt in range(LOGIN_BUDGET + 2):
+ # A different username per request prevents account lockout from
+ # hiding a bypass. Keep usernames unique across scenarios too.
+ username = f"spray-{prefix}-{attempt}"
+ response = _login(client, username, attempt, forged)
+ if attempt < LOGIN_BUDGET:
+ assert response.status_code == 401, response.text
+ else:
+ _assert_ip_limit(response)
+
+ # A fresh client must still get its own budget: simply collapsing
+ # everyone into the nginx loopback address would also stop the spray.
+ with _client(proxy, mode) as independent:
+ response = _login(independent, f"independent-{prefix}", 0, forged)
+ assert response.status_code == 401, response.text
+ _assert_ip_limit(_login(client, f"still-blocked-{prefix}", 8, forged))
+
+
+def test_account_lockout_remains_separate(proxy):
+ with _client(proxy, "append") as client:
+ username = f"same-account-{uuid4().hex[:12]}"
+ for attempt in range(LOGIN_BUDGET + 1):
+ response = _login(client, username, attempt, True)
+ if attempt < ACCOUNT_BUDGET:
+ assert response.status_code == 401, response.text
+ elif attempt < LOGIN_BUDGET:
+ assert response.status_code == 429, response.text
+ assert "temporarily locked" in response.text
+ assert "Retry-After" not in response.headers
+ else:
+ _assert_ip_limit(response)