Skip to content

Add abuse protection to /api/query (closes #168) - #376

Open
SuhrudhC wants to merge 5 commits into
codeforpdx:mainfrom
SuhrudhC:feature-rate-limit-api-query
Open

SuhrudhC wants to merge 5 commits into
codeforpdx:mainfrom
SuhrudhC:feature-rate-limit-api-query

Conversation

@SuhrudhC

Copy link
Copy Markdown

What type of PR is this? (check all applicable)

  • Bug Fix

Description

/api/query is the most expensive thing this app does — every request fans out to Vertex AI RAG plus a Gemini completion. Right now it has no rate limit at all, even though flask_limiter is already set up and used on /api/feedback. Anyone (or any script) can hit it as fast as they want, which is a real cost and availability risk.

This PR wires the existing limiter up to /api/query the same way it's already used on /api/feedback. It defaults to 10 requests per minute per IP, which should be plenty for a normal back-and-forth conversation but stops a script from hammering the endpoint. The limit is also configurable through a QUERY_RATE_LIMIT env var, so it can be tuned in production without a code change if it turns out to be too tight or too loose.

I also wrote a small script (backend/repro_rate_limit.py) that reproduces the bug by bursting both endpoints and comparing results — before the fix /api/query returned 200 for all 20 requests with zero rejections, and after the fix it correctly starts returning 429s past the 10th request.

Related Tickets & Documents

QA Instructions, Screenshots, Recordings

Easiest way to check this locally: send 11+ POST requests to /api/query from the same machine within a minute and confirm the 11th comes back with a 429. You can also just run uv run python backend/repro_rate_limit.py from the backend/ directory — it mocks out the LLM call so it doesn't need real GCP credentials, and prints out a before/after-style comparison of /api/query vs /api/feedback.

Added/updated tests?

  • Yes — two tests added to test_app.py (within-limit returns 200, over-limit returns 429), plus a new file test_query_rate_limit.py with 13 tests covering edge cases: the exact boundary (10th request succeeds, 11th doesn't), that two different IPs get separate quotas, that the window resets properly, that the env var is actually being read, and that /api/query and /api/feedback don't share counters with each other.

Documentation

  • No Architecture.md changes — the rate limiter itself isn't new, just where it's applied, so I didn't think this needed an architecture-level update. Happy to add a note if maintainers feel it's worth documenting.

[optional] Are there any post deployment tasks we need to perform?

Worth double-checking in production that the rate limiter is actually seeing real client IPs and not the IP of whatever proxy sits in front of the app (Digital Ocean). If it's only seeing the proxy's IP, every user would share one bucket. I didn't have access to verify the production networking setup, so flagging this for whoever reviews/deploys.

SuhrudhC and others added 3 commits June 14, 2026 20:27
Add a reproduction script and solution plan for the unprotected
/api/query endpoint. The script bursts both endpoints against the real
app with the LLM and email sender mocked: /api/query returns 200 for all
20 requests (no 429), while /api/feedback is throttled to 3/minute,
confirming the gap.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
/api/query fans out to Vertex AI RAG plus a Gemini completion on every
call. Without a rate limit, scripted traffic is a direct cost and
availability risk. flask_limiter was already wired up but only applied to
/api/feedback.

Wrap the ChatView class-based view with limiter.limit() before
registering the route, defaulting to 10 per minute (tunable via
QUERY_RATE_LIMIT env var without a redeploy). Add two tests mirroring
the existing feedback rate-limit test: one confirming requests within the
budget return 200, one confirming the 11th request returns 429.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Covers six angles to confirm the fix in the previous commit holds:

  Boundary     — exactly 10 requests succeed, the 11th returns 429.
  Per-IP       — two source IPs each get their own independent quota.
  Window reset — limiter.reset() refills the window; traffic resumes.
  Env-var      — QUERY_RATE_LIMIT is read from os.environ at startup.
  Regression   — /api/feedback limit unchanged; the two endpoints have
                  independent counters in both directions.
  Response     — 429 reply has a non-empty HTML error body.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Comment thread SOLUTION_PLAN.md Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did you mean to check this in?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was a personal planning scratch file that got accidentally committed. I just deleted that.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems like this should go in the backend/scripts dir

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved to backend/scripts/ alongside the other utility scripts. Let me know if there's anything else to fix before the pr can get merged.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make sure you pass the code-quality checks. I enabled the github action checks, but you can run these checks locally as well (see the README.md).

- Delete SOLUTION_PLAN.md (internal scratch file, not intended for the repo)
- Move backend/repro_rate_limit.py → backend/scripts/ alongside other utility scripts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@yangm2

yangm2 commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

@claude code-review

@github-actions

This comment was marked as resolved.

@SuhrudhC

SuhrudhC commented Oct 6, 2026

Copy link
Copy Markdown
Author

@yangm2 Addressed the code-quality request in the latest commit: formatted tests/test_query_rate_limit.py and removed its redundant constant import that failed Ruff N811.

Verified locally with the locked dependencies on Python 3.13:

  • ruff format --check: all 57 backend files pass.
  • ruff check and ty check: pass.
  • The CI test selection (not require_repo_secrets) with dummy credentials and mocked services: 430 passed, 1 deselected, 88.84% coverage (80% required).

The update is confined to the test file. Prepared and validated with Codex; the push triggers a fresh upstream check run.

@leekahung

Copy link
Copy Markdown
Contributor

@claude pr-review

@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

No code snapshot is available for this PR. The snapshot job may not have run or may have failed — check the PR checks workflow and re-trigger by commenting @claude once it completes.

@leekahung

Copy link
Copy Markdown
Contributor

@claude pr-review

@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @leekahung's task in 1m 5s —— View job


PR review: Add abuse protection to /api/query

  • Gather context (diff, project CLAUDE.md, /pr guidance)
  • Review app.py limiter wiring and proxy/IP handling
  • Review tests and the repro script
  • Check how the frontend handles a 429
  • Post findings

Rate-limiting /api/query is the right call, and the wiring in app.py matches how /api/feedback is already limited. Thanks for raising the proxy question in the PR body. I checked config/, and that concern turns out to be the main blocker, along with one frontend gap.


🔴 Blocking

1. In production every user shares one bucket. backend/tenantfirstaid/app.py:21, config/tenantfirstaid.conf:39

The limiter keys on get_remote_address, which reads request.remote_addr. In production nginx proxies /api/ to gunicorn over a Unix socket (proxy_pass http://unix:/run/tenantfirstaid.sock:). That means gunicorn never sees a client IP. REMOTE_ADDR comes through empty, and get_remote_address falls back to "127.0.0.1". So every user in the world lands in the same bucket. Once about 10 messages a minute are sent site-wide, everyone gets a 429.

Nginx already sets X-Forwarded-For and X-Real-IP, so the fix is small: trust exactly one proxy hop.

from werkzeug.middleware.proxy_fix import ProxyFix

app = Flask(__name__)
# nginx is the only hop in front of gunicorn (Unix socket), so trust one X-Forwarded-For entry.
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)

Only trust one hop. If the app ever trusts more, clients can spoof their own X-Forwarded-For to dodge the limit. This also fixes /api/feedback, which has the same bug today, but the effect here is much worse because chat is the main feature. Please add a test that sends two different X-Forwarded-For values from the same REMOTE_ADDR and checks that they get separate quotas. The current TestPerIpIsolation tests set REMOTE_ADDR directly, so they can't catch this.

Fix this →

2. A 429 shows up as a chat reply made of raw HTML. frontend/src/hooks/useMessages.tsx:35-41, frontend/src/pages/Chat/utils/streamHelper.ts:61-83

addNewMessage never checks response.ok; it just returns response.body.getReader(). flask_limiter's 429 body is an HTML page. processLines treats any line that isn't JSON as text and appends it to the bot message. So a rate-limited user sees <!doctype html> … <h1>Too Many Requests</h1> … rendered as the assistant's answer. The fix:

  • In addNewMessage, throw (or return a typed error) when !response.ok.
  • In streamHelper, show a friendly message for 429, such as "You're sending messages too quickly. Please wait a minute and try again." The existing catch block already handles the generic case.
  • Optionally, register a JSON @app.errorhandler(429) on the backend so every API client gets a predictable shape.

Fix this →


🟡 Should fix

3. With memory:// storage the limit is per worker, not per IP. app.py:23

Production runs gunicorn -w 10 (config/tenantfirstaid-backend.service:16), and the Docker image runs 2 workers. Each worker process keeps its own in-memory counter, so the real ceiling is roughly 10 × workers per minute per client, depending on how requests spread across workers. It still caps runaway scripts, so it's fine as a first step. Please mention it in the code comment and the PR body, and consider a follow-up to move to shared storage (Redis, or the Valkey that DO manages). Also, "tunable without a redeploy" in the comment isn't quite right: the value is read once at import, so changing it means editing the env and restarting the service.

4. The tests hard-code 10 but read the limit from the environment. tests/test_query_rate_limit.py, tests/test_app.py:87-101

.env is loaded by constants at import time. If a developer sets QUERY_RATE_LIMIT=20 per minute in their local .env, the boundary and 429 tests fail. Either pin the env in a fixture or conftest before tenantfirstaid.app is imported, or parse the limit (limits.parse(QUERY_RATE_LIMIT).amount) and use that number instead of 10/11.

5. The TestEnvVarWiring tests always pass. tests/test_query_rate_limit.py:191-205

Both tests assert QUERY_RATE_LIMIT == os.getenv("QUERY_RATE_LIMIT", "10 per minute"), which is exactly the expression in app.py, so they can't fail. To actually test the wiring, set the env var with monkeypatch, importlib.reload(tenantfirstaid.app) (or build the app in a factory), and check that the new limit fires. Otherwise, delete them.


🟢 Nits

  • Duplicate tests. The two new tests in test_app.py (test_query_within_limit_returns_200, test_query_rate_limiting_returns_429) are covered by TestBoundary. Keep one set.
  • Stale references in the test docstring. Lines 4-11 mention commits ae78a5c and 70185c2, which won't mean anything after a squash merge. It also lists "Retry-After" as point 6 while the test itself says Retry-After isn't emitted. Please trim it.
  • scripts/repro_rate_limit.py is out of date now that the fix is in. Its docstring and output describe the bug as present, and it now prints "bug NOT reproduced". It also uses return_value=iter(...), so the shared iterator is used up after the first call. The pytest suite already covers this, so I'd drop the script rather than keep it in backend/scripts/. If you keep it, rename it and turn it into a "verify limit" check.
  • Response headers. Consider Limiter(..., headers_enabled=True) so clients get Retry-After and X-RateLimit-*. The frontend could then tell the user how long to wait.
  • Docs. /pr guidance asks that env vars stay consistent across .env.example, deployment, and docs. Please add QUERY_RATE_LIMIT (and the 10/min default) to Deployment.md's env var section, and add a line to Architecture.md's /api/query description noting that it's rate-limited.

Summary

The backend change is small and correct as far as it goes. Before merging, please fix #1: as deployed today, the limit would apply to the whole site instead of per user and would lock out real users almost immediately. Please also fix #2 so a 429 doesn't show raw HTML in the chat. #3–#5 can go in this PR or a follow-up.

I didn't run the test suite in this job. This was a read-only review of the diff, the nginx/gunicorn config, and the frontend stream handling.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add abuse protection (rate limiting) to /api/query

3 participants