-
Notifications
You must be signed in to change notification settings - Fork 0
fix: security hardening - rate limiting and brute-force protection for bearer auth #31
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e8e38eb
add
krishna3554 15f28ef
fix: retrieval quality - query expansion overfitting and bidirectiona…
krishna3554 742fe41
fix: security hardening - rate limiting and brute-force protection fo…
krishna3554 0b26d04
Merge branch 'main' into fix/security-hardening-rate-limiting
krishna3554 2e44672
fix: address Devin Review findings on rate limiting and recall
devin-ai-integration[bot] f8d5950
ci: build the Docker deployment with the default builder
devin-ai-integration[bot] 82dabab
fix: install locked dependencies in the container image
devin-ai-integration[bot] 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
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
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 |
|---|---|---|
|
|
@@ -2,15 +2,29 @@ | |
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| import re | ||
| import secrets | ||
| import threading | ||
| import time | ||
| from contextlib import asynccontextmanager | ||
| from dataclasses import dataclass, field | ||
| from datetime import UTC, datetime | ||
| from uuid import uuid4 | ||
|
|
||
| from fastapi import Depends, FastAPI, Header, HTTPException, Path, Query, Response, status | ||
| from fastapi import ( | ||
| Depends, | ||
| FastAPI, | ||
| Header, | ||
| HTTPException, | ||
| Path, | ||
| Query, | ||
| Request, | ||
| Response, | ||
| status, | ||
| ) | ||
|
|
||
| from dma_api.config import Settings | ||
| from dma_api.config import AuthLimits, Settings | ||
| from dma_api.models import ( | ||
| MemoryExplanation, | ||
| MemoryPage, | ||
|
|
@@ -22,13 +36,109 @@ | |
| RememberRequest, | ||
| RetrievalExplanation, | ||
| ) | ||
| from dma_api.repository import MemoryRecord, SQLiteMemoryRepository | ||
| from dma_api.repository import MemoryRecord, SQLiteMemoryRepository, get_analyzer | ||
|
|
||
| logger = logging.getLogger("dma_api.auth") | ||
|
|
||
|
|
||
| @dataclass | ||
| class _SourceRecord: | ||
| timestamps: list[float] = field(default_factory=list) | ||
| locked_until: float = 0.0 | ||
|
|
||
|
|
||
| class InMemoryRateLimiter: | ||
| """Per-source sliding-window rate limiter with lockout for failed auth.""" | ||
|
|
||
| def __init__(self, limits: AuthLimits) -> None: | ||
| self._max_attempts = limits.max_attempts | ||
| self._window = limits.window_seconds | ||
| self._lockout = limits.lockout_seconds | ||
| self._max_sources = limits.max_tracked_sources | ||
| self._sources: dict[str, _SourceRecord] = {} | ||
| self._lock = threading.Lock() | ||
|
|
||
| def is_locked_out(self, source: str) -> bool: | ||
| with self._lock: | ||
| record = self._sources.get(source) | ||
| if record is None: | ||
| return False | ||
| return record.locked_until > time.monotonic() | ||
|
|
||
| def record_failure(self, source: str) -> None: | ||
| now = time.monotonic() | ||
| with self._lock: | ||
| self._evict_stale(now) | ||
| record = self._sources.setdefault(source, _SourceRecord()) | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
|
||
| cutoff = now - self._window | ||
| record.timestamps = [t for t in record.timestamps if t > cutoff] | ||
| record.timestamps.append(now) | ||
| if len(record.timestamps) >= self._max_attempts: | ||
| record.locked_until = now + self._lockout | ||
| attempts_in_window = len(record.timestamps) | ||
| logger.warning( | ||
| "auth_failure source=%s total_in_window=%d", | ||
| source, | ||
| attempts_in_window, | ||
| ) | ||
|
|
||
| def record_success(self, source: str) -> None: | ||
| with self._lock: | ||
| self._sources.pop(source, None) | ||
|
|
||
| def tracked_sources(self) -> int: | ||
| with self._lock: | ||
| return len(self._sources) | ||
|
|
||
| def _evict_stale(self, now: float) -> None: | ||
| """Drop sources without in-window failures or an active lockout. | ||
|
|
||
| Must be called while holding ``self._lock``. When eviction alone cannot | ||
| keep the map under ``max_tracked_sources``, the least recently active | ||
| sources are dropped so source churn cannot grow memory without bound. | ||
| """ | ||
| cutoff = now - self._window | ||
| for key, record in list(self._sources.items()): | ||
| if record.locked_until > now: | ||
| continue | ||
| if not any(timestamp > cutoff for timestamp in record.timestamps): | ||
| del self._sources[key] | ||
| overflow = len(self._sources) - self._max_sources + 1 | ||
| if overflow <= 0: | ||
| return | ||
| stalest = sorted(self._sources, key=self._last_activity)[:overflow] | ||
| for key in stalest: | ||
| del self._sources[key] | ||
|
Comment on lines
+106
to
+111
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
|
|
||
| def _last_activity(self, source: str) -> float: | ||
| record = self._sources[source] | ||
| return max(record.locked_until, max(record.timestamps, default=0.0)) | ||
|
|
||
|
|
||
| def _client_source( | ||
| request: Request, x_forwarded_for: str | None, *, trust_forwarded_for: bool | ||
| ) -> str: | ||
| """Identify the caller for rate limiting. | ||
|
|
||
| ``X-Forwarded-For`` is honoured only when the deployment declares that it | ||
| runs behind a trusted proxy; otherwise a client could rotate the header to | ||
| win a fresh failure counter for every guess. The transport peer address is | ||
| the default, so direct callers are never pooled into one shared bucket. | ||
| """ | ||
| if trust_forwarded_for and x_forwarded_for: | ||
| forwarded = x_forwarded_for.split(",")[0].strip() | ||
| if forwarded: | ||
| return forwarded | ||
| client = request.client | ||
| return client.host if client is not None else "unknown" | ||
|
|
||
|
|
||
| def create_app(settings: Settings | None = None) -> FastAPI: | ||
| """Create an independently configurable API application.""" | ||
| runtime_settings = settings or Settings() | ||
| repository = SQLiteMemoryRepository(runtime_settings.database_path) | ||
| analyzer = get_analyzer(runtime_settings.analyzer_kind) | ||
| repository = SQLiteMemoryRepository(runtime_settings.database_path, analyzer=analyzer) | ||
| rate_limiter = InMemoryRateLimiter(runtime_settings.auth_limits) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
|
|
||
| @asynccontextmanager | ||
| async def lifespan(_: FastAPI): | ||
|
|
@@ -41,10 +151,26 @@ async def lifespan(_: FastAPI): | |
| def healthz() -> dict[str, str]: | ||
| return {"status": "ok"} | ||
|
|
||
| def authenticate(authorization: str | None = Header(default=None)) -> str: | ||
| def authenticate( | ||
| request: Request, | ||
| authorization: str | None = Header(default=None), | ||
| x_forwarded_for: str | None = Header(default=None, alias="X-Forwarded-For"), | ||
| ) -> str: | ||
| source = _client_source( | ||
| request, x_forwarded_for, trust_forwarded_for=runtime_settings.trust_forwarded_for | ||
| ) | ||
| if rate_limiter.is_locked_out(source): | ||
| raise HTTPException( | ||
| status_code=status.HTTP_429_TOO_MANY_REQUESTS, | ||
| detail="too many failed authentication attempts; try again later", | ||
| ) | ||
| expected = f"Bearer {runtime_settings.api_key}" | ||
| if authorization is None or not secrets.compare_digest(authorization, expected): | ||
| raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid API key") | ||
| rate_limiter.record_failure(source) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid API key" | ||
| ) | ||
| rate_limiter.record_success(source) | ||
| return runtime_settings.tenant_id | ||
|
|
||
| @app.post("/v1/memories", response_model=MemoryResponse, status_code=status.HTTP_201_CREATED) | ||
|
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.