diff --git a/AGENTS.md b/AGENTS.md index 43a7759..3e1317a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -449,7 +449,6 @@ def test_analyze_route(mock_service_class): | URL validators | `src/ciberwebscan/utils/validators.py` | | Cleanup scheduler | `src/ciberwebscan/services/cleanup_scheduler.py` | | Example profiles | `examples/profiles/` (bugbounty, pentest, recon, stealth) | -| Manual API tests | `scripts/apiManualTest/` | | Unit tests | `tests/unit/` | | Integration tests | `tests/integration/` | | Shared fixtures | `tests/conftest.py` | diff --git a/tests/integration/api/conftest.py b/tests/integration/api/conftest.py index 2bbff8d..5011eed 100644 --- a/tests/integration/api/conftest.py +++ b/tests/integration/api/conftest.py @@ -14,28 +14,61 @@ import httpx import pytest +from ciberwebscan.config.loader import reset_config + pytest.importorskip("fastapi") pytest.importorskip("uvicorn") pytest.importorskip("python_multipart") -# Ensure API key auth is configured before any config is loaded -os.environ.setdefault( - "CIBERWEBSCAN_API_AUTH_API_KEYS", "test-api-key-cwscan-integration" -) -os.environ.setdefault("CIBERWEBSCAN_ATTACK_ENABLED", "true") -os.environ.setdefault("CIBERWEBSCAN_ATTACK_ALLOW_LOCAL", "true") - -# Force config reload so env vars take effect -from ciberwebscan.config.loader import reset_config - -reset_config() +# Test-relevant environment for this suite, applied by the module-scoped +# integration_env fixture below instead of at import time: pytest +# collects the whole tree even when integration tests are deselected +# (CI runs -m "not integration"), so import-time pins would leak into +# unit tests sharing the process — e.g. scraping allow_local would make +# the SSRF unit tests attempt real connections instead of validating. +_INTEGRATION_ENV: dict[str, str] = { + "CIBERWEBSCAN_API_AUTH_API_KEYS": "test-api-key-cwscan-integration", + "CIBERWEBSCAN_ATTACK_ENABLED": "true", + "CIBERWEBSCAN_ATTACK_ALLOW_LOCAL": "true", + # Quick/analysis/scrape integration tests scan a controlled loopback + # target (test_api_quick.py): opt local targets in per module so the + # SSRF policy still applies everywhere else. + "CIBERWEBSCAN_ANALYSIS_ALLOW_LOCAL": "true", + "CIBERWEBSCAN_SCRAPING_ALLOW_LOCAL": "true", + # Rate limiting is behaviour under test (test_api_robustness.py): + # pin it enabled so a local ~/.ciberwebscan/config.yaml cannot + # silently remove the middleware. The limit VALUE is left to the + # effective test configuration and read dynamically by the test. + "CIBERWEBSCAN_API_RATE_LIMIT_ENABLED": "true", +} API_SERVER_PORT = 5556 API_SERVER_URL = f"http://127.0.0.1:{API_SERVER_PORT}" +@pytest.fixture(scope="module", autouse=True) +def integration_env(): + """Pin test-relevant environment variables for one integration module. + + Restores the previous values and reloads the config on teardown so + the pins cannot bleed into other suites running in the same pytest + process. + """ + saved = {key: os.environ.get(key) for key in _INTEGRATION_ENV} + for key, value in _INTEGRATION_ENV.items(): + os.environ.setdefault(key, value) + reset_config() + yield + for key, value in saved.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + reset_config() + + @pytest.fixture(scope="module") -def api_server(): +def api_server(integration_env): """Start CiberWebScan API server for integration tests.""" cmd = [ sys.executable, @@ -84,7 +117,7 @@ def api_client(api_server: str) -> httpx.Client: @pytest.fixture(scope="module") -def auth_headers() -> dict[str, str]: +def auth_headers(integration_env) -> dict[str, str]: """Get auth headers using the first configured API key.""" from ciberwebscan.config.loader import get_config diff --git a/tests/integration/api/test_api_quick.py b/tests/integration/api/test_api_quick.py new file mode 100644 index 0000000..51adfbe --- /dev/null +++ b/tests/integration/api/test_api_quick.py @@ -0,0 +1,132 @@ +""" +Integration tests for the quick endpoint (POST /api/quick/scan). + +Runs against the real Uvicorn server: routing, middleware, auth, request +validation, QuickService, AnalyzeService and ScrapeService execute for +real. The only stand-in is a controlled loopback target HTTP server +(reproducible, no external services) that counts the requests the scan +actually makes; there are no service-level mocks. + +Note: with ``selector`` the scrape phase runs real requests but its +structured result is a list, which QuickService does not embed in +``report.scrape`` (selector mode); the round trip is therefore asserted +against the target's request counter. + +Covers: quick endpoint coverage lost with the manual scripts (see +backup/stash-api-manual-52cc50e). +""" + +from __future__ import annotations + +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +import httpx +import pytest + +pytestmark = pytest.mark.integration + +pytest.importorskip("fastapi") +pytest.importorskip("uvicorn") + +_TARGET_HTML = ( + b"Integration Target" + b"quick-scan-target-marker" +) + + +class _TargetHandler(BaseHTTPRequestHandler): + """Minimal local target that serves fixed HTML and counts requests.""" + + request_count = 0 + + def do_GET(self) -> None: + _TargetHandler.request_count += 1 + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.send_header("Content-Length", str(len(_TARGET_HTML))) + self.end_headers() + self.wfile.write(_TARGET_HTML) + + def do_POST(self) -> None: + self.do_GET() + + def log_message(self, format: str, *args: object) -> None: # noqa: A002 + pass # Suppress request logs during tests + + +@pytest.fixture(scope="module") +def target_server() -> str: + """Start a controlled loopback HTTP server as scan target. + + Returns the base URL (e.g. ``http://127.0.0.1:``). + """ + server = HTTPServer(("127.0.0.1", 0), _TargetHandler) + host, port = server.server_address + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://{host}:{port}" + server.shutdown() + + +@pytest.mark.network +class TestQuickScanEndpoint: + """Functional tests for POST /api/quick/scan over real HTTP.""" + + def test_quick_scan_low_runs_real_services( + self, api_client: httpx.Client, auth_headers: dict, target_server: str + ) -> None: + """A low-preset scan really analyses the local target end to end.""" + payload = { + "url": f"{target_server}/", + "preset": "low", + "selector": "body", + } + response = api_client.post( + "/api/quick/scan", json=payload, headers=auth_headers, timeout=60 + ) + assert response.status_code == 200 + + body = response.json() + assert body["success"] is True + assert body["preset"] == "low" + assert isinstance(body["warnings"], list) + assert body["duration_seconds"] > 0 + + data = body["data"] + assert data is not None + + # The report points at the target that was requested. + assert data["meta"]["target_url"].rstrip("/") == target_server + + # Analysis really ran against the local target: an http:// URL + # yields an SSL result without TLS, and fingerprint/headers + # results come from real requests to the target above. + assert data["ssl"] is not None + assert data["ssl"]["is_https"] is False + assert data["fingerprint"] is not None + assert isinstance(data["headers"]["findings"], list) + + # Proof of a real network round trip: the scan reached the target + # (consent/auth failures below never produce target requests). + assert _TargetHandler.request_count >= 1 + + def test_quick_scan_medium_requires_consent( + self, api_client: httpx.Client, auth_headers: dict, target_server: str + ) -> None: + """Medium preset without consent fails fast with 400 CONSENT_REQUIRED.""" + payload = {"url": f"{target_server}/", "preset": "medium"} + response = api_client.post( + "/api/quick/scan", json=payload, headers=auth_headers + ) + assert response.status_code == 400 + detail = response.json()["detail"] + assert detail["error_code"] == "CONSENT_REQUIRED" + + def test_quick_scan_requires_api_key( + self, api_client: httpx.Client, target_server: str + ) -> None: + """Requests without a key are rejected before any scan work.""" + payload = {"url": f"{target_server}/", "preset": "low"} + response = api_client.post("/api/quick/scan", json=payload) + assert response.status_code == 401 diff --git a/tests/integration/api/test_api_robustness.py b/tests/integration/api/test_api_robustness.py index 108312c..91a1b6d 100644 --- a/tests/integration/api/test_api_robustness.py +++ b/tests/integration/api/test_api_robustness.py @@ -1,15 +1,20 @@ """ Integration tests for API robustness. -Covers: test_api_robustness.py (corrupt JSON handling). -Rate limiting tests are in tests/unit/api/test_middleware.py. +Covers: test_api_robustness.py (corrupt JSON handling, rate limit burst). +Rate limiting unit logic lives in tests/unit/api/test_middleware.py; +enforcement end-to-end over real HTTP is asserted here. """ from __future__ import annotations +import time + import httpx import pytest +from ciberwebscan.config.loader import get_config + pytestmark = pytest.mark.integration pytest.importorskip("fastapi") @@ -31,3 +36,99 @@ def test_corrupt_json_returns_422(self, api_server: str): timeout=10, ) assert response.status_code == 422 + + +@pytest.mark.network +class TestRateLimitingOverHttp: + """End-to-end rate limiting through the real middleware. + + Runs against the module-scoped uvicorn server, so this file owns an + isolated process and therefore an isolated in-memory rate-limit + counter (all requests come from the peer ``127.0.0.1`` and share one + bucket). The burst size is derived from the effective test + configuration instead of assuming a fixed number of requests, and the + assertions are guarded against the wall-clock minute boundary so the + result does not depend on landing exactly on a window edge. + """ + + def test_burst_beyond_limit_gets_429_with_retry_after( + self, api_server: str + ) -> None: + config = get_config() + assert config.api.rate_limit.enabled, ( + "rate limiting must stay enabled in the integration environment" + ) + limit = config.api.rate_limit.requests_per_minute + + # Worst case: the minute window rotates once mid-burst and the + # whole limit has to be consumed again. Two full windows plus a + # small margin bound the loop without hardcoding e.g. "70". + max_requests = 2 * limit + 10 + allowed = 0 + first_allowed: httpx.Response | None = None + limited: httpx.Response | None = None + + started = time.time() + with httpx.Client(base_url=api_server, timeout=10.0) as client: + for _ in range(max_requests): + response = client.get("/health") + if response.status_code == 429: + limited = response + break + assert response.status_code == 200, ( + "requests under the limit must honour the endpoint " + f"contract, got {response.status_code}" + ) + if first_allowed is None: + first_allowed = response + allowed += 1 + ended = time.time() + + assert limited is not None, ( + f"no 429 after {allowed} requests although the configured " + f"limit is {limit}: rate limiting is not being enforced" + ) + + # Observable contract of the limited response. + assert "Retry-After" in limited.headers, ( + "429 responses must advertise Retry-After" + ) + retry_after_raw = limited.headers["Retry-After"] + assert retry_after_raw.isdigit(), ( + f"Retry-After must be an integer number of seconds, " + f"got {retry_after_raw!r}" + ) + retry_after = int(retry_after_raw) + assert 1 <= retry_after <= 60 + + # Rejected requests do not reset the counter: still limited in + # the same window. Guarded against the rare case where the + # window boundary arrives within the next couple of seconds. + if retry_after > 2: + again = client.get("/health") + assert again.status_code == 429, ( + "a rejected client must stay limited until the window ends" + ) + assert "Retry-After" in again.headers + + # Allowed requests answered according to the /health contract. + assert first_allowed is not None and allowed >= 1, ( + "expected at least one request to be served before the limit; " + "an earlier test may have exhausted this window's budget" + ) + health = first_allowed.json() + assert health["status"] == "healthy" + assert isinstance(health["version"], str) + + # Within a single window the middleware must not admit more than + # the configured limit. If the wall-clock minute rotated mid-test + # the counter legitimately reset, so the bound only holds when the + # burst stayed inside one window. + if int(started // 60) == int(ended // 60): + assert allowed <= limit, ( + f"admitted {allowed} requests although the limit is {limit}" + ) + + body = limited.json() + assert isinstance(body.get("error"), str) + assert body.get("retry_after_seconds") == retry_after