-
Notifications
You must be signed in to change notification settings - Fork 21
Add abuse protection to /api/query (closes #168) #376
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SuhrudhC
wants to merge
4
commits into
codeforpdx:main
Choose a base branch
from
SuhrudhC:feature-rate-limit-api-query
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ae78a5c
Reproduce missing rate limit on /api/query
SuhrudhC 70185c2
Apply per-IP rate limit to /api/query endpoint
SuhrudhC 266b541
Add comprehensive rate-limit verification tests for /api/query
SuhrudhC f5d9f02
Address PR review: remove planning scratch file, relocate repro script
SuhrudhC File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| """Reproduction: /api/query has NO rate limit, while /api/feedback does. | ||
|
|
||
| Uses the real Flask app from tenantfirstaid.app with the LLM chat manager and | ||
| the email sender mocked out, so no external calls are made. We fire a burst of | ||
| requests at each endpoint and report the status codes. | ||
|
|
||
| Expected (buggy) behavior: | ||
| - /api/query : 20/20 requests return 200, ZERO 429s -> unthrottled, cost risk | ||
| - /api/feedback: first 3 return 200, the rest return 429 -> throttled | ||
| """ | ||
|
|
||
| from collections import Counter | ||
| from unittest.mock import patch | ||
|
|
||
| from tenantfirstaid.app import app, limiter | ||
|
|
||
|
|
||
| def fire_query(client, n): | ||
| """Send n POSTs to /api/query with a mocked chat manager.""" | ||
| codes = [] | ||
| with patch("tenantfirstaid.chat.LangChainChatManager") as mock_cm: | ||
| mock_cm.return_value.generate_streaming_response.return_value = iter( | ||
| [{"type": "text", "text": "mocked legal advice"}] | ||
| ) | ||
| for _ in range(n): | ||
| resp = client.post( | ||
| "/api/query", | ||
| json={ | ||
| "messages": [{"role": "human", "content": "hi"}], | ||
| "city": None, | ||
| "state": "or", | ||
| }, | ||
| ) | ||
| # Drain the streaming body so the request fully completes. | ||
| resp.get_data() | ||
| codes.append(resp.status_code) | ||
| return Counter(codes) | ||
|
|
||
|
|
||
| def fire_feedback(client, n): | ||
| """Send n POSTs to /api/feedback with a mocked email sender.""" | ||
| codes = [] | ||
| with ( | ||
| patch("tenantfirstaid.feedback.EmailMessage"), | ||
| patch.dict( | ||
| "os.environ", {"SENDER_EMAIL": "s@t.com", "RECIPIENT_EMAIL": "r@t.com"} | ||
| ), | ||
| ): | ||
| for _ in range(n): | ||
| resp = client.post( | ||
| "/api/feedback", | ||
| data={"name": "Jane", "subject": "Bug", "feedback": "Broken"}, | ||
| ) | ||
| codes.append(resp.status_code) | ||
| return Counter(codes) | ||
|
|
||
|
|
||
| def run_trial(trial_no, burst=20): | ||
| app.testing = True | ||
| limiter.reset() # start each trial with a clean rate-limit window | ||
| client = app.test_client() | ||
|
|
||
| query_codes = fire_query(client, burst) | ||
| limiter.reset() | ||
| feedback_codes = fire_feedback(client, 5) | ||
|
|
||
| print(f"\n===== TRIAL {trial_no} =====") | ||
| print(f"/api/query x{burst:<3} -> {dict(query_codes)}") | ||
| print( | ||
| f" 429s on /api/query: {query_codes.get(429, 0)} " | ||
| f"(0 == UNPROTECTED, bug reproduced)" | ||
| ) | ||
| print(f"/api/feedback x5 -> {dict(feedback_codes)}") | ||
| print( | ||
| f" 429s on /api/feedback: {feedback_codes.get(429, 0)} " | ||
| f"(>0 == limiter works here)" | ||
| ) | ||
|
|
||
| bug_present = query_codes.get(429, 0) == 0 and feedback_codes.get(429, 0) > 0 | ||
| print(f" RESULT: bug {'REPRODUCED' if bug_present else 'NOT reproduced'}") | ||
| return bug_present | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| results = [run_trial(i) for i in (1, 2)] | ||
| print("\n========================================") | ||
| print(f"Bug reproduced in {sum(results)}/{len(results)} trials.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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/scriptsdirThere was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).