diff --git a/apps/api/app/api/routes/repositories.py b/apps/api/app/api/routes/repositories.py index 6225737..3252088 100644 --- a/apps/api/app/api/routes/repositories.py +++ b/apps/api/app/api/routes/repositories.py @@ -49,6 +49,7 @@ GitHubRateLimitError, GitHubRepoNotFoundError, GitHubServiceError, + RepositoryTooLargeError, fetch_github_metadata, parse_github_url, ) @@ -67,7 +68,7 @@ TestGeneratorError, generate_test, ) -from app.services.ingestion import ingest_repository +from app.services.ingestion import ingest_repository, RepositorySourceTooLargeError from app.services.pr_reviewer import ( PRNotFoundError, review_pull_request, @@ -529,6 +530,18 @@ def cb(processed: int, total: int, msg: str) -> None: files_total=result.files_fetched, message=f"Ingested {result.files_stored} files", ) + except (RepositoryTooLargeError, RepositorySourceTooLargeError) as e: + set_scan_progress( + repository_id=repository_id, + status="failed", + stage="failed", + progress=0, + message=str(e), + ) + raise HTTPException( + status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, + detail=str(e), + ) except GitHubRepoNotFoundError as e: set_scan_progress( repository_id=repository_id, diff --git a/apps/api/app/core/rate_limit.py b/apps/api/app/core/rate_limit.py new file mode 100644 index 0000000..4db6902 --- /dev/null +++ b/apps/api/app/core/rate_limit.py @@ -0,0 +1,227 @@ +"""Application-level API rate limiting for CodeLens. + +Architecture +------------ +Implemented as a Starlette middleware using the ``limits`` library +(the same backend used by ``slowapi``). + +Middleware-based limiting is preferred here because it requires no changes +to individual route function signatures: many CodeLens routes do not accept +a ``Request`` parameter, so decorator-based approaches (slowapi) would have +required adding ``Request`` to every affected route. + +Current storage +--------------- +``MemoryStorage`` -- process-local, in-memory. + +LIMITATION: counters are not shared across multiple worker processes or +Render replicas. If CodeLens is scaled horizontally, the effective limit +seen by a client is ``configured_limit x num_processes``. + +Upgrade path: replace ``MemoryStorage()`` with +``RedisStorage("redis://...")`` and the rest of the code is unchanged. + +How limits are applied +---------------------- +``ROUTE_LIMITS`` is a list of ``(HTTP_method, path_glob, limit_string)`` +tuples evaluated top-to-bottom. The first matching rule wins. If no rule +matches the global ``DEFAULT_LIMIT`` is used. + +Path globs use ``fnmatch`` syntax. ``*`` matches any characters within a +single path segment (or across segments -- fnmatch treats the whole string). + +Client identification +--------------------- +Authenticated requests: the CodeLens JWT session cookie is decoded (without +signature/expiry verification -- the normal auth dependency handles that) to +extract ``sub`` (user ID). This prevents a single user from bypassing limits +by rotating IPs. + +Unauthenticated requests: ``request.client.host`` (remote IP) is used. + +``X-Forwarded-For`` is intentionally NOT trusted: the deployment proxy +configuration has not been audited for header sanitisation. + +How to change limits +-------------------- +Edit ``ROUTE_LIMITS`` or ``DEFAULT_LIMIT`` in this module. No route-file +changes are required. + +Test isolation +-------------- +Call ``reset_limiter()`` between tests to flush all in-memory counters. +This prevents counter leakage between test cases. + +Limitations +----------- +* Process-local only (see above). +* Path matching uses fnmatch -- complex regex patterns are not supported. +* ``Retry-After`` value is approximate. +""" + +from __future__ import annotations + +import fnmatch +import logging +import time +from typing import Callable + +import jwt +from limits import parse as parse_limit +from limits.storage import MemoryStorage +from limits.strategies import FixedWindowRateLimiter +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import JSONResponse, Response + +from app.core.config import settings + +logger = logging.getLogger(__name__) + +# --------------------------------------------------------------------------- +# Storage container -- replaced atomically by reset_limiter() during tests. +# dispatch() accesses via module globals (not captured closures) so that +# reset_limiter() takes effect immediately. +# --------------------------------------------------------------------------- +class _State: + storage: MemoryStorage + limiter: FixedWindowRateLimiter + + def __init__(self): + self.storage = MemoryStorage() + self.limiter = FixedWindowRateLimiter(self.storage) + + +_state = _State() + + +def reset_limiter() -> None: + """Flush all rate-limit counters. + + Call this in test setUp / tearDown to prevent counter leakage between + test cases. Replaces the shared state object so the middleware picks up + fresh counters on the very next request. + """ + global _state + _state = _State() + + +# --------------------------------------------------------------------------- +# Global default -- applies when no specific rule matches. +# --------------------------------------------------------------------------- +DEFAULT_LIMIT = "60/minute" + +# --------------------------------------------------------------------------- +# Per-route limit table. +# Format: (HTTP_method | "*", path_glob, limit_string) +# Evaluated top-to-bottom; first match wins. +# --------------------------------------------------------------------------- +ROUTE_LIMITS: list[tuple[str, str, str]] = [ + # Auth + ("POST", "/auth/login", "10/minute"), + ("POST", "/auth/signup", "5/minute"), + ("GET", "/auth/google/login", "10/minute"), + # Google callback is intentionally NOT rate-limited strictly: the browser + # redirect from Google arrives here and the client cannot control the + # timing. The global default (60/min) still applies. + + # Repository metadata / connect (cause GitHub API calls) + ("POST", "/repositories/github/metadata", "30/minute"), + ("GET", "/repositories/github/metadata", "30/minute"), + ("POST", "/repositories/github", "10/minute"), + + # Scan (expensive background job) + ("POST", "/repositories/*/scan", "5/hour"), + + # AI endpoints + ("POST", "/repositories/*/ask", "20/hour"), + ("POST", "/repositories/*/findings/*/explain", "20/hour"), + ("POST", "/repositories/*/findings/*/fix", "10/hour"), + ("POST", "/repositories/*/findings/*/test", "10/hour"), + ("POST", "/repositories/*/pull-requests/*/ai-review", "5/hour"), + + # Health (raised limit so Render probes are never blocked) + ("GET", "/health", "120/minute"), + ("GET", "/db/health", "30/minute"), +] + + +def _match_path(method: str, path: str) -> str: + """Return the limit string for the first matching rule, or DEFAULT_LIMIT.""" + for rule_method, rule_pattern, limit_str in ROUTE_LIMITS: + if rule_method not in ("*", method): + continue + if fnmatch.fnmatch(path, rule_pattern): + return limit_str + return DEFAULT_LIMIT + + +def _get_client_key(request: Request) -> str: + """Return a stable client identifier for rate-limit namespacing. + + Prefers the authenticated user-id (from the JWT cookie) so that a single + user cannot bypass limits by rotating IP addresses. + + Falls back to ``request.client.host`` for unauthenticated requests. + """ + cookie = request.cookies.get(settings.auth_cookie_name) + if cookie: + try: + payload = jwt.decode( + cookie, + options={"verify_signature": False}, + algorithms=["HS256"], + ) + sub = payload.get("sub") + if sub: + return f"user:{sub}" + except Exception: + pass # malformed token -- fall back to IP + host = (request.client.host if request.client else None) or "unknown" + return f"ip:{host}" + + +class RateLimitMiddleware(BaseHTTPMiddleware): + """Starlette ASGI middleware that enforces per-client rate limits. + + Accesses ``_state`` via the module global on every request so that + ``reset_limiter()`` takes effect immediately without restarting the app. + """ + + async def dispatch(self, request: Request, call_next: Callable) -> Response: + path = request.url.path + method = request.method + + limit_str = _match_path(method, path) + item = parse_limit(limit_str) + key = _get_client_key(request) + # Namespace by method+path so limits are independent per endpoint. + namespace = f"rl:{method}:{path}" + + # Access via module global so reset_limiter() is respected. + allowed = _state.limiter.hit(item, namespace, key) + + if not allowed: + try: + stats = _state.limiter.get_window_stats(item, namespace, key) + retry_after = max(1, int(stats.reset_time - time.time())) + except Exception: + retry_after = 60 + + logger.warning( + "Rate limit exceeded: %s %s client=%s limit=%s", + method, path, key, limit_str, + ) + return JSONResponse( + status_code=429, + content={ + "detail": ( + "Too many requests. " + "Please slow down and try again later." + ), + "code": "RATE_LIMIT_EXCEEDED", + }, + headers={"Retry-After": str(retry_after)}, + ) + + return await call_next(request) diff --git a/apps/api/app/main.py b/apps/api/app/main.py index 83b1e61..73c658e 100644 --- a/apps/api/app/main.py +++ b/apps/api/app/main.py @@ -1,10 +1,11 @@ -from fastapi import FastAPI, Request +from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.middleware.cors import CORSMiddleware from sqlalchemy import text from app.api.routes import auth, repositories, pr_reviews, dashboard, ask from app.core.ai_errors import AIQuotaExceededError +from app.core.rate_limit import RateLimitMiddleware from app.db.database import engine app = FastAPI( @@ -37,6 +38,10 @@ def ai_quota_exception_handler(request: Request, exc: AIQuotaExceededError): allow_headers=["*"], ) +# Rate limiting — added after CORS so 429 responses still carry CORS headers +# for browser clients. +app.add_middleware(RateLimitMiddleware) + app.include_router(auth.router) app.include_router(repositories.router) @@ -44,6 +49,7 @@ def ai_quota_exception_handler(request: Request, exc: AIQuotaExceededError): app.include_router(dashboard.router) app.include_router(ask.router) + @app.get("/health") def health(): return { @@ -51,6 +57,7 @@ def health(): "service": "codelens", } + @app.get("/db/health") def db_health(): try: diff --git a/apps/api/app/services/github.py b/apps/api/app/services/github.py index 24b1dc9..d7db364 100644 --- a/apps/api/app/services/github.py +++ b/apps/api/app/services/github.py @@ -4,7 +4,6 @@ import urllib.error import urllib.request from dataclasses import dataclass -from urllib.parse import urlparse from urllib.parse import quote, urlparse @@ -28,6 +27,17 @@ class GitHubAPIError(GitHubServiceError): pass +class RepositoryTooLargeError(GitHubServiceError): + """Raised when a repository tree exceeds the configured entry limit. + + This prevents CodeLens from loading an extremely large GitHub recursive + tree entirely into memory before filtering. The limit is applied before + any per-file size check so that a repository with millions of files + cannot exhaust application memory. + """ + pass + + @dataclass(frozen=True) class ParsedGitHubRepo: owner: str @@ -64,27 +74,38 @@ class GitHubFileContent: size: int -# File extensions considered as analyzable source code. +# --------------------------------------------------------------------------- +# Resource limits +# --------------------------------------------------------------------------- + +# Maximum size in bytes for a single source file that will be accepted. +# Files larger than this are silently skipped during ingestion (is_supported_file). +MAX_FILE_SIZE_BYTES: int = 100_000 + +# Maximum number of entries (files + directories) allowed in a repository tree +# response before rejecting the ingestion entirely. This prevents loading +# enormous recursive trees into memory before filtering. +MAX_TREE_ENTRIES: int = 10_000 + + SUPPORTED_EXTENSIONS: frozenset[str] = frozenset({ ".py", ".js", ".ts", ".tsx", ".jsx", ".java", ".kt", ".kts", ".go", ".rs", ".rb", ".c", ".cpp", ".cc", ".cxx", ".h", ".hpp", ".cs", ".swift", ".m", - ".php", ".scala", ".ex", ".exs", + ".php", ".scala", ".r", ".sh", ".bash", ".zsh", - ".sql", - ".html", ".css", ".scss", ".less", - ".json", ".yaml", ".yml", ".toml", - ".md", ".txt", ".rst", - ".xml", ".graphql", ".proto", - ".dockerfile", + ".yaml", ".yml", ".json", ".toml", ".ini", ".cfg", + ".md", ".rst", ".txt", + ".sql", ".graphql", ".proto", + ".html", ".css", ".scss", ".sass", ".less", + ".lua", ".dart", ".ex", ".exs", + ".hs", ".ml", ".mli", ".clj", ".cljs", + ".v", ".vhd", ".verilog", ".tf", ".hcl", }) -# Maximum individual file size to fetch (100 KB). -MAX_FILE_SIZE_BYTES: int = 100_000 - def is_supported_file(path: str, size: int = 0) -> bool: """Return True if the file path has a supported extension and is within size limits.""" @@ -102,12 +123,12 @@ def is_supported_file(path: str, size: int = 0) -> bool: def _github_api_request(url: str, timeout: int = 10) -> dict | list: from app.core.config import settings - + headers = { "User-Agent": "CodeLens-App", "Accept": "application/vnd.github+json", } - + if settings.github_token: headers["Authorization"] = f"Bearer {settings.github_token}" @@ -267,6 +288,7 @@ def fetch_repo_tree( Returns a list of GitHubTreeEntry objects. Raises GitHubServiceError subclasses on failure. + Raises RepositoryTooLargeError if the tree exceeds MAX_TREE_ENTRIES entries. """ api_url = ( f"https://api.github.com/repos/{owner}/{repo}" @@ -274,8 +296,17 @@ def fetch_repo_tree( ) payload = _github_api_request(api_url, timeout=timeout) + raw_tree = payload.get("tree", []) + + # Reject before materialising objects — protects against massive trees + if len(raw_tree) > MAX_TREE_ENTRIES: + raise RepositoryTooLargeError( + f"Repository tree contains {len(raw_tree)} entries, which exceeds " + f"the maximum of {MAX_TREE_ENTRIES}. Use a smaller repository." + ) + entries: list[GitHubTreeEntry] = [] - for item in payload.get("tree", []): + for item in raw_tree: entries.append( GitHubTreeEntry( path=item["path"], @@ -301,7 +332,6 @@ def fetch_file_content( Returns a GitHubFileContent with the decoded text. Raises GitHubServiceError subclasses on failure. """ - api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}" encoded_path = quote(path.lstrip("/"), safe="/") api_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{encoded_path}" payload = _github_api_request(api_url, timeout=timeout) diff --git a/apps/api/app/services/ingestion.py b/apps/api/app/services/ingestion.py index cc7007b..0d57e02 100644 --- a/apps/api/app/services/ingestion.py +++ b/apps/api/app/services/ingestion.py @@ -24,6 +24,20 @@ ) +class IngestionError(Exception): + """Base exception for repository ingestion errors.""" + pass + + +class RepositorySourceTooLargeError(IngestionError): + """Raised when the aggregate size of supported source files exceeds the limit.""" + pass + + +# Aggregate limit: Total size of all fetched source files cannot exceed 20 MB. +MAX_TOTAL_SOURCE_BYTES: int = 20_000_000 + + @dataclass class IngestionResult: """Summary returned after ingesting a repository's source files.""" @@ -60,10 +74,11 @@ def ingest_repository( Steps: 1. Fetch the full recursive tree for the given branch. - 2. Filter for supported source files (by extension and size). - 3. Fetch the content of each supported file (up to max_files). - 4. If db and repository_id are provided, persist files to the database. - 5. Return an IngestionResult summary. + 2. Filter for supported source files (by extension and size limits). + 3. Apply aggregate size limits. + 4. Fetch the content of each supported file (up to max_files). + 5. If db and repository_id are provided, persist files to the database. + 6. Return an IngestionResult summary. Files that fail to fetch are recorded in errors and skipped. """ @@ -90,15 +105,41 @@ def ingest_repository( result.files_skipped = len(supported_entries) - len(entries_to_fetch) total_to_fetch = len(entries_to_fetch) + # Enforce aggregate size limit BEFORE fetching contents + total_bytes_expected = sum(entry.size for entry in entries_to_fetch) + if total_bytes_expected > MAX_TOTAL_SOURCE_BYTES: + raise RepositorySourceTooLargeError( + f"Repository source files total {total_bytes_expected} bytes, " + f"exceeding the maximum allowed size of {MAX_TOTAL_SOURCE_BYTES} bytes." + ) + if progress_callback is not None: progress_callback(0, total_to_fetch, f"Found {total_to_fetch} files to fetch") fetched_contents: list[GitHubFileContent] = [] + # Track actual bytes fetched just in case GitHub size metadata is inaccurate + actual_bytes_fetched = 0 + for idx, entry in enumerate(entries_to_fetch, start=1): + if actual_bytes_fetched + entry.size > MAX_TOTAL_SOURCE_BYTES: + # Failsafe if size metadata was wrong or we somehow exceeded limit + raise RepositorySourceTooLargeError( + f"Repository source exceeds the maximum allowed size of {MAX_TOTAL_SOURCE_BYTES} bytes." + ) + try: file_content = fetch_file_content(owner, repo, entry.path) + + # Additional safety check against actual content size + if actual_bytes_fetched + len(file_content.content.encode('utf-8')) > MAX_TOTAL_SOURCE_BYTES: + raise RepositorySourceTooLargeError( + f"Repository source exceeds the maximum allowed size of {MAX_TOTAL_SOURCE_BYTES} bytes." + ) + fetched_contents.append(file_content) + actual_bytes_fetched += len(file_content.content.encode('utf-8')) + result.fetched_files.append( IngestionFileEntry( path=file_content.path, diff --git a/apps/api/requirements.txt b/apps/api/requirements.txt index a7a250d..da254e8 100644 --- a/apps/api/requirements.txt +++ b/apps/api/requirements.txt @@ -28,5 +28,4 @@ argon2-cffi PyJWT authlib>=1.3.0 httpx>=0.27.0 - - +limits>=2.3 diff --git a/apps/api/tests/conftest.py b/apps/api/tests/conftest.py index 8e90d77..996ca46 100644 --- a/apps/api/tests/conftest.py +++ b/apps/api/tests/conftest.py @@ -28,6 +28,7 @@ def tearDown(self): from sqlalchemy import text from app.api.deps import get_current_user # noqa: F401 — re-exported for tests +from app.core.rate_limit import reset_limiter from app.db.database import engine from app.main import app # noqa: F401 — re-exported for tests @@ -42,26 +43,38 @@ def tearDown(self): @pytest.fixture(autouse=True) def sync_sequences(): - """Advance PostgreSQL sequences past any rows inserted with explicit IDs. - - Several test classes insert rows with explicit primary keys (e.g. User(id=1)) - to satisfy FK constraints. PostgreSQL SERIAL sequences are NOT advanced by - explicit-ID inserts. - - This fixture runs before EVERY test (function scope, autouse=True). - That guarantees that after any setUp() inserts User(id=1), the sequence is - re-synchronized before the next test tries to insert a row with an implicit ID, - preventing nextval() collisions regardless of test execution order or whether - the test database is fresh or reused. - - Example of the problem this solves on a fresh CI database: - 1. test_analyzer.setUp() inserts User(id=1) — sequence stays at 1. - 2. This fixture re-runs before test_ask. - 3. MAX(id)=1, so setval sets next nextval() to 2. - 4. test_ask.setUp() inserts User(email=...) — gets id=2, no collision. - - This fixture only affects the test database. It has no production impact. + """Advance PostgreSQL sequences and reset rate-limiter before every test. + + Two responsibilities: + + 1. Sequence synchronisation: + Several test classes insert rows with explicit primary keys (e.g. + User(id=1)) to satisfy FK constraints. PostgreSQL SERIAL sequences are + NOT advanced by explicit-ID inserts. This fixture re-synchronises the + sequence so that implicit inserts in later tests receive IDs higher than + any explicitly inserted ID, preventing primary-key collisions regardless + of test execution order or whether the database is fresh or reused. + + Example: + 1. test_analyzer.setUp() inserts User(id=1) — sequence stays at 1. + 2. This fixture re-runs before test_ask. + 3. MAX(id)=1, so setval makes the next nextval() return 2. + 4. test_ask.setUp() inserts User(email=...) — gets id=2, no collision. + + 2. Rate-limiter reset: + The application rate limiter uses an in-memory counter shared across + all requests to the same ``app`` singleton. Without a reset between + tests, requests made in earlier tests (e.g. auth tests that POST to + /auth/signup) can consume the per-minute quota and cause subsequent + rate-limit tests to see unexpected 429 responses. + + ``reset_limiter()`` replaces the in-memory storage object so all + counters start at zero before each test. + + Both operations are test-infrastructure only. Neither has any production + impact. """ + reset_limiter() with engine.connect() as conn: conn.execute(text( "SELECT setval('users_id_seq', " diff --git a/apps/api/tests/test_rate_limiting.py b/apps/api/tests/test_rate_limiting.py new file mode 100644 index 0000000..e5e752a --- /dev/null +++ b/apps/api/tests/test_rate_limiting.py @@ -0,0 +1,410 @@ +"""Comprehensive tests for Phase 1 API rate limiting. + +Tests cover: +- global default limit +- per-endpoint specific limits (login, signup, google login, github metadata, + github connect, scan, ask, explain, fix, test-gen, ai-pr-review) +- 429 response format (safe message, correct status code) +- Retry-After header presence +- test isolation via reset_limiter() in conftest autouse fixture +- existing auth/repo/AI endpoints still function normally +- health endpoint is not blocked + +Rate-limit semantics (FixedWindowRateLimiter): + For a limit of N/period: requests 1..N are allowed; request N+1 returns 429. +""" + +import unittest +from unittest.mock import patch + +from fastapi.testclient import TestClient + +from app.main import app +from app.core.rate_limit import reset_limiter, DEFAULT_LIMIT, ROUTE_LIMITS, _match_path +from app.api.deps import get_current_user +from tests.conftest import FAKE_USER + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _make_client(): + return TestClient(app, raise_server_exceptions=False) + + +def _hit(client, method, url, n, **kwargs): + """Fire n requests and return all responses.""" + fn = getattr(client, method.lower()) + return [fn(url, **kwargs) for _ in range(n)] + + +def _make_github_metadata(): + """Return a valid GitHubRepoMetadata mock instance.""" + from app.services.github import GitHubRepoMetadata + return GitHubRepoMetadata( + owner="o", + name="n", + full_name="o/n", + description=None, + default_branch="main", + url="https://github.com/o/n", + ) + + +# --------------------------------------------------------------------------- +# Base test class +# The conftest autouse sync_sequences fixture already calls reset_limiter() +# before every test. We also call it in setUp/tearDown for extra safety and +# to ensure the TestClient is created after the reset. +# --------------------------------------------------------------------------- + +class RateLimitTestBase(unittest.TestCase): + def setUp(self): + reset_limiter() + app.dependency_overrides[get_current_user] = lambda: FAKE_USER + self.client = _make_client() + + def tearDown(self): + reset_limiter() + app.dependency_overrides.clear() + + +# --------------------------------------------------------------------------- +# Unit tests — path matching logic +# --------------------------------------------------------------------------- + +class TestPathMatching(unittest.TestCase): + """Verify _match_path returns correct limit strings.""" + + def test_login(self): + self.assertEqual(_match_path("POST", "/auth/login"), "10/minute") + + def test_signup(self): + self.assertEqual(_match_path("POST", "/auth/signup"), "5/minute") + + def test_google_login(self): + self.assertEqual(_match_path("GET", "/auth/google/login"), "10/minute") + + def test_google_callback_uses_default(self): + # Callback must NOT be strictly rate-limited — uses global default + self.assertEqual(_match_path("GET", "/auth/google/callback"), DEFAULT_LIMIT) + + def test_github_metadata_post(self): + self.assertEqual(_match_path("POST", "/repositories/github/metadata"), "30/minute") + + def test_github_metadata_get(self): + self.assertEqual(_match_path("GET", "/repositories/github/metadata"), "30/minute") + + def test_github_connect(self): + self.assertEqual(_match_path("POST", "/repositories/github"), "10/minute") + + def test_scan(self): + self.assertEqual(_match_path("POST", "/repositories/42/scan"), "5/hour") + + def test_ask(self): + self.assertEqual(_match_path("POST", "/repositories/1/ask"), "20/hour") + + def test_explain(self): + self.assertEqual(_match_path("POST", "/repositories/1/findings/5/explain"), "20/hour") + + def test_fix(self): + self.assertEqual(_match_path("POST", "/repositories/1/findings/5/fix"), "10/hour") + + def test_test_gen(self): + self.assertEqual(_match_path("POST", "/repositories/1/findings/5/test"), "10/hour") + + def test_ai_pr_review(self): + self.assertEqual(_match_path("POST", "/repositories/1/pull-requests/3/ai-review"), "5/hour") + + def test_health_elevated(self): + self.assertEqual(_match_path("GET", "/health"), "120/minute") + + def test_db_health(self): + self.assertEqual(_match_path("GET", "/db/health"), "30/minute") + + def test_unmatched_uses_default(self): + self.assertEqual(_match_path("GET", "/repositories"), DEFAULT_LIMIT) + self.assertEqual(_match_path("GET", "/auth/me"), DEFAULT_LIMIT) + + +# --------------------------------------------------------------------------- +# Integration tests — actual HTTP responses +# --------------------------------------------------------------------------- + +class TestRateLimitIsolation(RateLimitTestBase): + """Verify reset_limiter() prevents counter leakage between tests.""" + + def test_isolation_first(self): + responses = _hit(self.client, "GET", "/health", 5) + for r in responses: + self.assertEqual(r.status_code, 200) + + def test_isolation_second(self): + # Counters from test_isolation_first must be gone (reset by setUp). + responses = _hit(self.client, "GET", "/health", 5) + for r in responses: + self.assertEqual(r.status_code, 200) + + +class TestHealthEndpoint(RateLimitTestBase): + """Health endpoint must never be blocked under normal probe frequency.""" + + def test_health_not_blocked(self): + # 120/minute limit; fire 30 to confirm they all pass + responses = _hit(self.client, "GET", "/health", 30) + for r in responses: + self.assertEqual(r.status_code, 200) + + +class Test429Format(RateLimitTestBase): + """429 response must be safe and provider-neutral.""" + + def _exhaust_login(self): + """Exhaust the login limit (10/min) then return 11th response.""" + for _ in range(10): + self.client.post("/auth/login", json={"email": "x@x.com", "password": "x"}) + return self.client.post("/auth/login", json={"email": "x@x.com", "password": "x"}) + + def test_429_status_code(self): + resp = self._exhaust_login() + self.assertEqual(resp.status_code, 429) + + def test_429_body_has_detail(self): + resp = self._exhaust_login() + body = resp.json() + self.assertIn("detail", body) + + def test_429_body_has_code(self): + resp = self._exhaust_login() + body = resp.json() + self.assertEqual(body["code"], "RATE_LIMIT_EXCEEDED") + + def test_429_message_is_safe(self): + resp = self._exhaust_login() + body_str = resp.text.lower() + # Must not leak internal implementation details + for forbidden in ("redis", "memor", "traceback", "exception", + "stack"): + self.assertNotIn(forbidden, body_str, + f"Forbidden word '{forbidden}' found in 429 body") + + def test_429_retry_after_header(self): + resp = self._exhaust_login() + self.assertIn("retry-after", resp.headers) + retry = int(resp.headers["retry-after"]) + self.assertGreater(retry, 0) + + +class TestLoginRateLimit(RateLimitTestBase): + """POST /auth/login: 10/minute. + Requests 1-10 allowed; request 11 blocked. + """ + + def _post_login(self): + return self.client.post( + "/auth/login", + json={"email": "test@example.com", "password": "wrongpassword"}, + ) + + def test_below_limit_not_429(self): + # First 10 may return 401 (wrong password) but NOT 429 + responses = [self._post_login() for _ in range(10)] + for r in responses: + self.assertNotEqual(r.status_code, 429) + + def test_above_limit_is_429(self): + for _ in range(10): + self._post_login() + resp = self._post_login() # 11th — over limit + self.assertEqual(resp.status_code, 429) + + +class TestSignupRateLimit(RateLimitTestBase): + """POST /auth/signup: 5/minute. + Requests 1-5 allowed; request 6 blocked. + """ + + def _post_signup(self, suffix=""): + return self.client.post( + "/auth/signup", + json={"email": f"rl_signup{suffix}@ratelimit.test", + "password": "Password123!"}, + ) + + def test_below_limit_not_429(self): + responses = [self._post_signup(f"b{i}") for i in range(5)] + for r in responses: + self.assertNotEqual(r.status_code, 429, + f"Got 429 on request: status={r.status_code}") + + def test_above_limit_is_429(self): + # 5 allowed, 6th blocked + for i in range(5): + self._post_signup(f"a{i}") + resp = self._post_signup("aover") + self.assertEqual(resp.status_code, 429) + + +class TestGoogleLoginRateLimit(RateLimitTestBase): + """GET /auth/google/login: 10/minute. + Requests 1-10 allowed; request 11 blocked. + """ + + def _get_google_login(self): + return self.client.get("/auth/google/login", follow_redirects=False) + + def test_below_limit_not_429(self): + responses = [self._get_google_login() for _ in range(10)] + for r in responses: + self.assertNotEqual(r.status_code, 429) + + def test_above_limit_is_429(self): + for _ in range(10): + self._get_google_login() + resp = self._get_google_login() # 11th + self.assertEqual(resp.status_code, 429) + + +class TestGitHubMetadataRateLimit(RateLimitTestBase): + """POST /repositories/github/metadata: 30/minute. + Requests 1-30 allowed; request 31 blocked. + """ + + @patch("app.api.routes.repositories.fetch_github_metadata") + def test_below_limit_not_429(self, mock_meta): + mock_meta.return_value = _make_github_metadata() + responses = [ + self.client.post( + "/repositories/github/metadata", + json={"url": "https://github.com/o/n"}, + ) + for _ in range(5) + ] + for r in responses: + self.assertNotEqual(r.status_code, 429) + + def test_above_limit_is_429(self): + # Don't need a valid response here — just exhaust the counter + for _ in range(30): + self.client.post( + "/repositories/github/metadata", + json={"url": "https://github.com/o/n"}, + ) + resp = self.client.post( + "/repositories/github/metadata", + json={"url": "https://github.com/o/n"}, + ) + self.assertEqual(resp.status_code, 429) + + +class TestGitHubConnectRateLimit(RateLimitTestBase): + """POST /repositories/github: 10/minute. + Requests 1-10 allowed; request 11 blocked. + """ + + def test_above_limit_is_429(self): + # Exhaust the counter (responses may be 4xx — doesn't matter) + for _ in range(10): + self.client.post( + "/repositories/github", + json={"url": "https://github.com/o/rl-connect"}, + ) + resp = self.client.post( + "/repositories/github", + json={"url": "https://github.com/o/rl-connect"}, + ) + self.assertEqual(resp.status_code, 429) + + +class TestScanRateLimit(RateLimitTestBase): + """POST /repositories/{id}/scan: 5/hour. + Requests 1-5 allowed; request 6 blocked. + """ + + def test_above_limit_is_429(self): + with patch("app.api.routes.repositories.is_scan_active", return_value=False), patch("app.api.routes.repositories.run_background_scan"): + for _ in range(5): + self.client.post("/repositories/99999/scan") + resp = self.client.post("/repositories/99999/scan") + self.assertEqual(resp.status_code, 429) + + +class TestAskRateLimit(RateLimitTestBase): + """POST /repositories/{id}/ask: 20/hour. + Requests 1-20 allowed; request 21 blocked. + """ + + def test_above_limit_is_429(self): + for _ in range(20): + self.client.post("/repositories/99999/ask", json={"question": "test"}) + resp = self.client.post("/repositories/99999/ask", json={"question": "test"}) + self.assertEqual(resp.status_code, 429) + + +class TestExplainRateLimit(RateLimitTestBase): + """POST /repositories/{id}/findings/{fid}/explain: 20/hour. + Requests 1-20 allowed; request 21 blocked. + """ + + def test_above_limit_is_429(self): + for _ in range(20): + self.client.post("/repositories/99999/findings/1/explain") + resp = self.client.post("/repositories/99999/findings/1/explain") + self.assertEqual(resp.status_code, 429) + + +class TestFixRateLimit(RateLimitTestBase): + """POST /repositories/{id}/findings/{fid}/fix: 10/hour. + Requests 1-10 allowed; request 11 blocked. + """ + + def test_above_limit_is_429(self): + for _ in range(10): + self.client.post("/repositories/99999/findings/1/fix") + resp = self.client.post("/repositories/99999/findings/1/fix") + self.assertEqual(resp.status_code, 429) + + +class TestTestGenRateLimit(RateLimitTestBase): + """POST /repositories/{id}/findings/{fid}/test: 10/hour. + Requests 1-10 allowed; request 11 blocked. + """ + + def test_above_limit_is_429(self): + for _ in range(10): + self.client.post("/repositories/99999/findings/1/test") + resp = self.client.post("/repositories/99999/findings/1/test") + self.assertEqual(resp.status_code, 429) + + +class TestAIPRReviewRateLimit(RateLimitTestBase): + """POST /repositories/{id}/pull-requests/{pr}/ai-review: 5/hour. + Requests 1-5 allowed; request 6 blocked. + """ + + def test_above_limit_is_429(self): + for _ in range(5): + self.client.post("/repositories/99999/pull-requests/1/ai-review") + resp = self.client.post("/repositories/99999/pull-requests/1/ai-review") + self.assertEqual(resp.status_code, 429) + + +class TestLegitimateRequestsPassThrough(RateLimitTestBase): + """Existing functionality must not be broken by rate limiting.""" + + def test_health_returns_200(self): + resp = self.client.get("/health") + self.assertEqual(resp.status_code, 200) + + def test_auth_me_returns_non_429(self): + resp = self.client.get("/auth/me") + self.assertNotEqual(resp.status_code, 429) + + def test_get_repositories_not_blocked(self): + resp = self.client.get("/repositories") + self.assertNotEqual(resp.status_code, 429) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/api/tests/test_resource_limits.py b/apps/api/tests/test_resource_limits.py new file mode 100644 index 0000000..61ef1fc --- /dev/null +++ b/apps/api/tests/test_resource_limits.py @@ -0,0 +1,158 @@ +"""Tests for repository resource exhaustion protection.""" + +import pytest +from unittest.mock import patch, MagicMock +from fastapi.testclient import TestClient + +from app.main import app +from app.services.github import ( + GitHubTreeEntry, + GitHubFileContent, + RepositoryTooLargeError, + MAX_TREE_ENTRIES, + MAX_FILE_SIZE_BYTES, + fetch_repo_tree, + is_supported_file, +) +from app.services.ingestion import ( + ingest_repository, + RepositorySourceTooLargeError, + MAX_TOTAL_SOURCE_BYTES, +) +from app.services.code_retriever import ( + _find_best_window, + MAX_FILES, + MAX_LINES_PER_FILE, + MAX_TOTAL_LINES, +) +from app.api.deps import get_current_user +from tests.conftest import FAKE_USER + + +client = TestClient(app) + + +def test_tree_size_protection(): + """Tree with > MAX_TREE_ENTRIES is rejected before fetching files.""" + large_tree = [{"path": f"file_{i}.py", "type": "blob", "sha": "123", "size": 100} for i in range(MAX_TREE_ENTRIES + 1)] + + with patch("app.services.github._github_api_request", return_value={"tree": large_tree}): + with pytest.raises(RepositoryTooLargeError) as exc: + fetch_repo_tree("owner", "repo") + assert f"exceeds the maximum of {MAX_TREE_ENTRIES}" in str(exc.value) + + +def test_aggregate_source_size_protection_before_fetch(): + """Ingestion rejects repository if sum of supported file sizes exceeds MAX_TOTAL_SOURCE_BYTES.""" + file_size = 50_000 # valid single file + file_count = (MAX_TOTAL_SOURCE_BYTES // file_size) + 1 # enough to exceed total + + large_tree = [ + GitHubTreeEntry(path=f"file_{i}.py", type="blob", sha="123", size=file_size) + for i in range(file_count) + ] + + with patch("app.services.ingestion.fetch_repo_tree", return_value=large_tree): + with pytest.raises(RepositorySourceTooLargeError) as exc: + ingest_repository("owner", "repo", max_files=file_count) + assert "exceeding the maximum allowed size" in str(exc.value) + + +def test_aggregate_source_size_protection_during_fetch(): + """Ingestion rejects repository if actual fetched size exceeds MAX_TOTAL_SOURCE_BYTES.""" + # GitHub tree metadata says files are tiny (so it passes the first check) + file_count = 500 + large_tree = [ + GitHubTreeEntry(path=f"file_{i}.py", type="blob", sha="123", size=10) + for i in range(file_count) + ] + + # But the actual fetch returns huge content, leading to aggregate overflow + actual_file_size = (MAX_TOTAL_SOURCE_BYTES // 10) + 1000 + large_content = "a" * actual_file_size + + with patch("app.services.ingestion.fetch_repo_tree", return_value=large_tree), \ + patch("app.services.ingestion.fetch_file_content", return_value=GitHubFileContent(path="", sha="", content=large_content, size=actual_file_size)): + + with pytest.raises(RepositorySourceTooLargeError) as exc: + ingest_repository("owner", "repo", max_files=file_count) + assert "exceeds the maximum allowed size" in str(exc.value) + + +def test_file_count_protection(): + """Ingestion fetches exactly up to max_files, no more.""" + # Create 300 supported files + large_tree = [ + GitHubTreeEntry(path=f"file_{i}.py", type="blob", sha="123", size=10) + for i in range(300) + ] + + with patch("app.services.ingestion.fetch_repo_tree", return_value=large_tree), \ + patch("app.services.ingestion.fetch_file_content", side_effect=lambda o, r, p: GitHubFileContent(path=p, sha="123", content="print('hello')", size=14)) as mock_fetch: + + result = ingest_repository("owner", "repo", max_files=200) + + assert mock_fetch.call_count == 200 + assert result.files_identified == 300 + assert result.files_fetched == 200 + assert result.files_skipped == 100 + + +def test_individual_file_size_limit(): + """is_supported_file rejects files larger than MAX_FILE_SIZE_BYTES.""" + assert is_supported_file("test.py", size=100) is True + assert is_supported_file("test.py", size=MAX_FILE_SIZE_BYTES + 1) is False + + +def test_endpoint_returns_413_for_large_tree(): + """POST /repositories/{id}/ingest returns 413 for RepositoryTooLargeError.""" + app.dependency_overrides[get_current_user] = lambda: FAKE_USER + + with patch("app.api.routes.repositories.Session.get", return_value=MagicMock(user_id=FAKE_USER.id, owner="owner", name="repo", default_branch="main")), \ + patch("app.api.routes.repositories.ingest_repository", side_effect=RepositoryTooLargeError("Too large")): + + response = client.post("/repositories/1/ingest") + + assert response.status_code == 413 + assert response.json()["detail"] == "Too large" + + app.dependency_overrides.clear() + + +def test_scan_concurrency_protection(): + """POST /repositories/{id}/scan returns existing state if scan is active.""" + app.dependency_overrides[get_current_user] = lambda: FAKE_USER + + mock_running_state = { + "repository_id": 1, + "status": "running", + "stage": "static_analysis", + "progress": 50, + "files_processed": 0, + "files_total": 0, + "message": "Starting static code analysis..." + } + + with patch("app.api.routes.repositories.Session.get", return_value=MagicMock(user_id=FAKE_USER.id)), \ + patch("app.api.routes.repositories.is_scan_active", return_value=True), \ + patch("app.api.routes.repositories.get_scan_progress", return_value=mock_running_state), \ + patch("app.api.routes.repositories.BackgroundTasks.add_task") as mock_add_task: + + response = client.post("/repositories/1/scan") + + assert response.status_code == 202 + assert response.json()["status"] == "running" + mock_add_task.assert_not_called() + + app.dependency_overrides.clear() + + +def test_ask_codelens_protections(): + """Ask CodeLens limits are maintained.""" + assert MAX_FILES == 5 + assert MAX_LINES_PER_FILE == 200 + assert MAX_TOTAL_LINES == 1000 + + # Test _find_best_window bounds + start, end = _find_best_window(match_lines=[500], total_lines=1000, window_size=MAX_LINES_PER_FILE) + assert end - start <= MAX_LINES_PER_FILE