Skip to content

Commit f3451fa

Browse files
security: bind rate limits to API credential
1 parent 8184cbb commit f3451fa

1 file changed

Lines changed: 9 additions & 1 deletion

File tree

‎app/api/routes.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,14 @@ def _authorize(api_key: str | None) -> None:
9797
raise HTTPException(status_code=401, detail="Invalid API key")
9898

9999

100+
def _rate_limit_identity(api_key: str | None) -> str:
101+
"""Return a non-secret identity that callers cannot control through request fields."""
102+
103+
if api_key is None:
104+
return "development-anonymous"
105+
return hashlib.sha256(api_key.encode("utf-8")).hexdigest()
106+
107+
100108
def _response(
101109
request: RecommendRequest,
102110
recommendations: list[str],
@@ -121,7 +129,7 @@ def recommend(
121129
req: RecommendRequest, x_api_key: str | None = Header(default=None)
122130
) -> RecommendResponse:
123131
_authorize(x_api_key)
124-
if not _rate_limiter.allow(req.user_id):
132+
if not _rate_limiter.allow(_rate_limit_identity(x_api_key)):
125133
raise HTTPException(status_code=429, detail="Recommendation rate limit exceeded")
126134
if _runtime is None:
127135
raise HTTPException(status_code=503, detail="Model not initialised")

0 commit comments

Comments
 (0)