Skip to content

fix: IP blocklist + global rate limit 120/min - #28

Merged
Sandeep-int merged 3 commits into
mainfrom
fix/ip-blocklist-global-rate-limit
Jun 10, 2026
Merged

Sandeep-int merged 3 commits into
mainfrom
fix/ip-blocklist-global-rate-limit

Conversation

@Sandeep-int

@Sandeep-int Sandeep-int commented Jun 10, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • IP blocklist check now denies blocked IPs with a 403 response.
  • Changes

    • Public rate limiting simplified to a single global limit (120/minute).
    • Packaged CLI entry removed (previously exposed command no longer available).
  • Tests

    • Rate-limit test updated to reflect the 120-request threshold.

@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 099b42bd-60f3-49df-b7f8-4206cd40ca64

📥 Commits

Reviewing files that changed from the base of the PR and between a5651aa and b01a1b9.

📒 Files selected for processing (1)
  • tests/test_rate_limit.py
✅ Files skipped from review due to trivial changes (1)
  • tests/test_rate_limit.py

📝 Walkthrough

Walkthrough

Adds an Azure Table–backed IP blocklist (checked by middleware and /v1/check) that returns 403 for blocked IPs, and simplifies public rate limiting to a single global bucket via get_rate_limit_key changes. Also removes a packaging top-level cli entry in egg-info.

Changes

Check Endpoint Security and Rate Limiting

Layer / File(s) Summary
IP blocklist lookup function
api/main.py
New is_ip_blocked(ip) queries Azure Table agentshieldblocklist, returns True when present, and fails open (False) on missing Azure config or lookup errors.
IP blocklist middleware
api/main.py
Middleware extracts client IP (X-Forwarded-For / request.client.host) and immediately returns HTTP 403 JSON when is_ip_blocked is True.
Rate limiting key function change
api/main.py
get_rate_limit_key(...) now returns "global" as the default bucket, consolidating standard request rate limiting.
Check endpoint IP block and rate limit integration
api/main.py
/v1/check performs an early is_ip_blocked(client_ip) guard (logs BLOCK, raises HTTP 403) and uses limiter.limit("120/minute", key_func=get_rate_limit_key) only.
Feedback endpoint rate limit change
api/main.py
/v1/feedback rate limiting simplified to limiter.limit("120/minute", key_func=get_rate_limit_key).
Rate limit tests
tests/test_rate_limit.py
Test updated to expect 120 successful POSTs to /v1/check before returning HTTP 429 on the 121st.

Packaging metadata cleanup

Layer / File(s) Summary
Remove top-level package entry
agent_shield.egg-info/top_level.txt
Removed the cli top-level entry from egg-info metadata (packaging-only change).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I nibble bits of code and logs at night,
I hop through tables to see who's right,
If Azure says "blocked", I sound the bell,
Else rate limits hum in one global shell,
A tiny guard rabbit keeps the endpoints tight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: adding IP blocklist functionality and implementing a global 120/minute rate limit across endpoints.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ip-blocklist-global-rate-limit

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 | 🔴 Critical

Fix import-time crash in /v1/feedback rate limiter: missing _rate_limit_exempt_non_pro

api/main.py:409 uses exempt_when=_rate_limit_exempt_non_pro on the @limiter.limit(...) decorator, but _rate_limit_exempt_non_pro is not defined or imported anywhere in the repository; this will raise NameError when the module is imported (decorators are evaluated at import time). Restore the helper (or update/remove exempt_when to 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 | 🔴 Critical

Fix rate-limit contract mismatch (internal not exempt)

  • api/main.py get_rate_limit_key() routes internal keys to "internal-unlimited" (150-154), but /v1/check applies @limiter.limit("120/minute", key_func=get_rate_limit_key) so internal traffic is still throttled to 120/min (271-273).
  • README.md documents “Internal (unlimited) / Pro (60/min) / Free (10/min)” (287-289), but /v1/check only distinguishes internal vs global—no Pro/Free tiering.
  • api/main.py references _rate_limit_exempt_non_pro in the /v1/feedback decorator (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

📥 Commits

Reviewing files that changed from the base of the PR and between 5890b0a and 3bfe7a0.

⛔ Files ignored due to path filters (2)
  • dist/agent_shield_int-1.0.0-py3-none-any.whl is excluded by !**/dist/**
  • dist/agent_shield_int-1.0.0.tar.gz is excluded by !**/dist/**, !**/*.gz
📒 Files selected for processing (11)
  • agent_shield.egg-info/PKG-INFO
  • agent_shield.egg-info/SOURCES.txt
  • agent_shield.egg-info/dependency_links.txt
  • agent_shield.egg-info/entry_points.txt
  • agent_shield.egg-info/top_level.txt
  • agent_shield_int.egg-info/PKG-INFO
  • agent_shield_int.egg-info/SOURCES.txt
  • agent_shield_int.egg-info/dependency_links.txt
  • agent_shield_int.egg-info/entry_points.txt
  • agent_shield_int.egg-info/top_level.txt
  • api/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

Comment thread api/main.py Resolved
Comment thread api/main.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 win

Redundant IP blocklist check—middleware already handles this.

The new ip_blocklist_middleware (lines 170-176) now blocks IPs before the request reaches this handler. This is_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 | 🟠 Major

Rate limit change breaks the rate-limit tests and makes non-internal traffic share one bucket

  • api/main.py sets @limiter.limit("120/minute", key_func=get_rate_limit_key) on POST /v1/check, but tests/test_rate_limit.py asserts 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 win

Use logging.exception() to capture full traceback.

The fail-open behavior is correct, but logger.error() only logs the exception message. Using logger.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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 348f31a3-1018-44e3-a3f3-d0cd0ccc3826

📥 Commits

Reviewing files that changed from the base of the PR and between 3bfe7a0 and a5651aa.

📒 Files selected for processing (1)
  • api/main.py

Comment thread api/main.py
Comment on lines +170 to +176
@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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

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.

@sonarqubecloud

Copy link
Copy Markdown

@Sandeep-int
Sandeep-int merged commit 2b47ba9 into main Jun 10, 2026
5 checks passed
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.

1 participant