Repository navigation
fix: IP blocklist + global rate limit 120/min - #28
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughAdds an Azure Table–backed IP blocklist (checked by middleware and ChangesCheck Endpoint Security and Rate Limiting
Packaging metadata cleanup
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
api/main.py (2)
150-154:⚠️ Potential issue | 🔴 CriticalFix import-time crash in
/v1/feedbackrate limiter: missing_rate_limit_exempt_non_pro
api/main.py:409usesexempt_when=_rate_limit_exempt_non_proon the@limiter.limit(...)decorator, but_rate_limit_exempt_non_prois not defined or imported anywhere in the repository; this will raiseNameErrorwhen the module is imported (decorators are evaluated at import time). Restore the helper (or update/removeexempt_whento reference an existing symbol).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/main.py` around lines 150 - 154, The NameError occurs because the decorator on the /v1/feedback endpoint uses exempt_when=_rate_limit_exempt_non_pro but that symbol is missing; restore the helper or point exempt_when at an existing predicate. Add (or import) a function named _rate_limit_exempt_non_pro(request: Request) -> bool that returns True for requests that should bypass limits (e.g., internal keys or pro users), or update the `@limiter.limit`(...) call to use an existing predicate such as _is_internal_key (or remove the exempt_when argument) so the decorator references a defined symbol.
150-154:⚠️ Potential issue | 🔴 CriticalFix rate-limit contract mismatch (internal not exempt)
api/main.pyget_rate_limit_key()routes internal keys to"internal-unlimited"(150-154), but/v1/checkapplies@limiter.limit("120/minute", key_func=get_rate_limit_key)so internal traffic is still throttled to 120/min (271-273).README.mddocuments “Internal (unlimited) / Pro (60/min) / Free (10/min)” (287-289), but/v1/checkonly distinguishes internal vs global—no Pro/Free tiering.api/main.pyreferences_rate_limit_exempt_non_proin the/v1/feedbackdecorator (exempt_when=...) without any definition in the repo (409), which will break module import when decorators are evaluated.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/main.py` around lines 150 - 154, get_rate_limit_key currently only returns "internal-unlimited" or "global", causing internal traffic to still hit the 120/min limiter and not supporting Pro/Free tiers; also a missing symbol _rate_limit_exempt_non_pro is referenced by the /v1/feedback decorator and will break import. Fix by expanding get_rate_limit_key (use _resolve_api_key and _is_internal_key) to return distinct keys for internal (e.g., "internal-unlimited"), pro (e.g., "tier-pro:<api_key_or_id>"), and free (e.g., "tier-free:<api_key_or_id>") based on the API key’s tier information (add or call a helper that maps API keys to tiers), and update the `@limiter.limit` on /v1/check to use appropriate per-tier rates (or keep strings but ensure key_func returns tiered keys). Also add a definition for _rate_limit_exempt_non_pro (a predicate that returns True for internal or pro keys and False for free) and reference that function in the /v1/feedback decorator so the decorator evaluation no longer fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/main.py`:
- Around line 274-280: The check for blocked IPs currently runs inside
check_prompt after the Security(verify_api_key) dependency, so verify_api_key
returns 401 before blocked IPs can produce a 403; to fix, enforce is_ip_blocked
earlier by moving the IP block logic into a middleware or a dedicated FastAPI
dependency that executes before verify_api_key (e.g., create a pre-request
middleware or a dependency like verify_ip_blocklist used in the route
dependencies or globally), call get_remote_address and log_to_azure("BLOCK",
...) there, and raise HTTPException(status_code=403) from that
middleware/dependency so blocked IPs are rejected and audited before
verify_api_key runs; keep verify_api_key and check_prompt unchanged except to
remove the in-handler is_ip_blocked check.
- Around line 51-64: The is_ip_blocked function currently swallows all
exceptions; change its exception handling so the call to
table.get_entity(partition_key="blocked", row_key=ip) specifically catches
ResourceNotFoundError and returns False (row not present), while catching other
Azure errors separately (e.g. from azure.core.exceptions import AzureError or
catch Exception as e scoped to Azure calls) to log an error (include the
exception details) and still return False to preserve fail-open behavior; ensure
ResourceNotFoundError is used and remove any unused imports and keep the
logger.warning when an IP is found and blocked.
---
Outside diff comments:
In `@api/main.py`:
- Around line 150-154: The NameError occurs because the decorator on the
/v1/feedback endpoint uses exempt_when=_rate_limit_exempt_non_pro but that
symbol is missing; restore the helper or point exempt_when at an existing
predicate. Add (or import) a function named _rate_limit_exempt_non_pro(request:
Request) -> bool that returns True for requests that should bypass limits (e.g.,
internal keys or pro users), or update the `@limiter.limit`(...) call to use an
existing predicate such as _is_internal_key (or remove the exempt_when argument)
so the decorator references a defined symbol.
- Around line 150-154: get_rate_limit_key currently only returns
"internal-unlimited" or "global", causing internal traffic to still hit the
120/min limiter and not supporting Pro/Free tiers; also a missing symbol
_rate_limit_exempt_non_pro is referenced by the /v1/feedback decorator and will
break import. Fix by expanding get_rate_limit_key (use _resolve_api_key and
_is_internal_key) to return distinct keys for internal (e.g.,
"internal-unlimited"), pro (e.g., "tier-pro:<api_key_or_id>"), and free (e.g.,
"tier-free:<api_key_or_id>") based on the API key’s tier information (add or
call a helper that maps API keys to tiers), and update the `@limiter.limit` on
/v1/check to use appropriate per-tier rates (or keep strings but ensure key_func
returns tiered keys). Also add a definition for _rate_limit_exempt_non_pro (a
predicate that returns True for internal or pro keys and False for free) and
reference that function in the /v1/feedback decorator so the decorator
evaluation no longer fails.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 11519c3f-0b36-46db-bc8f-bb103c59e5a5
⛔ Files ignored due to path filters (2)
dist/agent_shield_int-1.0.0-py3-none-any.whlis excluded by!**/dist/**dist/agent_shield_int-1.0.0.tar.gzis excluded by!**/dist/**,!**/*.gz
📒 Files selected for processing (11)
agent_shield.egg-info/PKG-INFOagent_shield.egg-info/SOURCES.txtagent_shield.egg-info/dependency_links.txtagent_shield.egg-info/entry_points.txtagent_shield.egg-info/top_level.txtagent_shield_int.egg-info/PKG-INFOagent_shield_int.egg-info/SOURCES.txtagent_shield_int.egg-info/dependency_links.txtagent_shield_int.egg-info/entry_points.txtagent_shield_int.egg-info/top_level.txtapi/main.py
💤 Files with no reviewable changes (10)
- agent_shield.egg-info/dependency_links.txt
- agent_shield_int.egg-info/dependency_links.txt
- agent_shield.egg-info/PKG-INFO
- agent_shield_int.egg-info/top_level.txt
- agent_shield_int.egg-info/SOURCES.txt
- agent_shield.egg-info/entry_points.txt
- agent_shield.egg-info/top_level.txt
- agent_shield.egg-info/SOURCES.txt
- agent_shield_int.egg-info/PKG-INFO
- agent_shield_int.egg-info/entry_points.txt
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
api/main.py (2)
288-290: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick winRedundant IP blocklist check—middleware already handles this.
The new
ip_blocklist_middleware(lines 170-176) now blocks IPs before the request reaches this handler. Thisis_ip_blocked(client_ip)check is unreachable for blocked IPs and causes an unnecessary Azure Table lookup for every allowed request. The middleware also addresses the prior review concern about auth running before the IP block.♻️ Remove dead code
async def check_prompt(request: Request, req: CheckRequest, api_key: str = Security(verify_api_key)): start_time = time.time() target_payload = req.prompt client_ip = get_remote_address(request) or "unknown" - if is_ip_blocked(client_ip): - log_to_azure(target_payload, "BLOCK", 0.99, "IP_BLOCKLIST", 0.0, client_ip) - raise HTTPException(status_code=403, detail="Access denied") try:🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/main.py` around lines 288 - 290, The if-block calling is_ip_blocked(client_ip) and log_to_azure(...) in the request handler is now redundant because ip_blocklist_middleware performs IP blocking earlier; remove the entire conditional (the is_ip_blocked check and its log_to_azure call and raise HTTPException) from the handler so you avoid the extra Azure Table lookup on every request and let the middleware handle blocking and logging consistently.
281-282:⚠️ Potential issue | 🟠 MajorRate limit change breaks the rate-limit tests and makes non-internal traffic share one bucket
api/main.pysets@limiter.limit("120/minute", key_func=get_rate_limit_key)onPOST /v1/check, buttests/test_rate_limit.pyasserts the 11th request should be blocked with HTTP 429 after 10 successful requests.get_rate_limit_key()returns"global"for all non-internal API keys (only internal keys get"internal-unlimited"), so all non-internal users share the same 120/min quota.- README claims tiered limits (Free 10/min, Pro 60/min), which no longer matches the hardcoded 120/min behavior.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/main.py` around lines 281 - 282, The POST /v1/check route uses a hardcoded "`@limiter.limit`('120/min', key_func=get_rate_limit_key)" which conflicts with tests/test_rate_limit.py and README tiering because get_rate_limit_key returns "global" for non-internal keys (causing a shared bucket) and the 120/min value ignores Free/Pro tiers; fix by making rate-limiting dynamic: change the limiter.limit usage on the POST /v1/check route to call a function that returns the correct rate string per-request based on the key's tier (e.g., "10/min" for Free, "60/min" for Pro, "unlimited" or internal for internal keys), and/or update get_rate_limit_key so it returns a per-api-key identifier (not the literal "global") so each non-internal key has its own bucket; ensure behavior matches tests/test_rate_limit.py and README tier names.
🧹 Nitpick comments (1)
api/main.py (1)
65-67: ⚡ Quick winUse
logging.exception()to capture full traceback.The fail-open behavior is correct, but
logger.error()only logs the exception message. Usinglogger.exception()will include the full stack trace, which is valuable for diagnosing Azure connectivity issues or unexpected failures.♻️ Suggested improvement
except Exception as e: - logger.error(f"IP blocklist check failed — fail open: {e}") + logger.exception("IP blocklist check failed — fail open") return False🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/main.py` around lines 65 - 67, The except block currently calls logger.error(f"IP blocklist check failed — fail open: {e}") which only logs the message; replace this with logger.exception("IP blocklist check failed — fail open") inside the same except Exception as e block so the full traceback is recorded while preserving the fail-open return False behavior (locate the except block that references logger.error in api/main.py).Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/main.py`:
- Around line 170-176: The middleware ip_blocklist_middleware may raise
AttributeError when accessing request.client.host because request.client can be
None; change the client IP extraction to safely handle that by first checking
X-Forwarded-For, then using request.client.host only if request.client is not
None (e.g., via getattr(request, "client", None) and checking .host or using a
try/except), defaulting to "unknown" otherwise; keep the is_ip_blocked call,
logger.warning and JSONResponse behavior unchanged.
---
Outside diff comments:
In `@api/main.py`:
- Around line 288-290: The if-block calling is_ip_blocked(client_ip) and
log_to_azure(...) in the request handler is now redundant because
ip_blocklist_middleware performs IP blocking earlier; remove the entire
conditional (the is_ip_blocked check and its log_to_azure call and raise
HTTPException) from the handler so you avoid the extra Azure Table lookup on
every request and let the middleware handle blocking and logging consistently.
- Around line 281-282: The POST /v1/check route uses a hardcoded
"`@limiter.limit`('120/min', key_func=get_rate_limit_key)" which conflicts with
tests/test_rate_limit.py and README tiering because get_rate_limit_key returns
"global" for non-internal keys (causing a shared bucket) and the 120/min value
ignores Free/Pro tiers; fix by making rate-limiting dynamic: change the
limiter.limit usage on the POST /v1/check route to call a function that returns
the correct rate string per-request based on the key's tier (e.g., "10/min" for
Free, "60/min" for Pro, "unlimited" or internal for internal keys), and/or
update get_rate_limit_key so it returns a per-api-key identifier (not the
literal "global") so each non-internal key has its own bucket; ensure behavior
matches tests/test_rate_limit.py and README tier names.
---
Nitpick comments:
In `@api/main.py`:
- Around line 65-67: The except block currently calls logger.error(f"IP
blocklist check failed — fail open: {e}") which only logs the message; replace
this with logger.exception("IP blocklist check failed — fail open") inside the
same except Exception as e block so the full traceback is recorded while
preserving the fail-open return False behavior (locate the except block that
references logger.error in api/main.py).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
| @app.middleware("http") | ||
| async def ip_blocklist_middleware(request: Request, call_next): | ||
| client_ip = request.headers.get("X-Forwarded-For", "").split(",")[0].strip() or request.client.host or "unknown" | ||
| if is_ip_blocked(client_ip): | ||
| logger.warning(f"Middleware blocked IP: {client_ip}") | ||
| return JSONResponse(status_code=403, content={"detail": "Access denied"}) | ||
| return await call_next(request) |
There was a problem hiding this comment.
Potential AttributeError if request.client is None.
request.client can be None in certain ASGI configurations (e.g., some test clients, proxies). Accessing .host on None raises AttributeError—the or "unknown" fallback only handles falsy values, not exceptions.
🐛 Proposed fix
`@app.middleware`("http")
async def ip_blocklist_middleware(request: Request, call_next):
- client_ip = request.headers.get("X-Forwarded-For", "").split(",")[0].strip() or request.client.host or "unknown"
+ forwarded = request.headers.get("X-Forwarded-For", "").split(",")[0].strip()
+ client_ip = forwarded or (request.client.host if request.client else None) or "unknown"
if is_ip_blocked(client_ip):
logger.warning(f"Middleware blocked IP: {client_ip}")
return JSONResponse(status_code=403, content={"detail": "Access denied"})
return await call_next(request)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@api/main.py` around lines 170 - 176, The middleware ip_blocklist_middleware
may raise AttributeError when accessing request.client.host because
request.client can be None; change the client IP extraction to safely handle
that by first checking X-Forwarded-For, then using request.client.host only if
request.client is not None (e.g., via getattr(request, "client", None) and
checking .host or using a try/except), defaulting to "unknown" otherwise; keep
the is_ip_blocked call, logger.warning and JSONResponse behavior unchanged.
|



Summary by CodeRabbit
New Features
Changes
Tests