Repository navigation
studio: proxy-aware login rate-limit; allow google favicons in CSP - #5489
Conversation
Two follow-ups to #5375's auth + headers hardening. Login rate-limit: The per-IP bucket keyed on request.client.host alone. Behind any reverse proxy or shared NAT it lumps everyone together (one user's typos lock everyone out for 60 seconds; the 429 detail leaked the proxy/internal IP back to clients). The bucket key is now (client-ip, username.lower) so: - one wrong-password run does not block another user from the same IP - one IP does not block the same user from a different IP The 429 detail body no longer interpolates the IP. Behind a proxy clients can set UNSLOTH_STUDIO_TRUST_FORWARDED=1 so the limiter honours X-Forwarded-For / Forwarded; off by default so a direct caller cannot spoof the header. CSP img-src: components/assistant-ui/sources.tsx renders citation favicons from https://www.google.com/s2/favicons. The current img-src allows t0..t3.gstatic.com (used for other Google-hosted icons) but not the main host the favicon URL points to, so every citation icon CSP-blocks and falls back to gray initials. Adding www.google.com to img-src is the same shape as #5409's connect-src HF allowlist fix. Tests: - test_login_rate_limit.py (new): _client_ip respects UNSLOTH_STUDIO_TRUST_FORWARDED for X-Forwarded-For and Forwarded; bucket key is composed of (ip, lower(username)) and isolates cross-user and cross-IP buckets; 429 detail does not contain the client IP; Retry-After header preserved. - test_middleware.py: new test_img_src_allows_google_favicons pins that www.google.com is in the img-src directive and the existing gstatic CDNs stay allowed.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8d21d447fe
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if xff: | ||
| first = xff.split(",", 1)[0].strip() | ||
| if first: | ||
| return first |
There was a problem hiding this comment.
Normalize forwarded IPs before bucketing
When UNSLOTH_STUDIO_TRUST_FORWARDED=1 is used behind a proxy that includes the client port in X-Forwarded-For (for example 203.0.113.5:49152), returning the raw header value makes the login bucket key include the ephemeral port. Reconnecting with a different source port then creates a fresh (ip, username) bucket each time, so the five-failure lockout is not enforced for the same client/user even though the comment says ports are stripped.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request updates the login rate limiting mechanism to be keyed by both IP address and username, rather than just the IP, to improve security and prevent account-specific lockout attacks. It also adds support for honoring X-Forwarded-For headers via an environment variable, updates the Content Security Policy to allow Google favicon sources, and includes comprehensive tests for these changes. I have identified a high-severity issue regarding the robustness of the IP parsing logic in _client_ip and a medium-severity issue regarding an unused constant _LOGIN_LOCKOUT_SECONDS that should be addressed.
|
|
||
|
|
||
| def _record_login_failure(ip: str) -> int: | ||
| def _client_ip(request: Request | None) -> str: | ||
| if request is None: | ||
| return "_unknown" | ||
| if _trust_forwarded_for(): | ||
| # First entry in X-Forwarded-For is the originating client; trim and | ||
| # strip ports / bracketed IPv6. | ||
| xff = request.headers.get("x-forwarded-for", "") | ||
| if xff: | ||
| first = xff.split(",", 1)[0].strip() | ||
| if first: | ||
| return first | ||
| fwd = request.headers.get("forwarded", "") | ||
| if fwd: | ||
| for tok in fwd.split(";"): | ||
| tok = tok.strip() | ||
| if tok.lower().startswith("for="): |
There was a problem hiding this comment.
The _client_ip function has several issues regarding RFC 7239 compliance and robust IPv6/port stripping. Additionally, this type of complex logical check should be centralized into a single helper function and reused across the codebase to ensure consistency and simplify maintenance.
def _client_ip(request: Request | None) -> str:
if request is None:
return "_unknown"
if _trust_forwarded_for():
xff = request.headers.get("x-forwarded-for", "")
if xff:
first = xff.split(",", 1)[0].strip()
if first:
if first.startswith("["):
return first[1:].split("]", 1)[0]
return first.split(":", 1)[0] if first.count(":") == 1 else first
fwd = request.headers.get("forwarded", "")
if fwd:
first_hop = fwd.split(",", 1)[0]
for tok in first_hop.split(";"):
tok = tok.strip()
if tok.lower().startswith("for="):
val = tok[4:].strip('"')
if val.startswith("["):
return val[1:].split("]", 1)[0]
return val.split(":", 1)[0] if val.count(":") == 1 else val
return (request.client.host if request.client else None) or "_unknown"References
- Centralize recurring or complex logical checks (like determining if a host is external) into a single helper function and reuse it across the codebase to ensure consistency and simplify maintenance.
| _LOGIN_BUCKETS_LOCK = threading.Lock() | ||
| _LOGIN_WINDOW_SECONDS = 60.0 | ||
| _LOGIN_MAX_FAILS = 5 | ||
| _LOGIN_LOCKOUT_SECONDS = 60 |
…sentinel
Reviewer follow-ups to the proxy-aware login rate-limit PR.
Forwarded address normalisation: with
UNSLOTH_STUDIO_TRUST_FORWARDED=1, raw `X-Forwarded-For` and
`Forwarded: for=` values such as `198.51.100.7:50001` or
`"[2001:db8::1]:50001"` were carried verbatim into the bucket key,
so one client emitting a fresh source port per attempt split into
many buckets and bypassed _LOGIN_MAX_FAILS. _normalize_forwarded_addr
now strips quotes, optional `[..]:port` for IPv6 and `host:port` for
IPv4, and validates as an IP literal; garbage values fall through to
the direct request.client.host. Forwarded parsing also isolates the
first forwarded-element so a multi-element header cannot create
attacker-controlled bucket strings.
Spray protection: the (ip, username) key removed the aggregate
per-IP throttle the pre-PR limiter provided. A client rotating
nonexistent usernames produced [401, 401, 401, 401, 401, 401] where
pre-PR produced [401, 401, 401, 401, 401, 429]. Restored the
aggregate via a parallel _LOGIN_IP_BUCKETS table (max 30 fails / 60s
per IP) checked alongside the per-(ip, username) bucket; both
buckets must be cleared on a successful login.
Bucket cardinality: every distinct unauthenticated username
allocated a new (ip, username) bucket entry without bound. 1,000
random usernames from one IP produced 1,000 buckets. Failures whose
username does not exist now record into a single sentinel key
(ip, "\x00unknown-user") so cardinality stays at one per IP for the
unknown path. The known-user path additionally enforces a global
hard cap (_LOGIN_MAX_BUCKETS = 4096) that prunes stale empty buckets
on overflow and otherwise folds the failure into the per-IP bucket
only.
Test:
- python -m pytest studio/backend/tests/test_login_rate_limit.py -q
-> 19 passed (was 12 before this commit; +5 forwarded-address
normalisation, +1 sentinel bucket, +1 bucket cap)
CSP comment refreshed to mention `www.google.com` alongside
*.gstatic.com so future readers see why the host is allowlisted.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fc282035eb
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| with _LOGIN_BUCKETS_LOCK: | ||
| _LOGIN_BUCKETS.pop(ip, None) | ||
| _LOGIN_BUCKETS.pop(key, None) | ||
| _LOGIN_IP_BUCKETS.pop(ip, None) |
There was a problem hiding this comment.
Keep IP spray bucket after successful login
Clearing _LOGIN_IP_BUCKETS inside _clear_login_bucket lets any successful login from the same source IP reset the global per-IP failure counter, which bypasses the new spray protection (_LOGIN_IP_MAX_FAILS) added in this commit. In practice, an attacker who knows one valid credential on that IP can alternate successful logins with brute-force attempts and avoid ever hitting the intended IP aggregate throttle.
Useful? React with 👍 / 👎.
The new CSP google-favicon test used 'host string in directive string'
which CodeQL flagged as py/incomplete-url-substring-sanitization
(the substring could appear at an arbitrary position in a URL).
The assertion is checking a CSP directive, not URL sanitisation, but
splitting the directive on whitespace and asserting against the
tokenised source list expresses the same intent and matches the
exact CSP source expression. CodeQL no longer treats it as a URL
substring check.
Test: python -m pytest studio/backend/tests/test_middleware.py -q
-> 14 passed
…/unslothai/unsloth into studio-rate-limit-and-csp-google
CodeQL's py/incomplete-url-substring-sanitization still flagged the
tokenised "host in img_sources" check. Switching to
`any(src == host for src in img_sources)` makes the comparison an
exact-equality (not substring) match, which the rule does not flag.
Test: python -m pytest studio/backend/tests/test_middleware.py -q
-> 14 passed
Compress the 6-line constants header on _LOGIN_BUCKETS to 3 lines and the per-helper docstrings on _trust_forwarded_for / _normalize_forwarded_addr to one line each. Same code, fewer in-flow tutorials. Note in the CSP comment that www.google.com is the active favicon host (used by sources.tsx for s2/favicons citations); *.gstatic.com stays as legacy faviconV2 coverage but the SPA no longer fetches it. 33 tests in test_login_rate_limit.py + test_middleware.py still pass.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1cdcb45fce
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| """Login with username/password. Per-account + per-IP rate-limited.""" | ||
| key = _bucket_key(request, payload.username) | ||
| unknown_key = _unknown_user_key(request) | ||
| blocked_for = max(_login_blocked(key), _login_blocked(unknown_key)) |
There was a problem hiding this comment.
Avoid applying the unknown-user bucket to known users
When any request from an IP has accumulated _LOGIN_MAX_FAILS missing-username failures, this pre-check calls _login_blocked(unknown_key) for every later login attempt from that IP, including a valid username with the correct password. Because the sentinel account bucket uses the 5-attempt per-account limit, a few typoed or sprayed nonexistent usernames lock out all real users behind the same NAT/proxy before the intended _LOGIN_IP_MAX_FAILS aggregate limit is reached.
Useful? React with 👍 / 👎.
Summary
Two follow-ups to #5375 on the auth rate-limiter and CSP headers.
Login rate-limit (proxy-aware, per-(ip, username))
routes/auth.py:_client_keykeyed the bucket onrequest.client.host. Behind any reverse proxy or shared NAT that lumps the whole user base together (127.0.0.1everywhere) so one user's typos block everyone. The 429 body also interpolated the resolved IP back into the detail string.Now:
(client-ip, username.lower()). One user's wrong-password run does not block other users from the same IP; one IP's failures do not block the same user from another IP._LOGIN_MAX_FAILS = 5per (ip, user) over the 60-second window.Retry-Afteris still set.X-Forwarded-For/Forwardedparsing withUNSLOTH_STUDIO_TRUST_FORWARDED=1. Off by default so a direct caller cannot spoof the header.CSP img-src (allow www.google.com)
components/assistant-ui/sources.tsx:68fetches citation favicons fromhttps://www.google.com/s2/favicons?domain=.... The existingimg-srcallowlist coverst0..t3.gstatic.com(used elsewhere) but not the mainwww.google.comhost the favicon URL points to, so every citation icon CSP-blocks and falls back to a gray initial. Same shape as #5409'sconnect-srcHF allowlist fix.Test plan
tests/test_login_rate_limit.py(new): pins_client_ipusesrequest.client.hostby default and ignoresX-Forwarded-ForunlessUNSLOTH_STUDIO_TRUST_FORWARDEDis setX-Forwarded-Forentry wins, andForwarded: for=...is honouredRetry-Afterheader still settests/test_middleware.py::TestSecurityHeadersMiddleware::test_img_src_allows_google_faviconspinswww.google.cominimg-srcand asserts the pre-existingt0..t3.gstatic.comentries remaintest_middleware.py+test_login_rate_limit.py