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.

harden(api): warn once per invalid app.api_rate_limit value and bound the scan (#6558)

Sebastian Caocc8421406d35
diff --git a/changelog.d/6558.bugfix.md b/changelog.d/6558.bugfix.md
new file mode 100644
index 0000000000..b2b816ee21
--- /dev/null
+++ b/changelog.d/6558.bugfix.md
@@ -0,0 +1,6 @@
+An invalid `app.api_rate_limit` value (the setting has no schema entry, so
+anything can be stored) is now warned about once per distinct value per
+process instead of on every `/api/v1` request, with repeats logged at debug.
+Only a string of at most 32 characters made of ASCII digits is read as a
+number, so an oversized or non-ASCII digit string falls back to the default
+without being scanned or echoed whole.
diff --git a/src/local_deep_research/web/dependencies/rate_limit.py b/src/local_deep_research/web/dependencies/rate_limit.py
index 1085de151d..0a7f231cd5 100644
--- a/src/local_deep_research/web/dependencies/rate_limit.py
+++ b/src/local_deep_research/web/dependencies/rate_limit.py
@@ -12,6 +12,7 @@ import re
from collections.abc import Callable
from contextvars import ContextVar
from functools import wraps
+from typing import Any
from limits.errors import ConfigurationError
from loguru import logger
@@ -479,6 +480,17 @@ API_RATE_LIMIT_DEFAULT = 60 # requests per minute
# How much of an invalid app.api_rate_limit value the warning echoes.
_INVALID_VALUE_LOG_CHARS = 60
+# Longest string still read as a number. A rate limit is a dozen digits at
+# most, and the value is client-writable and re-read on every request, so
+# anything longer is not scanned at all and is treated as invalid.
+_NUMERIC_VALUE_MAX_CHARS = 32
+
+# Invalid values already warned about, by their truncated echo, so a stored
+# bad value warns once per process rather than on every request (repeats
+# log at debug). Bounded; once full, new values keep warning every time.
+_WARNED_INVALID_VALUES_MAX = 256
+_warned_invalid_values: set[str] = set()
+
# Cached at call time by the api_v1 router's require_api_access dependency
# (which already reads the user's settings for the app.enable_api gate).
# ContextVar keeps it request-scoped under asyncio. Consumed by the
@@ -493,42 +505,61 @@ def set_request_api_rate_limit(value: object) -> None:
"""Cache the authenticated user's app.api_rate_limit for this request.
Only 0 (the kill switch) and positive ints are cached as given. A
- string of decimal digits (surrounding whitespace allowed) is cached as
+ string of ASCII digits (surrounding whitespace allowed) is cached as
the int it spells: app.api_rate_limit has no defaults-JSON entry, so
an env override (LDR_APP_API_RATE_LIMIT=120) or a text-typed settings
row reaches here as the raw string "120", which main's Flask code
- honoured ("0" therefore disables the limit just as 0 does). The
- default is cached in place of anything else, with a
+ honoured ("0" therefore disables the limit just as 0 does). ASCII
+ only: str.isdecimal() also passes other scripts' digits, which int()
+ converts, but a number typed into an env var or a text column is
+ [0-9], so anything else is refused rather than quietly honoured. A
+ string longer than _NUMERIC_VALUE_MAX_CHARS is not scanned or
+ converted at all: no rate limit is that long, and this runs on every
+ request. The default is cached in place of anything else, with a
warning naming the value, because nothing validates the setting
upstream and a negative, fractional, boolean or non-numeric value can
arrive here. Cached as-is, such a value would count as "custom": the
static limit steps aside, and slowapi, unable to parse the limit
string built from it, logs an error and skips the dynamic limit -
- leaving the user with no limit at all.
+ leaving the user with no limit at all. A stored invalid value comes
+ back on every request, so the warning is emitted once per distinct
+ value per process (bounded, see _WARNED_INVALID_VALUES_MAX) and
+ repeats are logged at debug.
"""
- if isinstance(value, str) and value.strip().isdecimal():
- try:
- value = int(value.strip())
- except ValueError:
- # Past the interpreter's int() digit limit (4300 by default).
- # A string that long is not a rate limit, and the ValueError
- # must not escape as a 500; left as-is for the check below.
- pass
+ if isinstance(value, str) and len(value) <= _NUMERIC_VALUE_MAX_CHARS:
+ stripped = value.strip()
+ if stripped.isascii() and stripped.isdigit():
+ value = int(stripped)
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
# The app.* namespace is client-writable, so the echoed value is
- # capped rather than logged whole.
- shown = repr(value)
+ # capped rather than logged whole, and a string is cut BEFORE repr
+ # so a multi-MB value is never copied whole just to echo its head.
+ if isinstance(value, str):
+ shown = repr(value[:_INVALID_VALUE_LOG_CHARS])
+ else:
+ shown = repr(value)
if len(shown) > _INVALID_VALUE_LOG_CHARS:
shown = shown[:_INVALID_VALUE_LOG_CHARS] + "..."
- logger.warning(
+ message = (
f"Ignoring invalid app.api_rate_limit {shown}: expected 0 "
"(disabled) or a positive integer; applying the default of "
f"{API_RATE_LIMIT_DEFAULT} per minute"
)
+ if shown in _warned_invalid_values:
+ logger.debug(message)
+ else:
+ if len(_warned_invalid_values) < _WARNED_INVALID_VALUES_MAX:
+ _warned_invalid_values.add(shown)
+ logger.warning(message)
value = API_RATE_LIMIT_DEFAULT
_api_rate_limit_ctx.set(value)
+def _reset_invalid_value_warnings() -> None:
+ """Forget which invalid values have been warned about (for tests)."""
+ _warned_invalid_values.clear()
+
+
def _api_user_key(request: Request) -> str:
username = (
request.session.get("username") if "session" in request.scope else None
@@ -594,7 +625,7 @@ _api_custom_rate_limit = limiter.shared_limit(
)
-def api_rate_limit(func):
+def api_rate_limit(func: Callable[..., Any]) -> Callable[..., Any]:
"""Apply the static-default + dynamic-custom limit pair to a route.
The second decorator call is for its registration side effect only and
diff --git a/tests/web/test_rate_limit_census.py b/tests/web/test_rate_limit_census.py
index e5038082be..ec82f4fcd0 100644
--- a/tests/web/test_rate_limit_census.py
+++ b/tests/web/test_rate_limit_census.py
@@ -58,7 +58,10 @@ from local_deep_research.web.fastapi_app import app
from local_deep_research.web.dependencies.rate_limit import (
API_RATE_LIMIT_DEFAULT,
DEFAULT_RATE_LIMIT,
+ _INVALID_VALUE_LOG_CHARS,
+ _NUMERIC_VALUE_MAX_CHARS,
_api_rate_limit_ctx,
+ _reset_invalid_value_warnings,
limiter,
set_request_api_rate_limit,
)
@@ -394,6 +397,16 @@ def check(monkeypatch):
return _check
[email protected](autouse=True)
+def _fresh_invalid_value_warnings():
+ """``set_request_api_rate_limit`` warns once per invalid value per
+ process. The same literals recur across parametrizations here and in
+ the HTTP contract tests, so each test starts with nothing warned yet."""
+ _reset_invalid_value_warnings()
+ yield
+ _reset_invalid_value_warnings()
+
+
class TestCensusIsComplete:
"""The table above must describe the assembled app exactly."""
@@ -626,8 +639,8 @@ class TestSharedBucketsAreEnforced:
@pytest.mark.parametrize(
"raw,limit",
- [("120", 120), (" 2 ", 2)],
- ids=["env-override-string", "padded-string"],
+ [("120", 120), (" 2 ", 2), ("2".rjust(_NUMERIC_VALUE_MAX_CHARS), 2)],
+ ids=["env-override-string", "padded-string", "padded-to-the-bound"],
)
def test_api_v1_numeric_strings_are_honoured(
self, check, loguru_caplog, raw, limit
@@ -636,7 +649,9 @@ class TestSharedBucketsAreEnforced:
override (``LDR_APP_API_RATE_LIMIT=120``) or a text-typed settings
row reaches ``set_request_api_rate_limit`` as the raw string. Main
honoured it (``f"{value} per minute"``), so the string is cached as
- the int it spells and enforced at THAT value, with no warning."""
+ the int it spells and enforced at THAT value, with no warning. The
+ length bound on that conversion is inclusive: a string padded out
+ to exactly ``_NUMERIC_VALUE_MAX_CHARS`` is still read."""
user = _unique_user("apiv1-str")
ip = _unique_ip()
@@ -667,18 +682,45 @@ class TestSharedBucketsAreEnforced:
@pytest.mark.parametrize(
"bad_value",
- [-5, 2.5, "abc", "12a", None],
- ids=["negative", "fractional", "non-numeric", "mixed-string", "none"],
+ [
+ -5,
+ 2.5,
+ "abc",
+ "12a",
+ None,
+ True,
+ False,
+ "1" * (_NUMERIC_VALUE_MAX_CHARS + 1),
+ "\u0661\u0662\u0660",
+ ],
+ ids=[
+ "negative",
+ "fractional",
+ "non-numeric",
+ "mixed-string",
+ "none",
+ "true",
+ "false",
+ "digits-over-length-bound",
+ "non-ascii-digits",
+ ],
)
def test_api_v1_invalid_values_fall_back_to_the_default(
self, check, loguru_caplog, bad_value
):
"""``app.api_rate_limit`` has no settings-schema entry, so a
- negative, fractional, non-numeric or null value can reach
+ negative, fractional, non-numeric, null or boolean value can reach
``set_request_api_rate_limit``. It must be logged and the user held
at the static default, NOT treated as a custom value: that would
exempt the static limit and hand the dynamic one a limit string
- slowapi cannot parse, which it logs and skips - no limit at all."""
+ slowapi cannot parse, which it logs and skips - no limit at all.
+ ``False`` is the sneaky one (an ``int`` equal to 0): taken at face
+ value it would engage the kill switch. A digit string past
+ ``_NUMERIC_VALUE_MAX_CHARS`` is refused too, even though ``int()``
+ could convert it: the length bound runs before the digit scan. So
+ are the Arabic-Indic digits for 120: ``str.isdecimal()`` passes
+ them and ``int()`` reads them, but the setting is a number typed
+ into an env var or a text column, so only ASCII digits count."""
user = _unique_user("apiv1-bad")
ip = _unique_ip()
@@ -708,15 +750,19 @@ class TestSharedBucketsAreEnforced:
assert f"invalid app.api_rate_limit {bad_value!r}" in loguru_caplog.text
@pytest.mark.parametrize(
- "huge", ["x" * 4096, "9" * 5000], ids=["text", "digits"]
+ "huge",
+ ["x" * 4096, "9" * 5000, "9" * 80 + "x"],
+ ids=["text", "digits", "mixed"],
)
def test_api_v1_invalid_value_warning_is_bounded(self, loguru_caplog, huge):
"""The ``app.*`` namespace is client-writable, so the warning must
- not echo a multi-KB value whole: ``repr`` is cut at 60 characters
- and the default is still what gets cached. The digit string is
- also past ``int()``'s 4300-digit conversion limit, so it must be
- refused like any other garbage rather than raise out of the
- request."""
+ not echo a multi-KB value whole: ``repr`` is cut at
+ ``_INVALID_VALUE_LOG_CHARS`` characters and the default is still
+ what gets cached. The digit string is also past ``int()``'s
+ 4300-digit conversion limit, so it must be refused like any other
+ garbage rather than raise out of the request. All three are past
+ ``_NUMERIC_VALUE_MAX_CHARS`` as well, so none of them is scanned
+ for digits before being refused."""
token = _api_rate_limit_ctx.set(API_RATE_LIMIT_DEFAULT)
try:
set_request_api_rate_limit(huge)
@@ -724,11 +770,60 @@ class TestSharedBucketsAreEnforced:
finally:
_api_rate_limit_ctx.reset(token)
- assert "invalid app.api_rate_limit '" + huge[:59] + "..." in (
- loguru_caplog.text
- )
+ echo = repr(huge)[:_INVALID_VALUE_LOG_CHARS] + "..."
+ assert f"invalid app.api_rate_limit {echo}" in loguru_caplog.text
assert huge not in loguru_caplog.text
+ def test_api_v1_invalid_value_is_sliced_before_repr(self, loguru_caplog):
+ """The cut above has to happen BEFORE ``repr``: a multi-MB stored
+ value would otherwise be copied in full on every request just to
+ show the head of it. A ``str`` subclass that records the lengths
+ ``repr`` is asked for is the probe: slicing hands ``repr`` a plain
+ ``str`` of at most ``_INVALID_VALUE_LOG_CHARS`` characters, so the
+ recorder never sees the whole value."""
+ seen = []
+
+ class Recorded(str):
+ def __repr__(self):
+ seen.append(len(self))
+ return super().__repr__()
+
+ huge = Recorded("x" * 4096)
+ token = _api_rate_limit_ctx.set(API_RATE_LIMIT_DEFAULT)
+ try:
+ set_request_api_rate_limit(huge)
+ assert _api_rate_limit_ctx.get() == API_RATE_LIMIT_DEFAULT
+ finally:
+ _api_rate_limit_ctx.reset(token)
+
+ assert all(n <= _INVALID_VALUE_LOG_CHARS for n in seen), seen
+ echo = repr("x" * 4096)[:_INVALID_VALUE_LOG_CHARS] + "..."
+ assert f"invalid app.api_rate_limit {echo}" in loguru_caplog.text
+ assert "x" * 4096 not in loguru_caplog.text
+
+ def test_api_v1_invalid_value_warns_once_per_value(self, loguru_caplog):
+ """A stored invalid value is re-read on every request, so the
+ warning fires once per distinct value per process: a repeat of the
+ same value is logged at debug, a different value warns again, and
+ the default is cached every time regardless."""
+ token = _api_rate_limit_ctx.set(API_RATE_LIMIT_DEFAULT)
+ try:
+ for value in ("abc", "abc", "12a"):
+ set_request_api_rate_limit(value)
+ assert _api_rate_limit_ctx.get() == API_RATE_LIMIT_DEFAULT
+ finally:
+ _api_rate_limit_ctx.reset(token)
+
+ logged = [
+ (record.levelname, record.getMessage())
+ for record in loguru_caplog.records
+ if "invalid app.api_rate_limit" in record.getMessage()
+ ]
+ assert [level for level, _ in logged] == ["WARNING", "DEBUG", "WARNING"]
+ assert "invalid app.api_rate_limit 'abc'" in logged[0][1]
+ assert "invalid app.api_rate_limit 'abc'" in logged[1][1]
+ assert "invalid app.api_rate_limit '12a'" in logged[2][1]
+
@pytest.mark.parametrize("zero", [0, "0"], ids=["int", "numeric-string"])
def test_api_v1_zero_still_disables_the_limit(self, check, zero):
"""The kill switch survives the validation above: ``0`` is cached