~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(auth): allow more registration retries (#7329)
LearningCircuit0f8d1c482ea5
diff --git a/changelog.d/+registration-rate-limit.bugfix.md b/changelog.d/+registration-rate-limit.bugfix.mdnew file mode 100644index 0000000000..729e8afbc7--- /dev/null+++ b/changelog.d/+registration-rate-limit.bugfix.md@@ -0,0 +1,3 @@+Allow registration retries with a default limit of 10 attempts per minute and+300 per hour per client IP, instead of 3 per hour. Both limits include failed+attempts. Existing environment and legacy configuration overrides still apply.diff --git a/changelog.d/4870.security.md b/changelog.d/4870.security.mdindex 3495528ddc..04074b01ec 100644--- a/changelog.d/4870.security.md+++ b/changelog.d/4870.security.md@@ -1,4 +1,4 @@-**Breaking change for deployments behind a reverse proxy, whether or not they set `TRUST_PROXY_HEADERS`.** Up to v1.10.7 the rate limiter keyed on the left-most `X-Forwarded-For` entry, or else `X-Real-IP`, sent by *any* peer, so any client could choose its own rate-limit bucket. What it does now depends on the configuration. **With `TRUST_PROXY_HEADERS` unset/false** it reads those headers only from a direct peer that is private, loopback or link-local (6to4 `2002::/16`, Teredo `2001::/32` and NAT64 `64:ff9b::/96`/`64:ff9b:1::/48` peers do not count on any Python version, although Python's `ipaddress` may report some of them private, depending on the version), or, once `LDR_SERVER_FORWARDED_ALLOW_IPS` is set to a restricted list, only from a peer in that list; and it keys on the **right-most** `X-Forwarded-For` entry, or `X-Real-IP` when no `X-Forwarded-For` is present. **With `TRUST_PROXY_HEADERS=true` and a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`** only a listed peer's headers count: the key is the client address uvicorn derived from a listed peer's `X-Forwarded-For`, or, when no `X-Forwarded-For` is present, a listed peer's `X-Real-IP`; any other peer is keyed on its own address. **With `TRUST_PROXY_HEADERS=true` and `LDR_SERVER_FORWARDED_ALLOW_IPS` unset** the key is the **right-most** `X-Forwarded-For` entry from *any* peer, public addresses included. That is still an improvement on v1.10.7's left-most entry (a client behind one appending proxy can no longer choose its bucket with a forged prefix), but a client connecting straight to LDR writes the whole header and still chooses its key, so set `LDR_SERVER_FORWARDED_ALLOW_IPS`; LDR logs a startup warning saying so. In this mode `X-Real-IP` is read only from a private, loopback or link-local peer. What changes for an existing deployment that never set `TRUST_PROXY_HEADERS`: (1) a proxy that reaches LDR from a public or carrier-grade-NAT address — a cloud load balancer, a Tailscale/CGNAT peer in `100.64.0.0/10`, a public nginx host — has its forwarded headers ignored, collapsing every client behind it into one rate-limit bucket and making the login (5/15min) and registration (3/hour) lockouts deployment-global; set `LDR_SERVER_FORWARDED_ALLOW_IPS=<proxy address(es)>`. (2) A single proxy on a private or Docker network keeps per-client keying, provided it **overwrites** `X-Forwarded-For` and `X-Real-IP` with the address it observed: a client-sent header passed through unchanged still lets that client choose its key, and a proxy that sets only `X-Real-IP` must also clear `X-Forwarded-For`, which LDR prefers. An appending proxy now yields the address it observed rather than the client's forged left-most entry. (3) Behind a chain of proxies (CDN → nginx) the default settings key every client on the outer proxy's address, whether the inner proxy appends or overwrites with a plain `$remote_addr`, so all of them share one bucket and the login and registration lockouts become deployment-global. Either have the inner proxy resolve the real client itself (nginx `realip`) and overwrite with that address, or make every inner proxy append and set a multi-hop setting: `LDR_SERVER_TRUSTED_PROXY_COUNT` (below), or `TRUST_PROXY_HEADERS=true` with every hop listed in `LDR_SERVER_FORWARDED_ALLOW_IPS` (an allow-list without `TRUST_PROXY_HEADERS=true` still keys on the right-most entry). See "Proxy chains" in `docs/deployment/reverse-proxy.md`. What changes for a deployment with `TRUST_PROXY_HEADERS=true` and no `LDR_SERVER_FORWARDED_ALLOW_IPS`: points (2) and (3) apply (for an appending chain, list every hop in `LDR_SERVER_FORWARDED_ALLOW_IPS`; `LDR_SERVER_TRUSTED_PROXY_COUNT` has no effect in this mode, and setting it without the allow-list makes LDR refuse to start), but a public-address proxy's `X-Forwarded-For` is still honoured; only its `X-Real-IP` is ignored (v1.10.7 honoured it from any peer). So a proxy on a public or carrier-grade-NAT address that sends `X-Real-IP` and no `X-Forwarded-For` of its own, such as an nginx with only `proxy_set_header X-Real-IP $remote_addr`, is keyed on its own address and collapses all its clients into one bucket until you set `LDR_SERVER_FORWARDED_ALLOW_IPS` to that proxy's IP address as LDR sees it; having the proxy overwrite `X-Forwarded-For` with the address it observed also restores per-client keys. Appending to `X-Forwarded-For` yields the right rate-limit key there too, but while `LDR_SERVER_FORWARDED_ALLOW_IPS` is unset uvicorn reports the left-most, client-written entry as the request's client address, so a single proxy should overwrite (for a chain, see (3)).+**Breaking change for deployments behind a reverse proxy, whether or not they set `TRUST_PROXY_HEADERS`.** Up to v1.10.7 the rate limiter keyed on the left-most `X-Forwarded-For` entry, or else `X-Real-IP`, sent by *any* peer, so any client could choose its own rate-limit bucket. What it does now depends on the configuration. **With `TRUST_PROXY_HEADERS` unset/false** it reads those headers only from a direct peer that is private, loopback or link-local (6to4 `2002::/16`, Teredo `2001::/32` and NAT64 `64:ff9b::/96`/`64:ff9b:1::/48` peers do not count on any Python version, although Python's `ipaddress` may report some of them private, depending on the version), or, once `LDR_SERVER_FORWARDED_ALLOW_IPS` is set to a restricted list, only from a peer in that list; and it keys on the **right-most** `X-Forwarded-For` entry, or `X-Real-IP` when no `X-Forwarded-For` is present. **With `TRUST_PROXY_HEADERS=true` and a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`** only a listed peer's headers count: the key is the client address uvicorn derived from a listed peer's `X-Forwarded-For`, or, when no `X-Forwarded-For` is present, a listed peer's `X-Real-IP`; any other peer is keyed on its own address. **With `TRUST_PROXY_HEADERS=true` and `LDR_SERVER_FORWARDED_ALLOW_IPS` unset** the key is the **right-most** `X-Forwarded-For` entry from *any* peer, public addresses included. That is still an improvement on v1.10.7's left-most entry (a client behind one appending proxy can no longer choose its bucket with a forged prefix), but a client connecting straight to LDR writes the whole header and still chooses its key, so set `LDR_SERVER_FORWARDED_ALLOW_IPS`; LDR logs a startup warning saying so. In this mode `X-Real-IP` is read only from a private, loopback or link-local peer. What changes for an existing deployment that never set `TRUST_PROXY_HEADERS`: (1) a proxy that reaches LDR from a public or carrier-grade-NAT address — a cloud load balancer, a Tailscale/CGNAT peer in `100.64.0.0/10`, a public nginx host — has its forwarded headers ignored, collapsing every client behind it into one rate-limit bucket and making the login (5/15min) and registration (10/minute and 300/hour) lockouts deployment-global; set `LDR_SERVER_FORWARDED_ALLOW_IPS=<proxy address(es)>`. (2) A single proxy on a private or Docker network keeps per-client keying, provided it **overwrites** `X-Forwarded-For` and `X-Real-IP` with the address it observed: a client-sent header passed through unchanged still lets that client choose its key, and a proxy that sets only `X-Real-IP` must also clear `X-Forwarded-For`, which LDR prefers. An appending proxy now yields the address it observed rather than the client's forged left-most entry. (3) Behind a chain of proxies (CDN → nginx) the default settings key every client on the outer proxy's address, whether the inner proxy appends or overwrites with a plain `$remote_addr`, so all of them share one bucket and the login and registration lockouts become deployment-global. Either have the inner proxy resolve the real client itself (nginx `realip`) and overwrite with that address, or make every inner proxy append and set a multi-hop setting: `LDR_SERVER_TRUSTED_PROXY_COUNT` (below), or `TRUST_PROXY_HEADERS=true` with every hop listed in `LDR_SERVER_FORWARDED_ALLOW_IPS` (an allow-list without `TRUST_PROXY_HEADERS=true` still keys on the right-most entry). See "Proxy chains" in `docs/deployment/reverse-proxy.md`. What changes for a deployment with `TRUST_PROXY_HEADERS=true` and no `LDR_SERVER_FORWARDED_ALLOW_IPS`: points (2) and (3) apply (for an appending chain, list every hop in `LDR_SERVER_FORWARDED_ALLOW_IPS`; `LDR_SERVER_TRUSTED_PROXY_COUNT` has no effect in this mode, and setting it without the allow-list makes LDR refuse to start), but a public-address proxy's `X-Forwarded-For` is still honoured; only its `X-Real-IP` is ignored (v1.10.7 honoured it from any peer). So a proxy on a public or carrier-grade-NAT address that sends `X-Real-IP` and no `X-Forwarded-For` of its own, such as an nginx with only `proxy_set_header X-Real-IP $remote_addr`, is keyed on its own address and collapses all its clients into one bucket until you set `LDR_SERVER_FORWARDED_ALLOW_IPS` to that proxy's IP address as LDR sees it; having the proxy overwrite `X-Forwarded-For` with the address it observed also restores per-client keys. Appending to `X-Forwarded-For` yields the right rate-limit key there too, but while `LDR_SERVER_FORWARDED_ALLOW_IPS` is unset uvicorn reports the left-most, client-written entry as the request's client address, so a single proxy should overwrite (for a chain, see (3)).Rate limiting can now derive the client IP from an explicit, admin-declared trusted-proxy hop count instead of only the pre-existing private-peer heuristic. Set `LDR_SERVER_TRUSTED_PROXY_COUNT` to the exact number of `X-Forwarded-For` entries your trusted proxies append (one per appending hop for an ordinary proxy); with `TRUST_PROXY_HEADERS` unset/false and the direct peer private/loopback or listed in a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`, the FastAPI rate limiter then reads the corresponding entry from the *right* end of `X-Forwarded-For` (the address appended by the outermost trusted hop), never the raw first (leftmost) entry — which a client can always forge, even through a real proxy. An `X-Forwarded-For` that is missing or has fewer entries than the configured count, or a direct peer that passes neither check (for example a cloud load balancer on a public address with no allow-list), falls back to the direct socket peer rather than trusting an ambiguous chain; such a public-address proxy must be listed in `LDR_SERVER_FORWARDED_ALLOW_IPS`, or every client behind it shares one rate-limit bucket. The value must be an ASCII decimal integer from 0 to 16. Surrounding whitespace (Unicode whitespace included) is ignored, and `-0` reads as `0`. Anything else (a negative value, `1_0`, `+3`, a non-ASCII digit, an out-of-range hop count) prevents startup instead of failing silently, and an empty or whitespace-only value counts as unset. The setting defaults to `0`, which keeps the pre-existing behaviour of trusting `X-Forwarded-For`/`X-Real-IP` when the direct peer is itself private/loopback (or, once a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS` is set, only when the direct peer is listed there); beyond the forwarding-trust change described above, deployments that do not set the new variable need no further action.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex ce1dbbe4e0..74100ba1c7 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -684,7 +684,7 @@ They are not available in the Web UI because they are needed to start the applic| `security.account_lockout_threshold` | `LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD` | `10` | Number of consecutive failed login attempts before an account is temporarily locked out. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD). | APP || `security.rate_limit_default` | `LDR_SECURITY_RATE_LIMIT_DEFAULT` | `5000 per hour;50000 per day` | Default rate limit for all HTTP endpoints. Configured via LDR_SECURITY_RATE_LIMIT_DEFAULT environment variable. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'. Requires server restart. | APP || `security.rate_limit_login` | `LDR_SECURITY_RATE_LIMIT_LOGIN` | `5 per 15 minutes` | Rate limit for login attempts to prevent brute force attacks. Configured via LDR_SECURITY_RATE_LIMIT_LOGIN environment variable (e.g., '5 per 15 minutes'). Requires server restart. | APP |-| `security.rate_limit_registration` | `LDR_SECURITY_RATE_LIMIT_REGISTRATION` | `3 per hour` | Rate limit for registration attempts to prevent spam. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '3 per hour'). Requires server restart. | APP |+| `security.rate_limit_registration` | `LDR_SECURITY_RATE_LIMIT_REGISTRATION` | `10 per minute;300 per hour` | Rate limit for registration attempts per client IP, including failed attempts. Defaults to 10 per minute and 300 per hour. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '10 per minute;300 per hour'); semicolon-separated limits all apply. Requires server restart. | APP || `security.rate_limit_settings` | `LDR_SECURITY_RATE_LIMIT_SETTINGS` | `30 per minute` | Rate limit for settings modification endpoints. Configured via LDR_SECURITY_RATE_LIMIT_SETTINGS environment variable. Requires server restart. | APP || `security.rate_limit_upload_ip` | `LDR_SECURITY_RATE_LIMIT_UPLOAD_IP` | `60 per minute;1000 per hour` | Per-IP rate limit for file upload endpoints (applies to anonymous and authenticated requests). Configured via LDR_SECURITY_RATE_LIMIT_UPLOAD_IP environment variable. Multiple limits separated by semicolons. Requires server restart. | APP || `security.rate_limit_upload_user` | `LDR_SECURITY_RATE_LIMIT_UPLOAD_USER` | `60 per minute;1000 per hour` | Per-authenticated-user rate limit for file upload endpoints (e.g., RAG collection uploads). Configured via LDR_SECURITY_RATE_LIMIT_UPLOAD_USER environment variable. Multiple limits separated by semicolons (e.g., '60 per minute;1000 per hour'). Requires server restart. | APP |diff --git a/docs/deployment/reverse-proxy.md b/docs/deployment/reverse-proxy.mdindex 617eb6e70b..1d62bfb3bf 100644--- a/docs/deployment/reverse-proxy.md+++ b/docs/deployment/reverse-proxy.md@@ -215,8 +215,9 @@ LDR. In a chain that is the *inner* proxy, and what it writes is the outerhop's address: if it appends, the right-most entry is the outer hop'saddress; if it overwrites with a plain `$remote_addr`, that address is theonly entry. Either way every client is keyed on the outer hop and shares one-rate-limit bucket, so a few failed logins or registrations lock everyone out-of the whole deployment. Setting `LDR_SERVER_FORWARDED_ALLOW_IPS` does not+rate-limit bucket. Repeated login or registration attempts can exhaust that+shared budget and lock everyone out of the whole deployment. Setting+`LDR_SERVER_FORWARDED_ALLOW_IPS` does notchange this while `TRUST_PROXY_HEADERS` is unset: the allow-list only decideswhich direct peers may send forwarded headers, and the right-most entry isstill the key. Pick **one** of the two configurations below.diff --git a/src/local_deep_research/defaults/settings_security.json b/src/local_deep_research/defaults/settings_security.jsonindex 49e9394fc4..30e8bbccd2 100644--- a/src/local_deep_research/defaults/settings_security.json+++ b/src/local_deep_research/defaults/settings_security.json@@ -25,14 +25,14 @@},"security.rate_limit_registration": {"category": "security",- "description": "Rate limit for registration attempts to prevent spam. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '3 per hour'). Requires server restart.",+ "description": "Rate limit for registration attempts per client IP, including failed attempts. Defaults to 10 per minute and 300 per hour. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '10 per minute;300 per hour'); semicolon-separated limits all apply. Requires server restart.","editable": false,"max_value": null,"min_value": null,"name": "Registration Rate Limit","type": "APP","ui_element": "text",- "value": "3 per hour",+ "value": "10 per minute;300 per hour","visible": false},"security.rate_limit_settings": {diff --git a/src/local_deep_research/web/dependencies/rate_limit.py b/src/local_deep_research/web/dependencies/rate_limit.pyindex 7e673d20cc..5f4cdf7372 100644--- a/src/local_deep_research/web/dependencies/rate_limit.py+++ b/src/local_deep_research/web/dependencies/rate_limit.py@@ -1854,7 +1854,9 @@ if _limiter_init_failed:limiter.enabled = _RATE_LIMITING_ENABLEDLOGIN_RATE_LIMIT = _config.get("rate_limit_login", "5 per 15 minutes")-REGISTRATION_RATE_LIMIT = _config.get("rate_limit_registration", "3 per hour")+REGISTRATION_RATE_LIMIT = _config.get(+ "rate_limit_registration", "10 per minute;300 per hour"+)# Use a separate config key for password-change so tightening login limits# doesn't accidentally lock users out of their own settings.PASSWORD_CHANGE_RATE_LIMIT = _config.get(diff --git a/src/local_deep_research/web/server_config.py b/src/local_deep_research/web/server_config.pyindex 93f04d0e13..85e2162e09 100644--- a/src/local_deep_research/web/server_config.py+++ b/src/local_deep_research/web/server_config.py@@ -74,7 +74,7 @@ _DEFAULTS: Dict[str, Any] = {"allow_registrations": True,"rate_limit_default": "5000 per hour;50000 per day","rate_limit_login": "5 per 15 minutes",- "rate_limit_registration": "3 per hour",+ "rate_limit_registration": "10 per minute;300 per hour","rate_limit_settings": "30 per minute","rate_limit_upload_user": "60 per minute;1000 per hour","rate_limit_upload_ip": "60 per minute;1000 per hour",diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 192d7ba56d..b8e723e5da 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -9940,14 +9940,14 @@},"security.rate_limit_registration": {"category": "security",- "description": "Rate limit for registration attempts to prevent spam. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '3 per hour'). Requires server restart.",+ "description": "Rate limit for registration attempts per client IP, including failed attempts. Defaults to 10 per minute and 300 per hour. Configured via LDR_SECURITY_RATE_LIMIT_REGISTRATION environment variable (e.g., '10 per minute;300 per hour'); semicolon-separated limits all apply. Requires server restart.","editable": false,"max_value": null,"min_value": null,"name": "Registration Rate Limit","type": "APP","ui_element": "text",- "value": "3 per hour",+ "value": "10 per minute;300 per hour","visible": false},"security.rate_limit_settings": {diff --git a/tests/settings/test_shipped_defaults_contracts.py b/tests/settings/test_shipped_defaults_contracts.pyindex ae7b92f409..59b8162a92 100644--- a/tests/settings/test_shipped_defaults_contracts.py+++ b/tests/settings/test_shipped_defaults_contracts.py@@ -370,7 +370,7 @@ DOCUMENTED_PERMISSIVE_DEFAULTS: Dict[str, Tuple[Any, str]] = {True,"Initial account creation must work out of the box. Compensating ""controls: the default listen address is loopback (web.host) and "- "registration is rate limited to 3/hour.",+ "registration is rate limited to 10/minute and 300/hour per IP.",),"app.lock_settings": (False,@@ -1022,8 +1022,9 @@ class TestEveryDefaultIsLoadable:RATE_LIMIT_CEILINGS: Dict[str, float] = {# Brute-force surface. 5 attempts / 15 min = 0.34/min."security.rate_limit_login": 0.5,- # Account-spam surface. 3 / hour = 0.05/min.- "security.rate_limit_registration": 0.1,+ # Allow form retries and shared-IP signups, with a short burst cap.+ # The dedicated contract below also requires a <=300/hour window.+ "security.rate_limit_registration": 10.0,# Settings mutation, per authenticated user."security.rate_limit_settings": 30.0,# Upload endpoints, per user and per IP.@@ -1081,7 +1082,26 @@ class TestRateLimitDefaults:f"(key, string, req/min, ceiling): {too_loose}")- def test_login_is_stricter_than_the_global_fallback(self):+ def test_registration_keeps_a_sustained_hourly_cap(self):+ """Allow shared-IP signups and form retries within a bounded hour.++ 300/hour/IP is the deliberate allowance for groups sharing an IP+ and retrying registration forms. Successful and failed submissions+ both count; the separate 10/minute window also bounds bursts.+ """+ raw = raw_defaults()["security.rate_limit_registration"]["value"]+ hourly_limits = [+ item for item in parse_many(raw) if item.get_expiry() == 3600+ ]+ assert hourly_limits, (+ f"registration must retain an explicit hourly window: {raw!r}"+ )+ for item in hourly_limits:+ assert 1 <= item.amount <= 300, (+ f"registration must allow at most 300 attempts per hour: {raw!r}"+ )++ def test_auth_limits_are_stricter_than_the_global_fallback(self):"""The auth endpoints must not be governed by the generic budget.A login limit that merely matches the default limit is the same as@@ -1108,10 +1128,9 @@ class TestRateLimitDefaults:))assert login < fallback / 10- assert register < fallback / 10- assert register < login, (- "registration should be at least as strict as login"- )+ # Registration permits form retries while login retains the+ # stricter budget needed to limit password guessing.+ assert register < fallbackdef test_json_rate_limits_match_the_defaults_the_server_actually_uses(self,diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.jsindex af457d37f1..40d8d7faa6 100644--- a/tests/ui_tests/run_all_tests.js+++ b/tests/ui_tests/run_all_tests.js@@ -548,7 +548,7 @@ const tests = [name: 'Rate Limiting Functionality Test',file: 'test_rate_limiting_settings.js',shard: 'api-crud',- description: 'Tests rate limiting works on auth endpoints and static files are exempt',+ description: 'Tests authentication rate limits and 429 response bodies and headers',// The test file itself no-ops (early `return`, exit 0) unless// ENABLE_RATE_LIMITING=true, because CI always launches the server// with LDR_DISABLE_RATE_LIMITING=true (see docker-tests.yml — everydiff --git a/tests/ui_tests/test_rate_limiting_settings.js b/tests/ui_tests/test_rate_limiting_settings.jsindex 4af0d8dc2f..cc23b28050 100644--- a/tests/ui_tests/test_rate_limiting_settings.js+++ b/tests/ui_tests/test_rate_limiting_settings.js@@ -1,210 +1,107 @@/**- * Rate Limiting Functionality Test+ * Authentication rate-limit check against a fresh server using the shipped+ * defaults, with rate limiting enabled. All submissions fail form validation.*- * Tests that rate limiting is working correctly on authentication endpoints.- * Verifies that requests are blocked after exceeding limits and that proper- * headers are returned.- *- * Prerequisites: Web server running on http://127.0.0.1:5000- *- * Usage: node tests/ui_tests/test_rate_limiting_settings.js+ * Usage: BASE_URL=http://127.0.0.1:5000 node tests/ui_tests/test_rate_limiting_settings.js*/+const assert = require('node:assert/strict');const puppeteer = require('puppeteer');const { getPuppeteerLaunchOptions } = require('./puppeteer_config');-async function testRateLimiting() {- // Skip this test in CI unless ENABLE_RATE_LIMITING=true- // Rate limiting is disabled in CI by default, so this test would fail- if (process.env.CI && process.env.ENABLE_RATE_LIMITING !== 'true') {- console.log('⚠️ Skipping rate limiting test in CI (requires ENABLE_RATE_LIMITING=true)');- console.log('ℹ️ This test needs rate limiting enabled, but CI disables it by default');- return; // Caller awaits but doesn't use return value- }-- const browser = await puppeteer.launch(getPuppeteerLaunchOptions());- const page = await browser.newPage();- const baseUrl = 'http://127.0.0.1:5000';-- try {- console.log('🚀 Starting rate limiting functionality test...');-- // Test 1: Test login rate limiting (5 per 15 minutes)- console.log('\n🔍 Test 1: Login endpoint should be rate limited (5 attempts per 15 min)');-- await page.goto(`${baseUrl}/auth/login`, { waitUntil: 'domcontentloaded' });-- let loginAttempts = 0;- let rateLimitTriggered = false;-- // Make login attempts until rate limited- for (let i = 0; i < 10; i++) {- const response = await page.evaluate(async (url) => {- const res = await fetch(`${url}/api/v1/auth/login`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify({- username: 'testuser_nonexistent',- password: 'wrongpassword' // gitleaks:allow- })- });-- return {- status: res.status,- headers: {- ratelimitLimit: res.headers.get('X-RateLimit-Limit'),- ratelimitRemaining: res.headers.get('X-RateLimit-Remaining'),- ratelimitReset: res.headers.get('X-RateLimit-Reset')- }- };- }, baseUrl);-- loginAttempts++;-- if (response.status === 429) {- console.log(`✅ Rate limit triggered after ${loginAttempts} login attempts`);- console.log(`📊 Rate limit headers:`, response.headers);- rateLimitTriggered = true;- break;- } else {- console.log(`📍 Login attempt ${loginAttempts}: status ${response.status}, remaining: ${response.headers.ratelimitRemaining}`);- }-- // Small delay between requests- await new Promise(resolve => setTimeout(resolve, 100));- }-- if (!rateLimitTriggered) {- console.log('❌ Rate limit was not triggered after 10 login attempts');- throw new Error('Login rate limiting is not working');- }-- if (loginAttempts > 6) {- console.log(`⚠️ Rate limit triggered later than expected (after ${loginAttempts} attempts, expected ~5)`);- }-- // Test 2: Test registration rate limiting (3 per hour)- console.log('\n🔍 Test 2: Registration endpoint should be rate limited (3 attempts per hour)');-- // Use a different page context to reset cookies/session- const page2 = await browser.newPage();- await page2.goto(`${baseUrl}/auth/register`, { waitUntil: 'domcontentloaded' });-- let registrationAttempts = 0;- let regRateLimitTriggered = false;-- // Make registration attempts until rate limited- for (let i = 0; i < 10; i++) {- const response = await page2.evaluate(async (url, attemptNum) => {- const res = await fetch(`${url}/api/v1/auth/register`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify({- username: `testuser_ratelimit_${Date.now()}_${attemptNum}`,- password: 'testpassword123' // gitleaks:allow- })- });-- return {- status: res.status,- headers: {- ratelimitLimit: res.headers.get('X-RateLimit-Limit'),- ratelimitRemaining: res.headers.get('X-RateLimit-Remaining'),- ratelimitReset: res.headers.get('X-RateLimit-Reset')- }- };- }, baseUrl, i);-- registrationAttempts++;-- if (response.status === 429) {- console.log(`✅ Rate limit triggered after ${registrationAttempts} registration attempts`);- console.log(`📊 Rate limit headers:`, response.headers);- regRateLimitTriggered = true;- break;- } else {- console.log(`📍 Registration attempt ${registrationAttempts}: status ${response.status}, remaining: ${response.headers.ratelimitRemaining}`);- }-- // Small delay between requests- await new Promise(resolve => setTimeout(resolve, 100));+async function postAuthForm(page, endpoint, data) {+ return page.evaluate(async (path, formData) => {+ const csrfResponse = await fetch('/auth/csrf-token');+ if (!csrfResponse.ok) {+ throw new Error(`CSRF token request failed: ${csrfResponse.status}`);}-- if (!regRateLimitTriggered) {- console.log('❌ Rate limit was not triggered after 10 registration attempts');- throw new Error('Registration rate limiting is not working');+ const { csrf_token: csrfToken } = await csrfResponse.json();+ if (!csrfToken) {+ throw new Error('CSRF token response is missing its token');}- if (registrationAttempts > 4) {- console.log(`⚠️ Rate limit triggered later than expected (after ${registrationAttempts} attempts, expected ~3)`);- }-- await page2.close();-- // Test 3: Verify 429 error response format- console.log('\n🔍 Test 3: Verify 429 error response format');-- const errorResponse = await page.evaluate(async (url) => {- const res = await fetch(`${url}/api/v1/auth/login`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify({- username: 'testuser',- password: 'testpass' // gitleaks:allow- })- });-- const body = await res.json();- return {- status: res.status,- body- };- }, baseUrl);-- if (errorResponse.status === 429) {- console.log('✅ 429 status code returned correctly');- console.log('📊 Error response body:', errorResponse.body);+ const response = await fetch(path, {+ method: 'POST',+ credentials: 'same-origin',+ redirect: 'manual',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ 'X-CSRFToken': csrfToken+ },+ body: new URLSearchParams(formData).toString()+ });+ return {+ status: response.status,+ headers: {+ limit: response.headers.get('X-RateLimit-Limit'),+ remaining: response.headers.get('X-RateLimit-Remaining'),+ reset: response.headers.get('X-RateLimit-Reset'),+ retryAfter: response.headers.get('Retry-After')+ },+ body: response.status === 429 ? await response.json() : null+ };+ }, endpoint, data);+}- if (errorResponse.body.error && errorResponse.body.message) {- console.log('✅ Error response has correct format (error and message fields)');- } else {- console.log('⚠️ Error response format unexpected:', errorResponse.body);- }- } else {- console.log(`ℹ️ Rate limit may have reset, got status ${errorResponse.status}`);- }+function assertRateLimited(response, limit) {+ assert.equal(response.status, 429, 'Expected a rate-limit response');+ assert.equal(response.headers.limit, String(limit));+ assert.equal(response.headers.remaining, '0');+ assert.match(response.headers.reset, /^\d+(\.\d+)?$/);+ assert.match(response.headers.retryAfter, /^\d+$/);+ assert.equal(response.body.error, 'Too many requests');+ assert.equal(response.body.message, 'Too many attempts. Please try again later.');+}- // Summary- console.log('\n📊 Test Summary:');- console.log(`✅ Login rate limiting (5 per 15 min): PASS (triggered after ${loginAttempts} attempts)`);- console.log(`✅ Registration rate limiting (3 per hour): PASS (triggered after ${registrationAttempts} attempts)`);- console.log(`✅ Error response format: PASS`);+async function exhaustBucket(page, endpoint, data, allowedAttempts) {+ for (let attempt = 1; attempt <= allowedAttempts; attempt++) {+ const response = await postAuthForm(page, endpoint, data);+ assert.equal(response.status, 400,+ `${endpoint}: attempt ${attempt}/${allowedAttempts} must reach form validation`);+ }+ const response = await postAuthForm(page, endpoint, data);+ assertRateLimited(response, allowedAttempts);+ console.log(`${endpoint}: ${allowedAttempts} validation failures allowed; next attempt returned 429`);+}- console.log('\n🎉 Rate limiting functionality test completed successfully');+async function testRateLimiting() {+ // CI servers normally disable limiting; an explicit opt-in is required.+ if (process.env.CI && process.env.ENABLE_RATE_LIMITING !== 'true') {+ console.log('Skipping rate limiting check in CI (requires ENABLE_RATE_LIMITING=true)');+ return;+ }- } catch (error) {- console.error('❌ Error during rate limiting test:', error);- throw error;+ const baseUrl = (process.env.BASE_URL || 'http://127.0.0.1:5000').replace(/\/+$/, '');+ const browser = await puppeteer.launch(getPuppeteerLaunchOptions());+ try {+ const page = await browser.newPage();+ await page.goto(`${baseUrl}/auth/login`, { waitUntil: 'domcontentloaded' });+ const invalidLogin = { username: '', password: '' };+ await exhaustBucket(page, '/auth/login', invalidLogin, 5);++ // Use the same browser and client IP: spending the login quota must+ // leave the independent registration bucket usable.+ await page.goto(`${baseUrl}/auth/register`, { waitUntil: 'domcontentloaded' });+ await exhaustBucket(page, '/auth/register', {+ username: 'x',+ password: '',+ confirm_password: '',+ acknowledge: 'false'+ }, 10);++ // The login bucket must still be exhausted after registration checks.+ assertRateLimited(await postAuthForm(page, '/auth/login', invalidLogin), 5);+ console.log('Authentication rate limits, separate buckets, 429 bodies and headers passed');} finally {await browser.close();}}-// Run the testif (require.main === module) {testRateLimiting()- .then(() => {- console.log('✅ All rate limiting tests completed');- process.exit(0);- })+ .then(() => process.exit(0)).catch(error => {- console.error('❌ Rate limiting tests failed:', error);+ console.error('Rate limiting check failed:', error);process.exit(1);});}diff --git a/tests/web/routers/test_auth_rate_limits.py b/tests/web/routers/test_auth_rate_limits.pyindex 37aebce82e..c9c4bcb9cb 100644--- a/tests/web/routers/test_auth_rate_limits.py+++ b/tests/web/routers/test_auth_rate_limits.py@@ -37,10 +37,15 @@ Enforcement notes:"""import importlib+import os+import timeimport uuid+from contextlib import closing+from types import SimpleNamespaceimport pytestfrom fastapi.testclient import TestClient+from limits.storage import MemoryStoragefrom local_deep_research.web.dependencies.rate_limit import (INTEGRITY_CHECK_RATE_LIMIT,@@ -186,6 +191,50 @@ class TestRegistrationBucket:assert body["error"] == "Too many requests"assert "message" in body+ def test_registration_hourly_cap_survives_minute_resets(+ self, app, monkeypatch+ ):+ """Minute resets permit retries without erasing the hourly cap."""+ if os.environ.get("LDR_SECURITY_RATE_LIMIT_REGISTRATION"):+ pytest.skip("requires the shipped registration limits")+ assert REGISTRATION_RATE_LIMIT == "10 per minute;300 per hour"+ if not isinstance(limiter._storage, MemoryStorage):+ pytest.skip("requires the default in-memory rate-limit storage")++ # Advance only the storage clock, leaving session/CSRF timestamps+ # and the rest of the app on real time. No waiting or user DB writes.+ started = time.time()+ clock = SimpleNamespace(now=started)+ monkeypatch.setattr(+ "limits.storage.memory.time",+ SimpleNamespace(time=lambda: clock.now),+ )+ with closing(_make_client(app, _unique_ip())) as client:+ for _ in range(30):+ for _ in range(10):+ response = client.post(+ "/auth/register",+ data=_BAD_REGISTER,+ follow_redirects=False,+ )+ assert response.status_code == 400+ clock.now += 61++ # The minute bucket has reset, but all 300 accepted attempts+ # still lie within the same hour.+ response = client.post(+ "/auth/register", data=_BAD_REGISTER, follow_redirects=False+ )+ assert response.status_code == 429+ assert response.headers["x-ratelimit-limit"] == "300"+ assert response.headers["x-ratelimit-remaining"] == "0"++ clock.now = started + 3601+ response = client.post(+ "/auth/register", data=_BAD_REGISTER, follow_redirects=False+ )+ assert response.status_code == 400+def test_login_exhaustion_does_not_block_registration(self, app):"""Login and register are separate buckets for the same IP."""_require_small(LOGIN_ATTEMPTS, "login")diff --git a/tests/web/test_rate_limit_census.py b/tests/web/test_rate_limit_census.pyindex 801388a808..6c811028dd 100644--- a/tests/web/test_rate_limit_census.py+++ b/tests/web/test_rate_limit_census.py@@ -144,7 +144,13 @@ UNIFIED = Bucket("unified_search", "_user_key", None, ("60 per 1 minute",))# --- unscoped buckets (limiter.limit(...)); bucket == request URL ---------AUTH_LOGIN = Bucket(PER_URL, "_get_client_ip", None, ("5 per 15 minute",))-AUTH_REGISTER = Bucket(PER_URL, "_get_client_ip", None, ("3 per 1 hour",))+# PR 7329 raised the shipped registration default from 3/hour to a+# dual 10/min + 300/hour budget per client IP (both counting failed+# attempts) so a typo no longer locks the signup form out for an hour;+# premise changed by changelog.d/+registration-rate-limit.bugfix.md.+AUTH_REGISTER = Bucket(+ PER_URL, "_get_client_ip", None, ("10 per 1 minute", "300 per 1 hour")+)AUTH_VALIDATE = Bucket(PER_URL, "_get_client_ip", None, ("30 per 1 minute",))# /auth/integrity-check runs SQLite's full integrity_check scan, so it gets# its own tight per-IP budget rather than sharing a brute-force bucket.diff --git a/tests/web/test_server_config.py b/tests/web/test_server_config.pyindex 32a00d5079..a8edd0c1f8 100644--- a/tests/web/test_server_config.py+++ b/tests/web/test_server_config.py@@ -128,7 +128,10 @@ class TestLoadServerConfig:@pytest.mark.usefixtures("_default_typed_setting")def test_default_rate_limit_registration(self):"""Default rate_limit_registration value."""- assert load_server_config()["rate_limit_registration"] == "3 per hour"+ assert (+ load_server_config()["rate_limit_registration"]+ == "10 per minute;300 per hour"+ )@pytest.mark.usefixtures("_default_typed_setting")def test_default_rate_limit_settings(self):@@ -163,7 +166,7 @@ class TestLoadServerConfig:assert result["allow_registrations"] is Trueassert result["rate_limit_default"] == "5000 per hour;50000 per day"assert result["rate_limit_login"] == "5 per 15 minutes"- assert result["rate_limit_registration"] == "3 per hour"+ assert result["rate_limit_registration"] == "10 per minute;300 per hour"assert result["rate_limit_upload_user"] == "60 per minute;1000 per hour"assert result["rate_limit_upload_ip"] == "60 per minute;1000 per hour"assert result["rate_limit_settings"] == "30 per minute"