From 9c1b9d07075d21cb3dc5268e4108aff9285774c4 Mon Sep 17 00:00:00 2001 From: HC-ONLINE Date: Fri, 6 Nov 2026 13:29:47 -0500 Subject: [PATCH 1/6] feat(api): add scan admission control, deadlines and dedicated scan threadpool --- src/ciberwebscan/api/app.py | 13 +- src/ciberwebscan/api/concurrency.py | 264 ++++++++++++++++++++++++++++ src/ciberwebscan/config/models.py | 30 ++++ 3 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 src/ciberwebscan/api/concurrency.py diff --git a/src/ciberwebscan/api/app.py b/src/ciberwebscan/api/app.py index edcc56e..ea5c519 100644 --- a/src/ciberwebscan/api/app.py +++ b/src/ciberwebscan/api/app.py @@ -10,12 +10,14 @@ from collections.abc import AsyncGenerator from contextlib import asynccontextmanager +import anyio.to_thread from fastapi import FastAPI, Request from fastapi.encoders import jsonable_encoder from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from ciberwebscan import __description__, __version__ +from ciberwebscan.api.concurrency import configure as configure_scan_concurrency from ciberwebscan.api.middleware import ( add_rate_limiting_middleware, add_request_logging_middleware, @@ -44,8 +46,17 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Handle application startup and shutdown.""" logger.info("Starting CiberWebScan API") - # Start cleanup scheduler + # Explicit sizing of the shared AnyIO threadpool (BUG-013): the + # framework default of 40 tokens becomes configuration, and the scan + # admission controller/limiter are built from the current config so + # the effective limits are fixed and logged at startup. app_config = get_config() + anyio.to_thread.current_default_thread_limiter().total_tokens = ( + app_config.api.sync_threadpool_tokens + ) + configure_scan_concurrency() + + # Start cleanup scheduler if app_config.download.enabled: scheduler = get_scheduler() scheduler.start() diff --git a/src/ciberwebscan/api/concurrency.py b/src/ciberwebscan/api/concurrency.py new file mode 100644 index 0000000..d4060ff --- /dev/null +++ b/src/ciberwebscan/api/concurrency.py @@ -0,0 +1,264 @@ +""" +In-flight admission control for scan endpoints (BUG-013). + +Scan operations (analyze, attack, scrape, scrape batch, quick scan) are +long, blocking and non-cancellable once started. Before this module, the +five scan routes were plain ``def`` handlers dispatched by FastAPI onto the +shared AnyIO threadpool (default 40 tokens). A burst larger than the pool +built an unbounded FIFO queue with no signal to the client and no deadline. + +This module provides: + +- :class:`ScanAdmissionController`: a per-process in-flight counter with + early rejection (the 429 alternative to an unbounded queue). +- A dedicated AnyIO :class:`~anyio.CapacityLimiter` for scan work (sized + from ``api.max_concurrent_scans``), so scans stop competing with the + shared pool's tokens for synchronous dependencies and streaming responses. +- :func:`run_scan`: admission + execution + optional deadline with honest + cancellation semantics (see below). + +Cancellation semantics (verified against the installed AnyIO source and +measured): + +Starlette/AnyIO run each request inside a cancel scope. When a route +returns or raises, that scope is torn down and cancels the awaiting path. +``asyncio.shield`` only protects a task from the ``wait_for`` deadline; it +does NOT protect it from request-scope teardown. A naive +``ensure_future`` + ``wait_for(shield(...))`` therefore cancels the scan +work (and releases its slot) as soon as the 504 is delivered, while the +blocking worker thread keeps running: capacity is freed while resources are +still consumed. + +To avoid that, the blocking callable runs via +``anyio.to_thread.run_sync(..., abandon_on_cancel=True, limiter=...)``. With +``abandon_on_cancel=True`` AnyIO shields the worker from the request's +cancel scope, so cancelling the *wait* (deadline or client disconnect) +detaches the waiter but leaves the thread running. The in-flight slot is +released via a done callback on the worker future, which fires on the event +loop only when the worker thread has truly finished (and is safely +suppressed if the loop is already closed). Capacity therefore tracks real +resource usage, never the client's willingness to keep waiting. + +Note on token ownership: the scan limiter is used *only* as the worker gate +(``run_sync`` acquires and releases its own token). The admission counter is +a separate, module-owned integer so that (a) a task never holds two tokens on +one limiter — AnyIO forbids it — and (b) the slot can outlive the request. +""" + +from __future__ import annotations + +import asyncio +import logging +from collections.abc import Callable +from typing import TypeVar + +import anyio.to_thread +from anyio import CapacityLimiter +from fastapi import HTTPException + +from ciberwebscan.config.loader import get_config + +logger = logging.getLogger(__name__) + +T = TypeVar("T") + +RETRY_AFTER_SECONDS = 5 +"""Seconds advertised in ``Retry-After`` when scan capacity is exhausted.""" + + +class ScanAdmissionController: + """Bounded in-flight counter for scan operations. + + ``try_acquire`` performs the check and the increment in a single + synchronous step on the event loop thread (no ``await`` between them), + so two concurrent requests within one process can never both observe + free capacity for the same slot. With multiple API worker processes the + limit is per process, not global. + """ + + def __init__(self, limit: int) -> None: + """Initialize the controller. + + Args: + limit: Maximum number of scans allowed in flight. + + Raises: + ValueError: If limit is below 1. + """ + if limit < 1: + raise ValueError("limit must be >= 1") + self._limit = limit + self._in_flight = 0 + + @property + def limit(self) -> int: + """Maximum number of scans allowed in flight.""" + return self._limit + + @property + def in_flight(self) -> int: + """Number of scans currently holding a slot.""" + return self._in_flight + + def try_acquire(self) -> bool: + """Take a slot if one is free. + + Returns: + True when a slot was acquired, False when the limit is reached. + """ + if self._in_flight >= self._limit: + return False + self._in_flight += 1 + return True + + def release(self) -> None: + """Return a previously acquired slot. + + Callers must only release a slot they acquired, and only when the + underlying work has really finished. A release without a matching + acquisition is logged and ignored rather than corrupting the count. + """ + if self._in_flight <= 0: + logger.warning("Scan admission release without a held slot; ignored") + return + self._in_flight -= 1 + + +_controller: ScanAdmissionController | None = None +_scan_limiter: CapacityLimiter | None = None + + +def configure() -> ScanAdmissionController: + """(Re)build the admission controller and scan limiter from config. + + Called from the application lifespan so the effective limits are fixed + at startup and logged once. Also usable from tests to apply a modified + configuration; a reconfigure while scans are in flight discards the old + accounting, so it must only happen when no scan is running. + """ + global _controller, _scan_limiter + + limit = get_config().api.max_concurrent_scans + _controller = ScanAdmissionController(limit) + _scan_limiter = CapacityLimiter(limit) + logger.info( + "Scan concurrency configured: max_concurrent_scans=%d, " + "scan_timeout_seconds=%s, sync_threadpool_tokens=%d", + limit, + get_config().api.scan_timeout_seconds, + get_config().api.sync_threadpool_tokens, + ) + return _controller + + +def reset() -> None: + """Drop the global controller and limiter (used by tests).""" + global _controller, _scan_limiter + _controller = None + _scan_limiter = None + + +def get_controller() -> ScanAdmissionController: + """Return the admission controller, building it from config if needed.""" + if _controller is None: + return configure() + return _controller + + +def get_scan_limiter() -> CapacityLimiter: + """Return the dedicated AnyIO limiter for scan threads.""" + if _scan_limiter is None: + configure() + assert _scan_limiter is not None + return _scan_limiter + + +async def run_scan(func: Callable[[], T]) -> T: + """Run a blocking scan callable with admission control and a deadline. + + The callable executes on a worker thread gated by the dedicated scan + limiter (not the shared AnyIO threadpool), so scan work cannot crowd out + synchronous dependencies or streaming responses. + + Saturation behaviour: when ``api.max_concurrent_scans`` scans are + already in flight, the request is rejected immediately with 429 and a + ``Retry-After`` header instead of queueing indefinitely. + + Deadline behaviour (``api.scan_timeout_seconds``): the client is + answered with 504 when the deadline elapses, but the blocking work + cannot be stopped — it keeps running until it finishes on its own + (bounded by the per-operation HTTP timeouts), and the in-flight slot is + held until then (released by the worker's done callback at true thread + end). With no timeout configured the request waits for the scan to + complete, as before. + + Args: + func: Zero-argument callable performing the blocking scan work. + + Returns: + Whatever the callable returns. + + Raises: + HTTPException: 429 when at capacity, 504 when the deadline elapses, + or whatever exception the callable itself raises. + """ + controller = get_controller() + if not controller.try_acquire(): + logger.warning( + "Scan rejected: %d scans already in flight (limit %d)", + controller.in_flight, + controller.limit, + ) + raise HTTPException( + status_code=429, + detail=( + f"Too many concurrent scans ({controller.in_flight} in " + f"flight, limit {controller.limit}); retry later" + ), + headers={"Retry-After": str(RETRY_AFTER_SECONDS)}, + ) + + # The slot taken above is released only when the worker thread has truly + # finished. add_done_callback on the worker future fires on the event + # loop at thread end (and is suppressed if the loop is already closed), + # so capacity is never freed while blocking work is still running. + worker_task: asyncio.Task[T] = asyncio.ensure_future( + anyio.to_thread.run_sync( + func, + abandon_on_cancel=True, + limiter=get_scan_limiter(), + ) + ) + + def _on_worker_done(finished: asyncio.Future[T]) -> None: + controller.release() + if not finished.cancelled(): + # Retrieve the exception (if any) so an abandoned-after-504 scan + # cannot emit "Task exception was never retrieved". + finished.exception() + + worker_task.add_done_callback(_on_worker_done) + + timeout = get_config().api.scan_timeout_seconds + if timeout is None: + return await worker_task + + try: + # Shielded: the deadline cancels only our wait, never the worker + # task that owns the thread and the admission slot. + return await asyncio.wait_for(asyncio.shield(worker_task), timeout) + except asyncio.TimeoutError as exc: + logger.error( + "Scan exceeded api.scan_timeout_seconds=%.1fs; answering 504 " + "while the non-cancellable work keeps its admission slot until " + "it finishes", + timeout, + ) + raise HTTPException( + status_code=504, + detail=( + f"Scan exceeded the configured deadline ({timeout:.0f}s). " + "The request was abandoned; the server-side work may still " + "be running until it reaches its own bounded end." + ), + ) from exc diff --git a/src/ciberwebscan/config/models.py b/src/ciberwebscan/config/models.py index 23e0025..03995fb 100644 --- a/src/ciberwebscan/config/models.py +++ b/src/ciberwebscan/config/models.py @@ -448,6 +448,36 @@ class APIConfig(BaseModel): port: Annotated[int, Field(ge=1, le=65535)] = 8000 auth: APIAuthConfig = Field(default_factory=lambda: APIAuthConfig()) rate_limit: APIRateLimitConfig = Field(default_factory=lambda: APIRateLimitConfig()) + max_concurrent_scans: Annotated[int, Field(ge=1, le=256)] = Field( + default=32, + description=( + "Maximum number of scan operations (analyze, attack, scrape, " + "scrape batch, quick scan) allowed in flight per API process. " + "Requests beyond this limit are rejected immediately with 429 " + "instead of queueing indefinitely. The limit is per process: " + "running multiple workers multiplies the effective capacity." + ), + ) + scan_timeout_seconds: Annotated[float | None, Field(ge=1.0, le=3600.0)] = Field( + default=None, + description=( + "Optional deadline for a whole scan request. When exceeded, the " + "client receives 504 and the admission slot is kept until the " + "underlying (non-cancellable) work finishes, so capacity is never " + "released while resources are still in use. None (default) = no " + "deadline. For batch scans the deadline covers the entire batch." + ), + ) + sync_threadpool_tokens: Annotated[int, Field(ge=1, le=512)] = Field( + default=40, + description=( + "Size of the shared AnyIO threadpool (used by synchronous " + "dependencies and streaming responses). Explicit so the default " + "of 40 threads is configuration, not a framework magic number. " + "Scan endpoints do not use this pool; they have their own limit " + "(api.max_concurrent_scans)." + ), + ) trusted_proxies: list[str] = Field( default=[], description=( From 8095fb8b3d6fdf962c633ab4c6bab8df432f01cb Mon Sep 17 00:00:00 2001 From: HC-ONLINE Date: Fri, 6 Nov 2026 13:34:16 -0500 Subject: [PATCH 2/6] fix(api): run scan routes through admission control instead of the shared threadpool --- src/ciberwebscan/api/routes/analyze.py | 36 +++++++++++++++- src/ciberwebscan/api/routes/attack.py | 36 +++++++++++++++- src/ciberwebscan/api/routes/quick.py | 30 ++++++++++++- src/ciberwebscan/api/routes/scrape.py | 59 ++++++++++++++++++++++++-- 4 files changed, 151 insertions(+), 10 deletions(-) diff --git a/src/ciberwebscan/api/routes/analyze.py b/src/ciberwebscan/api/routes/analyze.py index a0318ac..4699f8d 100644 --- a/src/ciberwebscan/api/routes/analyze.py +++ b/src/ciberwebscan/api/routes/analyze.py @@ -5,12 +5,14 @@ from __future__ import annotations import logging +from functools import partial from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, Request, status from pydantic import ValidationError from ciberwebscan.api.auth import AuthenticatedUser, get_current_user +from ciberwebscan.api.concurrency import run_scan from ciberwebscan.api.helpers.download_helper import enrich_response_with_token from ciberwebscan.api.models.requests import AnalyzeRequest from ciberwebscan.api.models.responses import APIResponse @@ -23,8 +25,25 @@ router = APIRouter() -@router.post("/analyze", response_model=APIResponse[AnalysisReport]) -def analyze_url( +@router.post( + "/analyze", + response_model=APIResponse[AnalysisReport], + responses={ + 429: { + "description": ( + "Too many concurrent scans (api.max_concurrent_scans); " + "retry after the advertised Retry-After seconds" + ) + }, + 504: { + "description": ( + "Scan exceeded api.scan_timeout_seconds; the blocking work " + "may still be running server-side" + ) + }, + }, +) +async def analyze_url( request: AnalyzeRequest, http_request: Request, user: Annotated[AuthenticatedUser, Depends(get_current_user)], @@ -32,7 +51,20 @@ def analyze_url( """ Perform security analysis on a URL. Supports SSL analysis, technology fingerprinting, header analysis, and CVE lookup. + + Runs under the API's scan admission control: at most + ``api.max_concurrent_scans`` scans execute at once per process; excess + requests receive 429 instead of queueing indefinitely. """ + return await run_scan(partial(_analyze_sync, request, http_request, user)) + + +def _analyze_sync( + request: AnalyzeRequest, + http_request: Request, + user: AuthenticatedUser, +) -> APIResponse[AnalysisReport]: + """Blocking analysis implementation (runs in a worker thread).""" try: # Convert request to service options options = AnalyzeOptions( diff --git a/src/ciberwebscan/api/routes/attack.py b/src/ciberwebscan/api/routes/attack.py index 94d294a..3d6537d 100644 --- a/src/ciberwebscan/api/routes/attack.py +++ b/src/ciberwebscan/api/routes/attack.py @@ -8,12 +8,14 @@ from __future__ import annotations import logging +from functools import partial from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, Request, status from pydantic import ValidationError from ciberwebscan.api.auth import AuthenticatedUser, get_current_user +from ciberwebscan.api.concurrency import run_scan from ciberwebscan.api.helpers.download_helper import enrich_response_with_token from ciberwebscan.api.models.requests import AttackRequest from ciberwebscan.api.models.responses import APIResponse @@ -27,8 +29,25 @@ router = APIRouter() -@router.post("/attack", response_model=APIResponse[AttackResult]) -def attack_target( +@router.post( + "/attack", + response_model=APIResponse[AttackResult], + responses={ + 429: { + "description": ( + "Too many concurrent scans (api.max_concurrent_scans); " + "retry after the advertised Retry-After seconds" + ) + }, + 504: { + "description": ( + "Scan exceeded api.scan_timeout_seconds; the blocking work " + "may still be running server-side" + ) + }, + }, +) +async def attack_target( request: AttackRequest, http_request: Request, user: Annotated[AuthenticatedUser, Depends(get_current_user)], @@ -40,7 +59,20 @@ def attack_target( **IMPORTANT**: Only test systems you own or have explicit written permission to test. Setting `user_consent=true` confirms that you have that permission. + + Runs under the API's scan admission control: at most + ``api.max_concurrent_scans`` scans execute at once per process; excess + requests receive 429 instead of queueing indefinitely. """ + return await run_scan(partial(_attack_sync, request, http_request, user)) + + +def _attack_sync( + request: AttackRequest, + http_request: Request, + user: AuthenticatedUser, +) -> APIResponse[AttackResult]: + """Blocking attack implementation (runs in a worker thread).""" try: from ciberwebscan.config.loader import get_config as get_app_config diff --git a/src/ciberwebscan/api/routes/quick.py b/src/ciberwebscan/api/routes/quick.py index 18d7312..4be298d 100644 --- a/src/ciberwebscan/api/routes/quick.py +++ b/src/ciberwebscan/api/routes/quick.py @@ -7,11 +7,13 @@ from __future__ import annotations import logging +from functools import partial from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, Request from ciberwebscan.api.auth import AuthenticatedUser, get_current_user +from ciberwebscan.api.concurrency import run_scan from ciberwebscan.api.helpers.download_helper import enrich_response_with_token from ciberwebscan.api.models.requests import QuickScanRequest from ciberwebscan.api.models.responses import ErrorResponse, QuickScanResponse @@ -32,7 +34,10 @@ "- **low**: SSL, fingerprint, headers (no attacks, no CVEs)\n" "- **medium**: Analysis + moderate attacks (XSS, SQLi) - requires consent\n" "- **high**: Full analysis + all attacks + CVEs - requires consent\n\n" - "Scraping is enabled when `selector` or `dynamic` is provided." + "Scraping is enabled when `selector` or `dynamic` is provided.\n\n" + "Runs under the API's scan admission control: at most " + "`api.max_concurrent_scans` scans execute at once per process; " + "excess requests receive 429 instead of queueing indefinitely." ), responses={ 401: { @@ -40,10 +45,22 @@ "description": "Unauthorized (missing/invalid API key)", }, 400: {"model": ErrorResponse, "description": "Validation error"}, + 429: { + "description": ( + "Too many concurrent scans (api.max_concurrent_scans); " + "retry after the advertised Retry-After seconds" + ) + }, 500: {"model": ErrorResponse, "description": "Internal server error"}, + 504: { + "description": ( + "Scan exceeded api.scan_timeout_seconds; the blocking work " + "may still be running server-side" + ) + }, }, ) -def quick_scan( +async def quick_scan( request: QuickScanRequest, http_request: Request, user: Annotated[AuthenticatedUser, Depends(get_current_user)], @@ -58,6 +75,15 @@ def quick_scan( Scraping runs when selector or dynamic is provided. """ + return await run_scan(partial(_quick_scan_sync, request, http_request, user)) + + +def _quick_scan_sync( + request: QuickScanRequest, + http_request: Request, + user: AuthenticatedUser, +) -> QuickScanResponse: + """Blocking quick scan implementation (runs in a worker thread).""" try: # Validate consent for medium/high preset = request.preset.lower() diff --git a/src/ciberwebscan/api/routes/scrape.py b/src/ciberwebscan/api/routes/scrape.py index 5b2823b..348dbdb 100644 --- a/src/ciberwebscan/api/routes/scrape.py +++ b/src/ciberwebscan/api/routes/scrape.py @@ -6,6 +6,7 @@ import logging import uuid +from functools import partial from typing import Annotated, Any from urllib.parse import urlparse @@ -13,6 +14,7 @@ from pydantic import ValidationError from ciberwebscan.api.auth import AuthenticatedUser, get_current_user +from ciberwebscan.api.concurrency import run_scan from ciberwebscan.api.helpers.download_helper import enrich_response_with_token from ciberwebscan.api.models.requests import ScrapeBatchRequest, ScrapeRequest from ciberwebscan.api.models.responses import ( @@ -27,9 +29,28 @@ router = APIRouter() +_SCAN_RESPONSES: dict[int | str, dict[str, Any]] = { + 429: { + "description": ( + "Too many concurrent scans (api.max_concurrent_scans); " + "retry after the advertised Retry-After seconds" + ) + }, + 504: { + "description": ( + "Scan exceeded api.scan_timeout_seconds; the blocking work " + "may still be running server-side" + ) + }, +} + -@router.post("/scrape", response_model=APIResponse[ScrapeResult | list[dict[str, Any]]]) -def scrape_url( +@router.post( + "/scrape", + response_model=APIResponse[ScrapeResult | list[dict[str, Any]]], + responses=_SCAN_RESPONSES, +) +async def scrape_url( request: ScrapeRequest, http_request: Request, user: Annotated[AuthenticatedUser, Depends(get_current_user)], @@ -37,7 +58,20 @@ def scrape_url( """ Scrape a single URL and return structured data. Supports both static (BeautifulSoup) and dynamic (Playwright) scraping. + + Runs under the API's scan admission control: at most + ``api.max_concurrent_scans`` scans execute at once per process; excess + requests receive 429 instead of queueing indefinitely. """ + return await run_scan(partial(_scrape_sync, request, http_request, user)) + + +def _scrape_sync( + request: ScrapeRequest, + http_request: Request, + user: AuthenticatedUser, +) -> APIResponse[ScrapeResult | list[dict[str, Any]]]: + """Blocking scrape implementation (runs in a worker thread).""" try: # Convert request to service options options = ScrapeOptions( @@ -105,15 +139,32 @@ def scrape_url( ) from e -@router.post("/scrape/batch", response_model=APIResponse[ScrapeBatchResultResponse]) -def scrape_batch( +@router.post( + "/scrape/batch", + response_model=APIResponse[ScrapeBatchResultResponse], + responses=_SCAN_RESPONSES, +) +async def scrape_batch( request: ScrapeBatchRequest, http_request: Request, user: Annotated[AuthenticatedUser, Depends(get_current_user)], ) -> APIResponse[ScrapeBatchResultResponse]: """ Scrape multiple URLs in batch. + + Runs under the API's scan admission control: the whole batch holds one + admission slot; a configured ``api.scan_timeout_seconds`` deadline + covers the entire batch. """ + return await run_scan(partial(_scrape_batch_sync, request, http_request, user)) + + +def _scrape_batch_sync( + request: ScrapeBatchRequest, + http_request: Request, + user: AuthenticatedUser, +) -> APIResponse[ScrapeBatchResultResponse]: + """Blocking batch scrape implementation (runs in a worker thread).""" try: urls = [str(url) for url in request.urls] options = ScrapeOptions( From efd45c71595320eca659d6e7993a1cb7ef5e8624 Mon Sep 17 00:00:00 2001 From: HC-ONLINE Date: Fri, 6 Nov 2026 13:35:40 -0500 Subject: [PATCH 3/6] fix(api): keep download and cleanup scheduler work off the event loop --- src/ciberwebscan/api/routes/download.py | 21 ++++++++++++------- .../services/cleanup_scheduler.py | 8 +++++-- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/ciberwebscan/api/routes/download.py b/src/ciberwebscan/api/routes/download.py index 621fb71..a6dbead 100644 --- a/src/ciberwebscan/api/routes/download.py +++ b/src/ciberwebscan/api/routes/download.py @@ -13,6 +13,7 @@ from fastapi import APIRouter, Depends, HTTPException, status from fastapi.responses import StreamingResponse +from starlette.concurrency import run_in_threadpool from ciberwebscan.api.auth import AuthenticatedUser, get_current_user from ciberwebscan.config.loader import get_config @@ -202,8 +203,12 @@ async def download_file( # Log-safe caller identity: never write raw API key material to logs. log_user = mask_identifier(user.identifier) - # Validate token - validation_result = download_service.validate_download_request( + # The DownloadService bridges sync registry code via run_async(); when + # called directly on the event loop that blocks it for the duration + # (BUG-013). Every blocking service call below is offloaded to the + # threadpool instead. + validation_result = await run_in_threadpool( + download_service.validate_download_request, token=token, user_id=user.identifier, ) @@ -229,9 +234,11 @@ async def download_file( reservation = _AttemptReservation(download_service, token) # Get file stream - stream_result = download_service.get_file_stream(token=token) + stream_result = await run_in_threadpool( + download_service.get_file_stream, token=token + ) if not stream_result.success: - reservation.refund_once() + await run_in_threadpool(reservation.refund_once) logger.error(f"Failed to get file stream: {stream_result.error}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, @@ -240,7 +247,7 @@ async def download_file( # Validate data is not None before announcing the stream if stream_result.data is None: - reservation.refund_once() + await run_in_threadpool(reservation.refund_once) logger.error("Stream result data is None despite success status") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, @@ -248,9 +255,9 @@ async def download_file( ) # Token metadata: the stored export format drives the download filename - info_result = download_service.get_info(token=token) + info_result = await run_in_threadpool(download_service.get_info, token=token) if not info_result.success or info_result.data is None: - reservation.refund_once() + await run_in_threadpool(reservation.refund_once) logger.error(f"Failed to get download metadata: {info_result.error}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, diff --git a/src/ciberwebscan/services/cleanup_scheduler.py b/src/ciberwebscan/services/cleanup_scheduler.py index bd8265e..331b577 100644 --- a/src/ciberwebscan/services/cleanup_scheduler.py +++ b/src/ciberwebscan/services/cleanup_scheduler.py @@ -11,6 +11,8 @@ import logging from typing import Any +from starlette.concurrency import run_in_threadpool + from ciberwebscan.config.loader import get_config from ciberwebscan.services.download_service import DownloadService @@ -58,8 +60,10 @@ async def _run_loop(self) -> None: if not self._running: break - # Run cleanup - result = self._service.cleanup_expired_tokens() + # Run cleanup off the event loop: the service bridges sync + # registry code via run_async(), which would otherwise block + # the loop (and every pending request) for the whole sweep. + result = await run_in_threadpool(self._service.cleanup_expired_tokens) if result.success: count = result.data or 0 From f53e34ba291d86ed56c29ad085614e715bc898b0 Mon Sep 17 00:00:00 2001 From: HC-ONLINE Date: Fri, 6 Nov 2026 13:36:52 -0500 Subject: [PATCH 4/6] perf(client): cache the shared SSL context to avoid repeated TLS setup --- src/ciberwebscan/core/client/http_client.py | 74 ++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/src/ciberwebscan/core/client/http_client.py b/src/ciberwebscan/core/client/http_client.py index 90f695d..e8fa043 100644 --- a/src/ciberwebscan/core/client/http_client.py +++ b/src/ciberwebscan/core/client/http_client.py @@ -17,6 +17,7 @@ import logging import os import random +import ssl import threading import time from collections import deque @@ -231,6 +232,68 @@ def max_rate(self) -> float: return self._max_rate +# Process-wide TLS contexts for verify=True clients, keyed by every input +# that changes how httpx would build its default context. +_ssl_context_cache: dict[tuple[bool, str | None, str | None], ssl.SSLContext] = {} +_ssl_context_lock = threading.Lock() + + +def _shared_ssl_context(http2: bool, trust_env: bool) -> ssl.SSLContext | None: + """Return a reusable TLS context for ``verify=True`` clients. + + Building httpx's default verification context re-reads the whole CA + bundle (certifi) on every construction — hundreds of milliseconds per + ``httpx.Client`` (measured: ~420 ms for the context alone, up to + ~1.3 s for the first full client), amplified by the GIL when many + scans construct clients concurrently (BUG-013). ``ssl.SSLContext`` is + safe to share between threads and httpx accepts it directly via + ``verify=``, so one context per shape is built and reused. + + The cache key covers every input that changes httpx's own default + context: + + - ``http2``: httpcore sets the ALPN protocols *on the context object* + for every new connection, so contexts must never be shared between + HTTP/2 and HTTP/1.1-only clients. + - ``trust_env`` plus the resolved ``SSL_CERT_FILE``/``SSL_CERT_DIR`` + values: httpx only honours those environment variables under + ``trust_env``; including the values keeps a runtime change from + silently reusing a stale bundle. + + Returns: + A reusable context, or None when it cannot be built (e.g. certifi + unavailable) — the caller then falls back to httpx's own + uncached construction. + """ + try: + import certifi + except ImportError: # pragma: no cover - certifi ships with httpx + return None + + ssl_cert_file = os.environ.get("SSL_CERT_FILE") if trust_env else None + ssl_cert_dir = os.environ.get("SSL_CERT_DIR") if trust_env else None + key = (http2, ssl_cert_file, ssl_cert_dir) + + context = _ssl_context_cache.get(key) + if context is not None: + return context + + with _ssl_context_lock: + context = _ssl_context_cache.get(key) + if context is None: + # Same construction httpx performs for verify=True + # (httpx._config.create_ssl_context), replicated here once + # instead of per client. + if ssl_cert_file: + context = ssl.create_default_context(cafile=ssl_cert_file) + elif ssl_cert_dir: + context = ssl.create_default_context(capath=ssl_cert_dir) + else: + context = ssl.create_default_context(cafile=certifi.where()) + _ssl_context_cache[key] = context + return context + + class HTTPClient: """ HTTP client with automatic retry, rate limiting, and logging. @@ -435,10 +498,19 @@ def _validate_request_target(request: httpx.Request) -> None: # Build httpx client. trust_env is explicit: environment proxies # (HTTP_PROXY & co.) are ignored unless use_env_proxies enabled # them, and in that case every env proxy was validated above. + # verify=True reuses a process-wide TLS context built with the + # same construction httpx would perform, minus the per-client CA + # bundle reload (see _shared_ssl_context). + verify_for_client: bool | ssl.SSLContext = resolved_verify + if resolved_verify is True: + shared_context = _shared_ssl_context(resolved_http2, resolved_use_env) + if shared_context is not None: + verify_for_client = shared_context + self._client = httpx.Client( timeout=resolved_timeout, http2=resolved_http2, - verify=resolved_verify, + verify=verify_for_client, follow_redirects=resolved_follow_redirects, max_redirects=resolved_max_redirects, headers=default_headers, From 378b32ed94f271f31fa8af8d1aeedde52f45e92f Mon Sep 17 00:00:00 2001 From: HC-ONLINE Date: Fri, 6 Nov 2026 13:39:11 -0500 Subject: [PATCH 5/6] test(api): cover the scan concurrency contract --- tests/integration/api/test_concurrency.py | 119 +++++++++ .../api/test_concurrency_limits.py | 183 +++++++++++++ tests/unit/api/test_concurrency_control.py | 244 ++++++++++++++++++ .../core/client/test_ssl_context_cache.py | 114 ++++++++ tests/unit/services/test_cleanup_scheduler.py | 88 +++++++ 5 files changed, 748 insertions(+) create mode 100644 tests/integration/api/test_concurrency_limits.py create mode 100644 tests/unit/api/test_concurrency_control.py create mode 100644 tests/unit/core/client/test_ssl_context_cache.py create mode 100644 tests/unit/services/test_cleanup_scheduler.py diff --git a/tests/integration/api/test_concurrency.py b/tests/integration/api/test_concurrency.py index 559cb9d..27f733f 100644 --- a/tests/integration/api/test_concurrency.py +++ b/tests/integration/api/test_concurrency.py @@ -9,6 +9,7 @@ from __future__ import annotations import asyncio +import os import socket import threading import time @@ -250,3 +251,121 @@ async def test_multiple_endpoints_concurrent(concurrency_server: str): f"Health checks blocked: max {max_health:.3f}s " f"({', '.join(f'{latency:.3f}' for latency in health_latencies)})" ) + + +@pytest.fixture(scope="module") +def deadline_server(): + """API server with a 1s scan deadline and a blocking analyze backend. + + The blocking backend never returns before the client releases it (up to + 10s), so the client receives 504 at ~1s while the worker keeps running. + This exercises the real ASGI request lifecycle under uvicorn (no + TestClient task-group teardown). + """ + from ciberwebscan.api import concurrency + from ciberwebscan.api.app import create_app + from ciberwebscan.api.auth import AuthenticatedUser, get_current_user + from ciberwebscan.config.loader import reset_config + + # The deadline is read per request via get_config(), and the autouse + # isolate_global_config fixture resets the config singleton before each + # test (this module-scoped fixture runs only once). An env var survives + # that reset because the loader re-reads env vars on every load, so the + # server keeps seeing the 1s deadline regardless of test ordering. + # The model requires scan_timeout_seconds >= 1.0. + os.environ["CIBERWEBSCAN_API_SCAN_TIMEOUT_SECONDS"] = "1" + reset_config() + concurrency.reset() + + app = create_app() + + def mock_user() -> AuthenticatedUser: + return AuthenticatedUser( + identifier="test-user", auth_method="api_key", scopes=["read"] + ) + + app.dependency_overrides[get_current_user] = mock_user + + release = threading.Event() + + def blocking_analyze(self, options): + # Hold the worker well past the 0.5s deadline so the 504 fires while + # the thread is still running, then raise a sentinel the client + # never sees (the request was already abandoned at the deadline). + release.wait(timeout=10) + raise RuntimeError("worker released after deadline (sentinel)") + + patcher = patch( + "ciberwebscan.api.routes.analyze.AnalyzeService.analyze", blocking_analyze + ) + patcher.start() + + port = _free_port() + base = f"http://127.0.0.1:{port}" + config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error") + server = uvicorn.Server(config) + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + + for _ in range(100): + if server.started: + break + time.sleep(0.05) + else: + patcher.stop() + pytest.fail("Deadline test server failed to start within 5s") + + try: + yield base, release + finally: + release.set() + server.should_exit = True + thread.join(timeout=5) + patcher.stop() + os.environ.pop("CIBERWEBSCAN_API_SCAN_TIMEOUT_SECONDS", None) + reset_config() + concurrency.reset() + + +@pytest.mark.network +@pytest.mark.asyncio +async def test_deadline_answers_504_and_slot_held_until_work_ends( + deadline_server: tuple[str, threading.Event], +): + """Under a real server: the 504 is answered at the deadline, but the + admission slot is NOT freed until the blocking worker thread truly ends + (honest accounting).""" + from ciberwebscan.api import concurrency + + base, release = deadline_server + controller = concurrency.get_controller() + + async with httpx.AsyncClient(base_url=base, timeout=10.0) as client: + start = time.perf_counter() + response = await client.post( + "/api/analyze", json={"url": "https://example.com", "ssl": True} + ) + elapsed = time.perf_counter() - start + + assert response.status_code == 504, ( + f"expected 504 at the 1s deadline, got {response.status_code}" + ) + # The 504 must come from the deadline (~1s), not from the worker's own + # bounded end (10s); leave headroom for request/CI latency. + assert elapsed < 2.5, f"504 was not answered at the deadline: {elapsed:.2f}s" + + # The worker is still blocked on `release`; immediately after the 504 the + # slot must still be held (no premature release). + assert controller.in_flight == 1, ( + f"slot was freed before the worker ended: in_flight={controller.in_flight}" + ) + + # Free the worker thread; the slot must be released once it truly ends. + release.set() + deadline = time.monotonic() + 4.0 + while time.monotonic() < deadline and controller.in_flight != 0: + await asyncio.sleep(0.1) + + assert controller.in_flight == 0, ( + f"slot never released after worker ended: in_flight={controller.in_flight}" + ) diff --git a/tests/integration/api/test_concurrency_limits.py b/tests/integration/api/test_concurrency_limits.py new file mode 100644 index 0000000..3a0fca3 --- /dev/null +++ b/tests/integration/api/test_concurrency_limits.py @@ -0,0 +1,183 @@ +""" +Integration tests for scan admission control under real concurrency (BUG-013). + +Unlike the older concurrency tests (which prove the event loop is not +blocked), these exercise the admission limit itself against a real uvicorn +server on 127.0.0.1 with a controlled blocking backend: + +- The excess beyond ``api.max_concurrent_scans`` is rejected with 429 + immediately (no unbounded queue). +- /health stays responsive while every scan slot is occupied. +- Capacity becomes usable again once the accepted scans really finish. +""" + +from __future__ import annotations + +import asyncio +import socket +import threading +import time +from collections.abc import Iterator +from unittest.mock import MagicMock, patch + +import httpx +import pytest +import uvicorn + +from ciberwebscan.api import concurrency +from ciberwebscan.export.models import AnalysisReport, ExportMeta + +pytestmark = pytest.mark.integration + +pytest.importorskip("fastapi") +pytest.importorskip("uvicorn") +pytest.importorskip("python_multipart") + + +def _free_port() -> int: + """Find an available port on localhost.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +@pytest.fixture +def saturation_server(monkeypatch) -> Iterator[tuple[str, threading.Event]]: + """Local API server with ``max_concurrent_scans=2`` and scans that block + on an event controlled by the test.""" + from ciberwebscan.api.app import create_app + from ciberwebscan.api.auth import AuthenticatedUser, get_current_user + from ciberwebscan.config.loader import reset_config + + monkeypatch.setenv("CIBERWEBSCAN_API_MAX_CONCURRENT_SCANS", "2") + reset_config() + concurrency.reset() + + release = threading.Event() + + def blocking_analyze(self, options): + release.wait(timeout=30) + result = MagicMock() + result.success = True + result.error = None + result.export_path = None + result.data = AnalysisReport(meta=ExportMeta(target_url=options.url)) + return result + + app = create_app() + + def mock_user() -> AuthenticatedUser: + return AuthenticatedUser( + identifier="test-user", auth_method="api_key", scopes=["read"] + ) + + app.dependency_overrides[get_current_user] = mock_user + + patcher = patch( + "ciberwebscan.api.routes.analyze.AnalyzeService.analyze", + blocking_analyze, + ) + patcher.start() + + port = _free_port() + base = f"http://127.0.0.1:{port}" + config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error") + server = uvicorn.Server(config) + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + + for _ in range(100): + if server.started: + break + time.sleep(0.05) + else: + patcher.stop() + pytest.fail("Saturation test server failed to start within 5s") + + try: + yield base, release + finally: + release.set() + server.should_exit = True + thread.join(timeout=5) + patcher.stop() + app.dependency_overrides.clear() + concurrency.reset() + + +async def _wait_in_flight(expected: int, timeout: float = 5.0) -> None: + """Poll the admission controller until in_flight reaches *expected*.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if concurrency.get_controller().in_flight == expected: + return + await asyncio.sleep(0.01) + raise AssertionError( + f"in_flight never reached {expected}: " + f"current={concurrency.get_controller().in_flight}" + ) + + +@pytest.mark.network +@pytest.mark.asyncio +async def test_saturation_rejects_early_and_health_stays_responsive( + saturation_server: tuple[str, threading.Event], +): + """With 2 slots and 3 scans: 2 run, the 3rd gets an immediate 429.""" + base, release = saturation_server + + async with httpx.AsyncClient(base_url=base, timeout=15.0) as client: + scan_tasks = [ + asyncio.create_task( + client.post("/api/analyze", json={"url": "https://example.com"}) + ) + for _ in range(2) + ] + await _wait_in_flight(2) + + # Both slots busy: /health must still answer promptly. + health_start = time.perf_counter() + health = await client.get("/health") + health_latency = time.perf_counter() - health_start + assert health.status_code == 200 + assert health_latency < 0.5, ( + f"/health blocked during saturation: {health_latency:.3f}s" + ) + + # The excess scan is rejected immediately, with a retry signal. + rejected = await client.post( + "/api/analyze", json={"url": "https://example.com"} + ) + assert rejected.status_code == 429 + assert rejected.headers.get("Retry-After") is not None + # Rejection must be fast (no queueing behind the blocked scans). + assert rejected.elapsed.total_seconds() < 1.0 + + # After the accepted scans finish, capacity is usable again. + release.set() + responses = await asyncio.gather(*scan_tasks) + assert [r.status_code for r in responses] == [200, 200] + await _wait_in_flight(0) + + follow_up = await client.post( + "/api/analyze", json={"url": "https://example.com"} + ) + assert follow_up.status_code == 200 + + +@pytest.mark.network +@pytest.mark.asyncio +async def test_admission_slot_released_after_failed_scan( + saturation_server: tuple[str, threading.Event], +): + """A scan that finishes with an error returns its slot immediately.""" + base, release = saturation_server + release.set() # scans complete immediately (successful path here) + + async with httpx.AsyncClient(base_url=base, timeout=15.0) as client: + for _ in range(3): + response = await client.post( + "/api/analyze", json={"url": "https://example.com"} + ) + assert response.status_code == 200 + await _wait_in_flight(0) diff --git a/tests/unit/api/test_concurrency_control.py b/tests/unit/api/test_concurrency_control.py new file mode 100644 index 0000000..e24fca5 --- /dev/null +++ b/tests/unit/api/test_concurrency_control.py @@ -0,0 +1,244 @@ +""" +Unit tests for scan admission control, deadlines and threadpool sizing (BUG-013). + +These tests pin the concurrency contract of the scan endpoints: + +- Admission rejects the excess with 429 instead of queueing unboundedly. +- A deadline answers 504 on time but keeps the admission slot until the + non-cancellable worker thread really finishes (no premature release). +- Slots are released on success, error and timeout. +- The shared AnyIO threadpool is sized from configuration at startup. +""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Iterator +from unittest.mock import MagicMock, patch + +import anyio.to_thread +import pytest +from fastapi.testclient import TestClient + +from ciberwebscan.api import concurrency +from ciberwebscan.api.app import create_app +from ciberwebscan.config.loader import reset_config +from ciberwebscan.export.models import AnalysisReport, ExportMeta + +pytestmark = pytest.mark.unit + + +@pytest.fixture(autouse=True) +def clean_concurrency_state() -> Iterator[None]: + """Isolate the module-level controller/limiter between tests.""" + concurrency.reset() + yield + concurrency.reset() + + +@pytest.fixture +def limit_one_scan(monkeypatch) -> None: + """Configure the app for at most one scan in flight.""" + monkeypatch.setenv("CIBERWEBSCAN_API_MAX_CONCURRENT_SCANS", "1") + reset_config() + + +@pytest.fixture +def one_second_deadline(monkeypatch) -> None: + """Configure a 1s scan deadline.""" + monkeypatch.setenv("CIBERWEBSCAN_API_SCAN_TIMEOUT_SECONDS", "1") + reset_config() + + +def _make_client() -> TestClient: + """Build an app + TestClient with authentication overridden.""" + from ciberwebscan.api.auth import AuthenticatedUser, get_current_user + + app = create_app() + + def mock_user() -> AuthenticatedUser: + return AuthenticatedUser( + identifier="test-user", auth_method="api_key", scopes=["read"] + ) + + app.dependency_overrides[get_current_user] = mock_user + return TestClient(app) + + +def _successful_result(url: str) -> MagicMock: + result = MagicMock() + result.success = True + result.error = None + result.export_path = None + result.data = AnalysisReport(meta=ExportMeta(target_url=url)) + return result + + +def _wait_in_flight(expected: int, timeout: float = 5.0) -> None: + """Poll the controller until in_flight reaches *expected*.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if concurrency.get_controller().in_flight == expected: + return + time.sleep(0.01) + raise AssertionError( + f"in_flight never reached {expected}: " + f"current={concurrency.get_controller().in_flight}" + ) + + +class TestScanAdmissionController: + """Pure unit tests for the admission counter.""" + + def test_acquire_up_to_limit(self): + controller = concurrency.ScanAdmissionController(2) + assert controller.try_acquire() is True + assert controller.try_acquire() is True + assert controller.try_acquire() is False + assert controller.in_flight == 2 + assert controller.limit == 2 + + def test_release_restores_capacity(self): + controller = concurrency.ScanAdmissionController(1) + assert controller.try_acquire() is True + controller.release() + assert controller.in_flight == 0 + assert controller.try_acquire() is True + + def test_release_without_acquire_is_ignored(self): + controller = concurrency.ScanAdmissionController(1) + controller.release() + assert controller.in_flight == 0 + + def test_limit_must_be_positive(self): + with pytest.raises(ValueError): + concurrency.ScanAdmissionController(0) + + +class TestScanAdmissionHTTP: + """Route-level behaviour of admission control and deadlines.""" + + def test_saturated_scan_rejected_with_429(self, limit_one_scan: None): + """The second concurrent scan gets 429 + Retry-After, not a queue.""" + started = threading.Event() + release = threading.Event() + + def blocking_analyze(self, options): + started.set() + release.wait(timeout=10) + return _successful_result(options.url) + + client = _make_client() + responses: list = [] + try: + with patch( + "ciberwebscan.api.routes.analyze.AnalyzeService.analyze", + blocking_analyze, + ): + first = threading.Thread( + target=lambda: responses.append( + client.post("/api/analyze", json={"url": "https://example.com"}) + ) + ) + first.start() + assert started.wait(timeout=5), "first scan never started" + + second = client.post( + "/api/analyze", json={"url": "https://example.com"} + ) + assert second.status_code == 429 + assert second.headers.get("Retry-After") is not None + + release.set() + first.join(timeout=10) + assert not first.is_alive() + assert responses[0].status_code == 200 + + # Capacity is reusable once the scan really finished. + _wait_in_flight(0) + finally: + release.set() + client.app.dependency_overrides.clear() + + def test_deadline_answers_504_but_slot_held_until_work_ends( + self, one_second_deadline: None + ): + """504 is answered on time; the slot is released only when the + blocking work actually finishes (honest accounting).""" + started = threading.Event() + release = threading.Event() + + def slow_analyze(self, options): + started.set() + release.wait(timeout=10) + return _successful_result(options.url) + + client = _make_client() + try: + with ( + patch( + "ciberwebscan.api.routes.analyze.AnalyzeService.analyze", + slow_analyze, + ), + # Used as a context manager so the underlying event loop + # (portal) stays alive across the request. Without it, + # TestClient tears the portal down per request and cancels + # the abandoned worker task, releasing the slot early — + # an artifact of the test harness, not of the design. + client, + ): + began = time.monotonic() + response = client.post( + "/api/analyze", json={"url": "https://example.com"} + ) + elapsed = time.monotonic() - began + + assert response.status_code == 504 + assert elapsed < 5, f"deadline did not fire promptly: {elapsed:.1f}s" + assert started.is_set() + + # The worker thread is still alive: the slot must NOT be free. + assert concurrency.get_controller().in_flight == 1 + + release.set() + _wait_in_flight(0, timeout=10) + finally: + release.set() + client.app.dependency_overrides.clear() + + def test_slot_released_after_scan_error(self, limit_one_scan: None): + """An exception inside the scan releases the admission slot.""" + + def failing_analyze(self, options): + raise RuntimeError("boom") + + client = _make_client() + try: + with patch( + "ciberwebscan.api.routes.analyze.AnalyzeService.analyze", + failing_analyze, + ): + response = client.post( + "/api/analyze", json={"url": "https://example.com"} + ) + assert response.status_code == 500 + _wait_in_flight(0) + finally: + client.app.dependency_overrides.clear() + + +class TestThreadpoolSizing: + """The shared AnyIO threadpool size comes from configuration.""" + + def test_default_limiter_sized_from_config(self, monkeypatch): + monkeypatch.setenv("CIBERWEBSCAN_API_SYNC_THREADPOOL_TOKENS", "7") + reset_config() + app = create_app() + with TestClient(app) as client: + limiter = client.portal.call(anyio.to_thread.current_default_thread_limiter) + assert limiter.total_tokens == 7 + + def test_scan_limiter_matches_configured_limit(self, limit_one_scan: None): + assert concurrency.get_scan_limiter().total_tokens == 1 + assert concurrency.get_controller().limit == 1 diff --git a/tests/unit/core/client/test_ssl_context_cache.py b/tests/unit/core/client/test_ssl_context_cache.py new file mode 100644 index 0000000..7fda57c --- /dev/null +++ b/tests/unit/core/client/test_ssl_context_cache.py @@ -0,0 +1,114 @@ +""" +Unit tests for the shared TLS context cache in HTTPClient (BUG-013). + +Building httpx's default verification context re-reads the whole CA bundle +on every client construction (hundreds of milliseconds). HTTPClient now +reuses one process-wide ``ssl.SSLContext`` per shape. These tests pin the +cache behaviour and its isolation rules (http2/ALPN, trust_env, SSL_CERT_*). +""" + +from __future__ import annotations + +import ssl +from collections.abc import Iterator + +import certifi +import pytest + +from ciberwebscan.core.client.http_client import ( + HTTPClient, + _shared_ssl_context, + _ssl_context_cache, +) + +pytestmark = pytest.mark.unit + + +@pytest.fixture(autouse=True) +def clear_ssl_cache() -> Iterator[None]: + _ssl_context_cache.clear() + yield + _ssl_context_cache.clear() + + +@pytest.fixture +def create_context_calls(monkeypatch) -> list: + """Record calls to ssl.create_default_context, passing through to it.""" + calls: list = [] + real_create = ssl.create_default_context + + def counting_create(*args, **kwargs): + calls.append({"args": args, "kwargs": kwargs}) + return real_create(*args, **kwargs) + + monkeypatch.setattr(ssl, "create_default_context", counting_create) + return calls + + +class TestSharedSslContext: + """Cache semantics of _shared_ssl_context.""" + + def test_same_shape_reuses_one_context(self, create_context_calls: list): + first = _shared_ssl_context(http2=True, trust_env=False) + second = _shared_ssl_context(http2=True, trust_env=False) + + assert first is not None + assert first is second + assert len(create_context_calls) == 1, ( + "the CA bundle must be loaded once per shape, not per client" + ) + assert create_context_calls[0]["kwargs"].get("cafile") == certifi.where() + + def test_http2_shapes_get_separate_contexts(self, create_context_calls: list): + """httpcore sets ALPN on the shared context per connection, so + HTTP/2 and HTTP/1.1-only clients must not share a context.""" + http2_ctx = _shared_ssl_context(http2=True, trust_env=False) + http1_ctx = _shared_ssl_context(http2=False, trust_env=False) + + assert http2_ctx is not None and http1_ctx is not None + assert http2_ctx is not http1_ctx + assert len(create_context_calls) == 2 + + def test_env_certs_ignored_without_trust_env( + self, create_context_calls: list, monkeypatch + ): + """SSL_CERT_FILE only matters under trust_env (httpx parity).""" + monkeypatch.setenv("SSL_CERT_FILE", "/nonexistent/cert.pem") + + context = _shared_ssl_context(http2=True, trust_env=False) + + assert context is not None + # Built from the certifi bundle, not from the env var. + assert create_context_calls[0]["kwargs"].get("cafile") == certifi.where() + assert (True, None, None) in _ssl_context_cache + assert (True, "/nonexistent/cert.pem", None) not in _ssl_context_cache + + def test_env_certs_honoured_under_trust_env( + self, create_context_calls: list, monkeypatch + ): + """Under trust_env the cache key includes the resolved env value.""" + + real_bundle = str(certifi.where()) + monkeypatch.setenv("SSL_CERT_FILE", real_bundle) + + context = _shared_ssl_context(http2=True, trust_env=True) + + assert context is not None + assert create_context_calls[0]["kwargs"].get("cafile") == real_bundle + assert (True, real_bundle, None) in _ssl_context_cache + + +class TestHTTPClientUsesSharedContext: + """HTTPClient construction goes through the cache.""" + + def test_verify_true_builds_context_once(self, create_context_calls: list): + with HTTPClient(verify=True) as first, HTTPClient(verify=True) as second: + assert first is not second + assert len(create_context_calls) == 1, ( + "second client must reuse the cached TLS context" + ) + + def test_verify_false_does_not_build_context(self, create_context_calls: list): + with HTTPClient(verify=False): + assert create_context_calls == [] + assert _ssl_context_cache == {} diff --git a/tests/unit/services/test_cleanup_scheduler.py b/tests/unit/services/test_cleanup_scheduler.py new file mode 100644 index 0000000..b84fc29 --- /dev/null +++ b/tests/unit/services/test_cleanup_scheduler.py @@ -0,0 +1,88 @@ +""" +Unit tests for the download cleanup scheduler (BUG-013). + +The scheduler used to call the (blocking) cleanup service directly on the +event loop, freezing every pending request for the duration of the sweep. +These tests pin that the cleanup work runs off the event loop. +""" + +from __future__ import annotations + +import asyncio +import threading +from collections.abc import Iterator +from unittest.mock import MagicMock, patch + +import pytest + +from ciberwebscan.services.cleanup_scheduler import DownloadCleanupScheduler + +pytestmark = pytest.mark.unit + + +@pytest.fixture +def fast_scheduler() -> Iterator[DownloadCleanupScheduler]: + """A scheduler with a 10ms interval and a mocked cleanup service. + + The mocked ``cleanup_expired_tokens`` records whether an event loop was + running in the thread that executed it. + """ + with ( + patch("ciberwebscan.services.cleanup_scheduler.get_config") as mock_config, + patch( + "ciberwebscan.services.cleanup_scheduler.DownloadService" + ) as mock_service_class, + ): + mock_config.return_value.download.cleanup_interval_seconds = 0.01 + + service = mock_service_class.return_value + state = {"loop_running": None, "calls": 0, "thread_id": None} + + def recording_cleanup(): + state["calls"] += 1 + state["thread_id"] = threading.get_ident() + try: + asyncio.get_running_loop() + except RuntimeError: + state["loop_running"] = False + else: + state["loop_running"] = True + result = MagicMock() + result.success = True + result.data = 0 + return result + + service.cleanup_expired_tokens.side_effect = recording_cleanup + scheduler = DownloadCleanupScheduler() + scheduler._test_state = state # type: ignore[attr-defined] + yield scheduler + scheduler.stop() + + +class TestCleanupSchedulerEventLoop: + """Cleanup must never execute on the event loop thread.""" + + @pytest.mark.asyncio + async def test_cleanup_runs_off_the_event_loop( + self, fast_scheduler: DownloadCleanupScheduler + ): + fast_scheduler.start() + assert fast_scheduler._running is True + + # Wait (deterministically polling the recorded state) for the + # first cleanup pass to happen off-loop. + state = fast_scheduler._test_state # type: ignore[attr-defined] + for _ in range(500): + if state["calls"] > 0: + break + await asyncio.sleep(0.01) + fast_scheduler.stop() + + assert state["calls"] > 0, "cleanup never ran" + assert state["loop_running"] is False, ( + "cleanup executed with a running event loop in its thread: " + "it would block the event loop (regression of BUG-013)" + ) + assert state["thread_id"] != threading.get_ident(), ( + "cleanup ran on the test's event-loop thread" + ) From 01ee55ffe570dcc1af4883b888d04c5916f1011b Mon Sep 17 00:00:00 2001 From: HC-ONLINE Date: Fri, 6 Nov 2026 13:41:14 -0500 Subject: [PATCH 6/6] docs(api): document scan concurrency limits, 429/504 semantics and config fields --- docs/API.md | 52 ++++++++++++++++++++++++++++++++++--------- docs/CONFIGURATION.md | 51 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 91 insertions(+), 12 deletions(-) diff --git a/docs/API.md b/docs/API.md index f6ba318..d839398 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1033,16 +1033,17 @@ All error responses include standardized error information: ### Common HTTP Status Codes -| Status | Meaning | -| ------ | -------------------------------------- | -| 200 | Success | -| 400 | Bad request (validation error) | -| 401 | Unauthorized (missing/invalid API key) | -| 403 | Forbidden (insufficient permissions) | -| 404 | Not found | -| 429 | Too many requests (rate limited) | -| 500 | Internal server error | -| 503 | Service unavailable | +| Status | Meaning | +| ------ | ----------------------------------------------------------- | +| 200 | Success | +| 400 | Bad request (validation error) | +| 401 | Unauthorized (missing/invalid API key) | +| 403 | Forbidden (insufficient permissions) | +| 404 | Not found | +| 429 | Too many requests (rate limited) or scan capacity exhausted | +| 500 | Internal server error | +| 503 | Service unavailable | +| 504 | Scan exceeded `api.scan_timeout_seconds` (deadline) | ## Configuration @@ -1063,6 +1064,11 @@ CIBERWEBSCAN_API_AUTH_SERVER_SECRET="" CIBERWEBSCAN_API_RATE_LIMIT_ENABLED=true CIBERWEBSCAN_API_RATE_LIMIT_REQUESTS_PER_MINUTE=60 +# Scan concurrency (admission, deadline, threadpool sizing) +CIBERWEBSCAN_API_MAX_CONCURRENT_SCANS=32 +CIBERWEBSCAN_API_SCAN_TIMEOUT_SECONDS=300 +CIBERWEBSCAN_API_SYNC_THREADPOOL_TOKENS=40 + # Client identification (reverse proxies allowed to set X-Forwarded-For) CIBERWEBSCAN_API_TRUSTED_PROXIES="127.0.0.1" @@ -1093,6 +1099,32 @@ The API includes rate limiting to prevent abuse: - **Per-client counter**: each client identity has its own bucket (see [Client identification](#client-identification-and-trusted-proxies) below) +### Scan concurrency + +Scan endpoints (`POST /api/analyze`, `/api/attack`, `/api/scrape`, +`/api/scrape/batch`, `/api/quick`) are long, blocking operations. They run +under a separate, per-process admission control that is distinct from the +per-client rate limiter: + +- **Admission limit**: at most `api.max_concurrent_scans` scans execute at + once per API process. Excess requests are rejected immediately with + **429** and a `Retry-After` header instead of queueing indefinitely. The + limit is per process — with `--workers N` the effective capacity is + `N × max_concurrent_scans`. +- **Deadline** (`api.scan_timeout_seconds`, default `null` = no deadline): + when set, the client is answered with **504** once the deadline elapses. + The blocking work cannot be cancelled mid-flight; it keeps running server + side until its own bounded end, and the admission slot stays held until + the worker thread truly finishes (capacity tracks real resource usage, + not the client's willingness to wait). Scans therefore never accumulate + unbounded behind a dead request. +- **Sizing**: scan work runs on a dedicated thread pool + (`api.sync_threadpool_tokens`) so scans cannot crowd out synchronous + dependencies (like auth) or streaming responses on the shared AnyIO + threadpool. + +See [CONFIGURATION.md](CONFIGURATION.md) for the full option reference. + ### Client identification and trusted proxies Clients are identified by their **connection peer address**. The diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 8423ace..0e8638d 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -79,6 +79,9 @@ Examples that work out of the box: - `CIBERWEBSCAN_ANALYSIS_CVE_NVD_API_KEY` → `analysis.cve.nvd_api_key` - `CIBERWEBSCAN_CACHE_MAX_SIZE_MB` → `cache.max_size_mb` - `CIBERWEBSCAN_API_RATE_LIMIT_REQUESTS_PER_MINUTE` → `api.rate_limit.requests_per_minute` +- `CIBERWEBSCAN_API_MAX_CONCURRENT_SCANS` → `api.max_concurrent_scans` (scan admission limit per process) +- `CIBERWEBSCAN_API_SCAN_TIMEOUT_SECONDS` → `api.scan_timeout_seconds` (scan deadline; must be >= 1 when set) +- `CIBERWEBSCAN_API_SYNC_THREADPOOL_TOKENS` → `api.sync_threadpool_tokens` - `CIBERWEBSCAN_API_TRUSTED_PROXIES` → `api.trusted_proxies` (comma-separated IPs/CIDRs) - `CIBERWEBSCAN_API_CORS_ORIGINS` → `api.cors_origins` - `CIBERWEBSCAN_API_CORS_ALLOW_CREDENTIALS` → `api.cors_allow_credentials` @@ -632,6 +635,9 @@ Configure the FastAPI server, authentication, and CORS settings. "api": { "host": "0.0.0.0", "port": 8000, + "max_concurrent_scans": 32, + "scan_timeout_seconds": null, + "sync_threadpool_tokens": 40, "auth": { "api_keys": ["your-api-key-1", "your-api-key-2"] }, @@ -655,6 +661,9 @@ Configure the FastAPI server, authentication, and CORS settings. | ------------------------------------ | --------: | ------------------------------------------------ | | `api.host` | `0.0.0.0` | API server bind address | | `api.port` | `8000` | API server port (1-65535) | +| `api.max_concurrent_scans` | `32` | Max scans in flight per process (1-256) | +| `api.scan_timeout_seconds` | `null` | Scan deadline in seconds (1-3600, `null` = off) | +| `api.sync_threadpool_tokens` | `40` | Dedicated scan threadpool size (1-512) | | `api.auth.api_keys` | `[]` | List of valid API keys for authentication | | `api.auth.server_secret` | `""` | Secret for HMAC log obfuscation only (see below) | | `api.rate_limit.enabled` | `true` | Rate limiting enabled by default | @@ -737,6 +746,41 @@ api: See also: [API.md — Authentication](API.md#authentication-1). +#### Scan concurrency + +The scan endpoints (`/api/analyze`, `/api/attack`, `/api/scrape`, +`/api/scrape/batch`, `/api/quick`) run blocking, non-cancellable work. Three +fields control how much of it a single API process will accept: + +- **`api.max_concurrent_scans`** (default `32`, range 1-256): admission limit + for in-flight scans. When the limit is reached, new scan requests are + rejected immediately with **429** and a `Retry-After` header instead of + queueing behind an unbounded backlog. The limit is **per process** — with + `--workers N` the effective capacity is `N × max_concurrent_scans`. + Changing it requires a restart (the controller is built at startup). +- **`api.scan_timeout_seconds`** (default `null` = no deadline, range + 1-3600): when set, a scan that exceeds the deadline is answered with + **504** while the blocking work keeps running server side until its own + bounded end (it cannot be cancelled mid-flight). The admission slot is + held until the worker thread truly finishes, so abandoned scans cannot + accumulate and free capacity they still consume. Read per request — + changes apply without a restart. +- **`api.sync_threadpool_tokens`** (default `40`, range 1-512): size of the + dedicated thread pool for scan work, so scans cannot crowd out synchronous + dependencies (like authentication) or streaming responses on the shared + AnyIO threadpool. Applied at startup. + +```yaml +api: + max_concurrent_scans: 32 + scan_timeout_seconds: 300 # optional deadline; omit (null) to disable + sync_threadpool_tokens: 40 +``` + +These limits are independent of the per-client HTTP rate limiter +(`api.rate_limit.*`): the rate limiter bounds request frequency per client, +while admission control bounds concurrent scan work per process. + #### CORS Security CORS (Cross-Origin Resource Sharing) controls which domains can access your API from a browser. The defaults are **secure by default**: @@ -1014,10 +1058,13 @@ configuration object in place, so every `get_config()` consumer sees them immedi - **Applied at next use (no restart):** `api.auth.api_keys` (API authentication is checked per request), `api.auth.server_secret` (log obfuscation only, read per request — the auto-generated default stays stable until the process restarts), `api.trusted_proxies` (client identity for - rate limiting and auth logs is resolved per request), and `download.require_same_user` (checked on + rate limiting and auth logs is resolved per request), `api.scan_timeout_seconds` (scan deadline + is read per request), and `download.require_same_user` (checked on every `GET /api/download/{token}`), HTTP client settings used when a client is created for a new operation, and scraping/analysis/attack defaults read per scan. -- **Require a restart:** `api.cors.*`, `api.rate_limit.*`, `download.cleanup_interval_seconds`, +- **Require a restart:** `api.cors.*`, `api.rate_limit.*`, `api.max_concurrent_scans` and + `api.sync_threadpool_tokens` (the admission controller and the scan threadpool are sized at + startup), `download.cleanup_interval_seconds`, `logging.*` handler configuration, and the API server `host`/`port` — these are captured once at startup (app creation, scheduler start, logging setup, server launch).