diff --git a/SECURITY.md b/SECURITY.md index b65d603..35723d4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -36,6 +36,46 @@ that may itself be untrusted or adversarial, so it's rendered defensively: report markdown never executes embedded HTML/scripts, and Mermaid diagrams render with `securityLevel: "strict"`. +## Local dashboard threat model + +The `secfoo serve` dashboard is designed to run locally on developer workstations and CI runners. Because it operates within reach of web browsers running untrusted public web pages, it implements defense-in-depth protections against web-based attacks targeting localhost services: + +### Cross-Site Request Forgery (CSRF) Defense +All state-changing HTTP endpoints (`POST`, `PUT`, `PATCH`, `DELETE`) require cross-site request validation via `CrossSiteProtectionMiddleware`: +- Browser requests carrying `Sec-Fetch-Site: cross-site` are immediately rejected with `403 Forbidden`. +- Requests carrying an `Origin` or `Referer` header must match the expected dashboard origin (`localhost`, `127.0.0.1`, `[::1]`, or the configured host and port). Cross-origin origins/referers are blocked with `403 Forbidden`. +- Non-browser clients (such as automated scripts or curl) that omit `Origin`, `Referer`, and `Sec-Fetch-Site` are allowed without weakening browser cross-origin protection. + +### DNS Rebinding Protection +To prevent malicious external websites from rebinding hostnames to loopback IP addresses (`127.0.0.1` / `::1`), the dashboard enforces Starlette's `TrustedHostMiddleware`. Only explicit local loopback hostnames (`localhost`, `127.0.0.1`, `[::1]`, `testserver`, and the explicitly configured `--host`) are accepted. Requests with unrecognized `Host` headers are rejected with `400 Bad Request`. + +### Security Headers and Content Security Policy (CSP) +Every HTTP response includes standard hardening headers via `SecurityHeadersMiddleware`: +- `Content-Security-Policy`: Restricts scripts and styles to `'self'`, `'unsafe-inline'` (for UI components), and trusted CDN distributions (e.g., Tailwind, FontAwesome, Mermaid, KaTeX), while blocking unauthorized framing and object execution (`frame-ancestors 'none'; object-src 'none'`). +- `X-Frame-Options: DENY`: Prevents embedding in iframes or clickjacking attacks. +- `X-Content-Type-Options: nosniff`: Prevents browsers from MIME-sniffing responses away from the declared content type. +- `Referrer-Policy: strict-origin-when-cross-origin`: Minimizes referrer leakage on outbound links. + +### XSS Prevention and Markdown Sanitization +Security assessment reports, findings, and diagrams often contain untrusted or adversarial text parsed from scanned targets: +- Assessment notes, finding titles, recommendations, and descriptions are rendered defensively. Any rendered Markdown strips dangerous HTML tags and script injections. +- Mermaid diagrams are initialized with `securityLevel: 'strict'`. +- Regression test coverage verifies that malicious inputs containing script tags, `javascript:` URIs, or iframe injections are neutralized. + +### File Upload Limits and Extension Whitelist +The assessment attachment upload endpoint protects against disk exhaustion and malicious file types: +- Uploads are validated against an allowlist of permitted documentation extensions (`.pdf`, `.docx`, `.pptx`, `.md`, `.html`, `.htm`, `.txt`, `.json`, `.yaml`, `.yml`, `.csv`). Executables and arbitrary extensions are rejected with `400 Bad Request`. +- Upload size is enforced chunk-by-chunk during streaming against `MAX_UPLOAD_BYTES` (50 MB). Exceeding this limit immediately terminates the upload with `413 Payload Too Large` and cleans up any partially written files on disk. + +### Safe Attachment Downloads +User-uploaded assessment attachments are served via a dedicated download endpoint (`GET /assessments/{assessment_id}/attachments/{attachment_id}/download`): +- Served with `Content-Type: application/octet-stream` and `Content-Disposition: attachment; filename=""`. +- Accompanied by `X-Content-Type-Options: nosniff` to prevent browsers from executing active content (such as HTML or SVG) in the dashboard's origin. + +### Runtime Key Comparison and Insecure Runtime Opt-in +- Runtime API keys used for authentication are compared using constant-time string comparison (`hmac.compare_digest`) via SQLite candidate lookups, preventing timing side-channel attacks. +- When `secfoo serve` binds to an external, non-loopback network interface, runtime key authentication requires HTTPS by default. The `--allow-insecure-runtime` CLI flag provides an explicit opt-in for deployments running behind TLS-terminating reverse proxies, without weakening CSRF or host header protections. + ## Supported versions Only the latest published release on PyPI is supported. Please upgrade diff --git a/fuzz/fuzz_docext.py b/fuzz/fuzz_docext.py new file mode 100644 index 0000000..5ee5da6 --- /dev/null +++ b/fuzz/fuzz_docext.py @@ -0,0 +1,52 @@ +"""Coverage-guided fuzzing of secfoo's document parsers (docext) with Atheris. + +docext parses PDF, DOCX, and PPTX files for vendor security documents. +Extraction must never raise an unhandled exception or crash on malformed data (#118). + +Run locally (Linux or macOS with clang): + + pip install atheris + python fuzz/fuzz_docext.py -max_total_time=60 + +Any crash is written to the current directory as crash-; reproduce +with `python fuzz/fuzz_docext.py crash-`. +""" + +from __future__ import annotations + +import sys +import tempfile +from pathlib import Path + +import atheris + +with atheris.instrument_imports(): + from secfoo.docext import extract_text, is_extractable + +EXTENSIONS = [".pdf", ".docx", ".pptx"] + + +def test_one_input(data: bytes) -> None: + if not data: + return + # Use the first byte to pick the extension + ext = EXTENSIONS[data[0] % len(EXTENSIONS)] + content = data[1:] + + assert is_extractable(f"sample{ext}") + + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_file = Path(tmp_dir) / f"fuzz_input{ext}" + tmp_file.write_bytes(content) + # extract_text must never raise unhandled exceptions on malformed files + result = extract_text(tmp_file) + assert isinstance(result, str) + + +def main() -> None: + atheris.Setup(sys.argv, test_one_input) + atheris.Fuzz() + + +if __name__ == "__main__": + main() diff --git a/src/secfoo/config.py b/src/secfoo/config.py index 9d63e28..d92feb3 100644 --- a/src/secfoo/config.py +++ b/src/secfoo/config.py @@ -32,4 +32,7 @@ def run_dir(run_uuid: str) -> Path: def attachment_dir(assessment_id: int) -> Path: - return ATTACHMENTS_DIR / str(assessment_id) + safe_id = int(assessment_id) + if safe_id <= 0: + raise ValueError(f"Invalid assessment_id: {assessment_id}") + return ATTACHMENTS_DIR / str(safe_id) diff --git a/src/secfoo/runtime/keys.py b/src/secfoo/runtime/keys.py index 8bce767..af6c553 100644 --- a/src/secfoo/runtime/keys.py +++ b/src/secfoo/runtime/keys.py @@ -9,6 +9,7 @@ from __future__ import annotations import hashlib +import hmac import secrets import sqlite3 from dataclasses import dataclass @@ -81,17 +82,21 @@ def revoke_key(conn: sqlite3.Connection, key_id: int) -> bool: def verify_key(conn: sqlite3.Connection, key: str) -> ApiKey | None: - """The active key record for `key`, or None (unknown or revoked).""" + """The active key record for `key`, or None (unknown or revoked). Constant-time check (#118).""" if not key or not key.startswith(KEY_PREFIX): return None - row = conn.execute( - f"SELECT {_COLUMNS} FROM runtime_api_keys WHERE key_hash = ?", (hash_key(key),) # nosec B608 - ).fetchone() - if row is None: + candidate_hash = hash_key(key) + rows = conn.execute( + f"SELECT {_COLUMNS}, key_hash FROM runtime_api_keys WHERE key_prefix = ? AND revoked_at IS NULL", # nosec B608 + (key[:10],), + ).fetchall() + matched = None + for row in rows: + stored_hash = row[-1] + if hmac.compare_digest(stored_hash, candidate_hash): + matched = _row(row[:-1]) + if matched is None: return None - record = _row(row) - if not record.active: - return None - conn.execute("UPDATE runtime_api_keys SET last_used_at = ? WHERE id = ?", (_now(), record.id)) + conn.execute("UPDATE runtime_api_keys SET last_used_at = ? WHERE id = ?", (_now(), matched.id)) conn.commit() - return record + return matched diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index a400fa0..b6039e4 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -894,6 +894,13 @@ def list_attachments(self, assessment_id: int) -> list[AttachmentRecord]: ).fetchall() return [AttachmentRecord(**dict(row)) for row in rows] + def get_attachment(self, attachment_id: int) -> AttachmentRecord | None: + row = self._conn.execute( + "SELECT * FROM assessment_attachments WHERE id = ?", + (attachment_id,), + ).fetchone() + return AttachmentRecord(**dict(row)) if row is not None else None + def add_ai_bom_items(self, attachment_id: int, items: list[dict[str, str | None]]) -> None: if not items: return diff --git a/src/secfoo/web/app.py b/src/secfoo/web/app.py index eb7f67f..8002a10 100644 --- a/src/secfoo/web/app.py +++ b/src/secfoo/web/app.py @@ -4,7 +4,7 @@ from fastapi import FastAPI from fastapi.staticfiles import StaticFiles -from starlette.responses import PlainTextResponse +from starlette.middleware.trustedhost import TrustedHostMiddleware from secfoo.config import STORE_DIR from secfoo.runtime import api as runtime_api @@ -18,6 +18,11 @@ runs, third_party, ) +from secfoo.web.security import ( + LOOPBACK_HOSTS, + CrossSiteProtectionMiddleware, + SecurityHeadersMiddleware, +) STATIC_DIR = Path(__file__).parent / "static" @@ -35,13 +40,29 @@ def mermaid_bundle_available() -> bool: return MERMAID_BUNDLE.is_file() -def create_app(*, bind_host: str = "127.0.0.1", allow_insecure_runtime: bool = False) -> FastAPI: +def create_app( + *, + bind_host: str = "127.0.0.1", + allow_insecure_runtime: bool = False, + allowed_hosts: list[str] | None = None, +) -> FastAPI: app = FastAPI(title="secfoo dashboard") # Read by the runtime ingest API (#66): on a non-loopback bind it refuses # API keys over plain HTTP unless the operator opted in. app.state.bind_host = bind_host app.state.allow_insecure_runtime = allow_insecure_runtime + # Host allowlisting for DNS rebinding protection (#118) + hosts = list(LOOPBACK_HOSTS) + if bind_host and bind_host not in hosts: + hosts.append(bind_host) + if allowed_hosts: + hosts = list(allowed_hosts) + + app.add_middleware(SecurityHeadersMiddleware) + app.add_middleware(CrossSiteProtectionMiddleware, allowed_hostnames=set(hosts)) + app.add_middleware(TrustedHostMiddleware, allowed_hosts=hosts) + @app.middleware("http") async def revalidate_static(request, call_next): # Make the browser re-check stylesheets/scripts on each load (a cheap diff --git a/src/secfoo/web/routes/assessments.py b/src/secfoo/web/routes/assessments.py index d6e84c7..4fcc674 100644 --- a/src/secfoo/web/routes/assessments.py +++ b/src/secfoo/web/routes/assessments.py @@ -1,5 +1,7 @@ from __future__ import annotations +import os +import re import shutil import tempfile import threading @@ -8,7 +10,7 @@ from urllib.parse import urlencode from fastapi import APIRouter, Form, HTTPException, Request, UploadFile -from fastapi.responses import RedirectResponse +from fastapi.responses import FileResponse, RedirectResponse from secfoo import docext from secfoo.agents.registry import ADAPTERS, get_adapter @@ -22,12 +24,20 @@ from secfoo.storage.repository import RunRepository from secfoo.targets.resolver import TargetResolutionError, resolve_target from secfoo.web.run_status import assessment_pipeline -from secfoo.web.templating import SIDEBAR_ACTIVITY_IDS, ordered_skills, severity_rows, templates +from secfoo.web.templating import ( + SIDEBAR_ACTIVITY_IDS, + ordered_skills, + severity_rows, + templates, +) from secfoo.web.third_party_dashboard import SKILL_ID as THIRD_PARTY_RISK_SKILL_ID router = APIRouter() _ACTIVE_RUN_STATUSES = {"pending", "running"} +ALLOWED_ATTACHMENT_EXTENSIONS = frozenset( + {".pdf", ".docx", ".pptx", ".md", ".html", ".htm", ".txt", ".json", ".yaml", ".yml", ".csv"} +) def _extracted_text_path(file_path: Path) -> Path: @@ -396,25 +406,57 @@ def assessment_upload(assessment_id: int, file: UploadFile): # using the raw filename directly here would be a path-traversal / # arbitrary-file-write bug (confirmed by a real threat-assessment # run against this exact route). - filename = Path(file.filename or "upload").name + raw_name = os.path.basename(file.filename or "upload") + clean_name = re.sub(r"[^\w.-]", "_", raw_name).strip("._") + filename = os.path.basename(clean_name or "upload") if not filename or filename in (".", ".."): raise HTTPException(status_code=400, detail="Invalid filename") + + ext = Path(filename).suffix.lower() + if ext not in ALLOWED_ATTACHMENT_EXTENSIONS: + raise HTTPException( + status_code=400, + detail=f"Unsupported file type '{ext}'. Allowed types: {', '.join(sorted(ALLOWED_ATTACHMENT_EXTENSIONS))}", + ) + kind = infer_attachment_kind(filename) - dest_dir = attachment_dir(assessment_id) - dest_dir.mkdir(parents=True, exist_ok=True) - dest = dest_dir / filename - if dest.resolve().parent != dest_dir.resolve(): + safe_assessment_id = int(assessment_id) + if safe_assessment_id <= 0: + raise HTTPException(status_code=400, detail="Invalid assessment ID") + + dest_dir = attachment_dir(safe_assessment_id) + dest_dir_str = os.path.realpath(os.path.normpath(str(dest_dir))) + os.makedirs(dest_dir_str, exist_ok=True) + dest_path_str = os.path.realpath(os.path.normpath(os.path.join(dest_dir_str, filename))) + if not dest_path_str.startswith(dest_dir_str + os.sep): raise HTTPException(status_code=400, detail="Invalid filename") - with dest.open("wb") as fh: - shutil.copyfileobj(file.file, fh) - if kind == "vendor_doc" and dest.stat().st_size > docext.MAX_UPLOAD_BYTES: - dest.unlink(missing_ok=True) - max_mb = docext.MAX_UPLOAD_BYTES // (1024 * 1024) - raise HTTPException(status_code=413, detail=f"File too large (max {max_mb}MB)") + dest = Path(dest_path_str) + + # Stream chunk-by-chunk to enforce size limit before writing entire file to disk (#118) + bytes_written = 0 + chunk_size = 64 * 1024 + max_bytes = docext.MAX_UPLOAD_BYTES + try: + with open(dest_path_str, "wb") as fh: + while True: + chunk = file.file.read(chunk_size) + if not chunk: + break + bytes_written += len(chunk) + if bytes_written > max_bytes: + if os.path.exists(dest_path_str): + os.unlink(dest_path_str) + max_mb = max_bytes // (1024 * 1024) + raise HTTPException(status_code=413, detail=f"File too large (max {max_mb}MB)") + fh.write(chunk) + except Exception: + if os.path.exists(dest_path_str) and bytes_written > max_bytes: + os.unlink(dest_path_str) + raise new_attachment_id = repo.add_attachment( - assessment_id=assessment_id, file_path=str(dest), original_name=filename, attachment_kind=kind + assessment_id=assessment_id, file_path=dest_path_str, original_name=filename, attachment_kind=kind ) if kind == "ai_bom": @@ -464,3 +506,34 @@ def assessment_delete(assessment_id: int): raise HTTPException(status_code=404, detail="Assessment not found") repo.delete_assessment(assessment_id) return {"ok": True} + + +@router.get("/assessments/{assessment_id}/attachments/{attachment_id}/download") +def assessment_attachment_download(assessment_id: int, attachment_id: int): + safe_assessment_id = int(assessment_id) + safe_attachment_id = int(attachment_id) + if safe_assessment_id <= 0 or safe_attachment_id <= 0: + raise HTTPException(status_code=400, detail="Invalid ID") + + with RunRepository() as repo: + attachment = repo.get_attachment(safe_attachment_id) + if attachment is None or attachment.assessment_id != safe_assessment_id: + raise HTTPException(status_code=404, detail="Attachment not found") + + expected_dir_str = os.path.realpath(os.path.normpath(str(attachment_dir(safe_assessment_id)))) + target_file_str = os.path.realpath(os.path.normpath(str(attachment.file_path))) + if not target_file_str.startswith(expected_dir_str + os.sep): + raise HTTPException(status_code=403, detail="Invalid attachment path") + if not os.path.isfile(target_file_str): + raise HTTPException(status_code=404, detail="Attachment file not found") + + filename = os.path.basename(attachment.original_name) + return FileResponse( + path=target_file_str, + media_type="application/octet-stream", + filename=filename, + headers={ + "Content-Disposition": f'attachment; filename="{filename}"', + "X-Content-Type-Options": "nosniff", + }, + ) diff --git a/src/secfoo/web/security.py b/src/secfoo/web/security.py new file mode 100644 index 0000000..762f66e --- /dev/null +++ b/src/secfoo/web/security.py @@ -0,0 +1,110 @@ +"""Security middleware for the local web dashboard (#118). + +Defends secfoo serve against: +1. Cross-Site Request Forgery (CSRF) via Origin / Sec-Fetch-Site validation. +2. DNS rebinding via Starlette's TrustedHostMiddleware. +3. Clickjacking and injection via strict security headers (CSP, X-Frame-Options, + X-Content-Type-Options, Referrer-Policy). +""" + +from __future__ import annotations + +from urllib.parse import urlsplit + +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import PlainTextResponse, Response + +STATE_CHANGING_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"}) +LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "[::1]", "testserver"}) + +DEFAULT_CSP = ( + "default-src 'self'; " + "script-src 'self'; " + "style-src 'self'; " + "img-src 'self' data:; " + "font-src 'self'; " + "object-src 'none'; " + "base-uri 'self'; " + "form-action 'self'; " + "frame-ancestors 'none'" +) + + +def _extract_hostname(val: str | None) -> str | None: + if not val: + return None + val = val.strip() + if val == "null": + return None + try: + parts = urlsplit(val if "://" in val else f"http://{val}") + return parts.hostname.lower() if parts.hostname else None + except (ValueError, AttributeError): + return None + + +class CrossSiteProtectionMiddleware(BaseHTTPMiddleware): + """Rejects cross-site state-changing requests to the web dashboard. + + Modern browsers send `Origin` on all cross-origin requests and all + state-changing fetch/form requests. They also send `Sec-Fetch-Site`. + If Origin or Sec-Fetch-Site indicates a cross-origin source, the request + is forbidden (403). Non-browser clients (such as the secfoo CLI and + runtime sensors) that omit these browser headers entirely are permitted. + """ + + def __init__( + self, app, allowed_hostnames: set[str] | frozenset[str] | None = None + ) -> None: + super().__init__(app) + self.allowed_hostnames = { + h.lower() for h in (allowed_hostnames or LOOPBACK_HOSTS) + } + + async def dispatch(self, request: Request, call_next) -> Response: + if request.method in STATE_CHANGING_METHODS: + origin = request.headers.get("origin") + sec_fetch_site = request.headers.get("sec-fetch-site", "").lower() + referer = request.headers.get("referer") + + # 1. Explicit Origin header: must match an allowed local host + if origin: + origin_host = _extract_hostname(origin) + if not origin_host or origin_host not in self.allowed_hostnames: + return PlainTextResponse( + "Cross-origin state-changing request forbidden", status_code=403 + ) + + # 2. Sec-Fetch-Site header: reject cross-site navigation/fetch + if sec_fetch_site == "cross-site": + return PlainTextResponse( + "Cross-site request forbidden", status_code=403 + ) + + # 3. Referer fallback when Origin is missing: if present, must match + if not origin and referer: + referer_host = _extract_hostname(referer) + if not referer_host or referer_host not in self.allowed_hostnames: + return PlainTextResponse( + "Cross-origin request forbidden", status_code=403 + ) + + return await call_next(request) + + +class SecurityHeadersMiddleware(BaseHTTPMiddleware): + """Attaches defensive security headers to all responses.""" + + def __init__(self, app, csp: str = DEFAULT_CSP) -> None: + super().__init__(app) + self.csp = csp + + async def dispatch(self, request: Request, call_next) -> Response: + response = await call_next(request) + headers = response.headers + headers["Content-Security-Policy"] = self.csp + headers["X-Frame-Options"] = "DENY" + headers["X-Content-Type-Options"] = "nosniff" + headers["Referrer-Policy"] = "strict-origin-when-cross-origin" + return response diff --git a/src/secfoo/web/templates/assessments/detail.html b/src/secfoo/web/templates/assessments/detail.html index 60271cb..3185872 100644 --- a/src/secfoo/web/templates/assessments/detail.html +++ b/src/secfoo/web/templates/assessments/detail.html @@ -115,7 +115,7 @@

Attachments

FileKindUploaded {% for att in attachments %} - {{ att.original_name }}{{ att.attachment_kind }}{{ att.uploaded_at | fmt_time }} + {{ att.original_name }}{{ att.attachment_kind }}{{ att.uploaded_at | fmt_time }} {% endfor %} diff --git a/tests/test_docext.py b/tests/test_docext.py index 2c8f262..7610512 100644 --- a/tests/test_docext.py +++ b/tests/test_docext.py @@ -1,5 +1,8 @@ from __future__ import annotations +from hypothesis import given, settings +from hypothesis import strategies as st + from secfoo.docext import extract_text, is_extractable # A minimal, hand-built, genuinely valid single-page PDF (not a mock/stub) @@ -123,3 +126,16 @@ def test_extract_text_returns_empty_string_for_malformed_pptx_rather_than_raisin path = tmp_path / "corrupt.pptx" path.write_bytes(b"this is not a zip file at all") assert extract_text(path) == "" + + +@settings(max_examples=50, deadline=None) +@given( + ext=st.sampled_from([".pdf", ".docx", ".pptx"]), + data=st.binary(min_size=0, max_size=10240), +) +def test_extract_text_fuzz_never_raises(ext, data, tmp_path_factory): + tmp_dir = tmp_path_factory.mktemp("fuzz") + fuzz_file = tmp_dir / f"fuzz{ext}" + fuzz_file.write_bytes(data) + result = extract_text(fuzz_file) + assert isinstance(result, str) diff --git a/tests/test_web/test_dashboard_security.py b/tests/test_web/test_dashboard_security.py new file mode 100644 index 0000000..03d9e7f --- /dev/null +++ b/tests/test_web/test_dashboard_security.py @@ -0,0 +1,419 @@ +"""Security hardening tests for the local dashboard (#118). + +Covers: +1. Cross-Site Request Forgery (CSRF) protection on all state-changing routes. +2. DNS rebinding defense via TrustedHostMiddleware. +3. Security response headers (CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy). +4. XSS regression corpus on report markdown and finding detail views. +5. Attachment upload size limits (streamed enforcement) and extension whitelist. +6. Safe attachment download serving (octet-stream, Content-Disposition, nosniff). +7. Constant-time API key verification and --allow-insecure-runtime enforcement. +""" + +from __future__ import annotations + +import pytest +from fastapi.testclient import TestClient + +from secfoo import docext +from secfoo.report.markdown import render_report_html +from secfoo.runtime.keys import create_key, revoke_key, verify_key +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + + +@pytest.fixture +def client(tmp_path, monkeypatch): + db_path = tmp_path / "db.sqlite" + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", db_path) + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + monkeypatch.setattr("secfoo.config.ATTACHMENTS_DIR", tmp_path / "attachments") + return TestClient(create_app()) + + +def _seed_assessment() -> tuple[int, int]: + repo = RunRepository() + project_id = repo.upsert_project( + "https://github.com/org/repo", "org/repo", "github" + ) + assessment_id = repo.create_assessment( + project_id=project_id, assessment_type="internal", status="ready" + ) + repo.close() + return project_id, assessment_id + + +# --------------------------------------------------------------------------- # +# 1. DNS Rebinding / Host Header Protection +# --------------------------------------------------------------------------- # + + +def test_trusted_host_rejects_foreign_host(client): + """DNS rebinding attempts with a foreign Host header get 400 Bad Request.""" + resp = client.get("/", headers={"Host": "evil.example"}) + assert resp.status_code == 400 + assert "Invalid host header" in resp.text + + +def test_trusted_host_accepts_valid_hosts(client): + """Requests with localhost or loopback Host headers succeed.""" + for host in ("localhost:8787", "127.0.0.1:8787", "testserver"): + resp = client.get("/", headers={"Host": host}) + assert resp.status_code == 200 + + +# --------------------------------------------------------------------------- # +# 2. Security Response Headers +# --------------------------------------------------------------------------- # + + +@pytest.mark.parametrize("path", ["/", "/assessments", "/activities/sast", "/agents"]) +def test_security_headers_present_on_routes(client, path): + """All dashboard responses must carry defensive security headers.""" + resp = client.get(path) + assert resp.status_code == 200 + headers = resp.headers + assert "Content-Security-Policy" in headers + assert "default-src 'self'" in headers["Content-Security-Policy"] + assert "frame-ancestors 'none'" in headers["Content-Security-Policy"] + assert headers["X-Frame-Options"] == "DENY" + assert headers["X-Content-Type-Options"] == "nosniff" + assert headers["Referrer-Policy"] == "strict-origin-when-cross-origin" + + +# --------------------------------------------------------------------------- # +# 3. Cross-Site Protection for ALL Six State-Changing POST Routes +# --------------------------------------------------------------------------- # + + +def test_csrf_rejection_post_assessments(client, monkeypatch): + """Route 1: POST /assessments rejected when cross-origin.""" + _seed_assessment() + data = { + "project_name": "Test Repo", + "project": "https://github.com/org/repo", + "assessment_type": "internal", + } + # Cross-origin Origin header -> 403 + resp = client.post( + "/assessments", data=data, headers={"Origin": "https://evil.example"} + ) + assert resp.status_code == 403 + assert "Cross-origin" in resp.text + + # Cross-site Sec-Fetch-Site -> 403 + resp = client.post( + "/assessments", data=data, headers={"Sec-Fetch-Site": "cross-site"} + ) + assert resp.status_code == 403 + + # Same-origin -> succeeds (redirects to assessment) + resp = client.post( + "/assessments", + data=data, + headers={"Origin": "http://127.0.0.1:8787", "Sec-Fetch-Site": "same-origin"}, + follow_redirects=False, + ) + assert resp.status_code == 303 + + +def test_csrf_rejection_post_bulk_status(client): + """Route 2: POST /assessments/bulk-status rejected when cross-origin.""" + _, a_id = _seed_assessment() + data = {"ids": [a_id], "new_status": "completed"} + + # Cross-origin Origin header -> 403 + resp = client.post( + "/assessments/bulk-status", + data=data, + headers={"Origin": "https://evil.example"}, + ) + assert resp.status_code == 403 + + # Same-origin -> succeeds + resp = client.post( + "/assessments/bulk-status", + data=data, + headers={"Origin": "http://127.0.0.1:8787"}, + follow_redirects=False, + ) + assert resp.status_code == 303 + + +def test_csrf_rejection_post_assessment_runs(client): + """Route 3: POST /assessments/{id}/runs rejected when cross-origin.""" + _, a_id = _seed_assessment() + + # Cross-origin Origin -> 403 + resp = client.post( + f"/assessments/{a_id}/runs", + data={"skill_ids": ["sast"]}, + headers={"Origin": "https://evil.example"}, + ) + assert resp.status_code == 403 + + +def test_csrf_rejection_post_attachments(client): + """Route 4: POST /assessments/{id}/attachments rejected when cross-origin.""" + _, a_id = _seed_assessment() + files = {"file": ("doc.pdf", b"%PDF-1.4 dummy", "application/pdf")} + + # Cross-origin Origin -> 403 + resp = client.post( + f"/assessments/{a_id}/attachments", + files=files, + headers={"Origin": "https://evil.example"}, + ) + assert resp.status_code == 403 + + +def test_csrf_rejection_post_assessment_delete(client): + """Route 5: POST /assessments/{id}/delete rejected when cross-origin.""" + _, a_id = _seed_assessment() + + # Cross-origin Origin -> 403 + resp = client.post( + f"/assessments/{a_id}/delete", + headers={"Origin": "https://evil.example"}, + ) + assert resp.status_code == 403 + + # Same-origin -> 200 + resp = client.post( + f"/assessments/{a_id}/delete", + headers={"Origin": "http://127.0.0.1:8787"}, + ) + assert resp.status_code == 200 + assert resp.json() == {"ok": True} + + +def test_csrf_rejection_post_finding_review(client): + """Route 6: POST /activities/sast/findings/{fp}/review rejected when cross-origin.""" + repo = RunRepository() + project_id = repo.upsert_project( + "https://github.com/org/repo", "org/repo", "github" + ) + run_uuid = repo.create_run( + project_id=project_id, + skill_id="sast", + skill_name="SAST", + agent_id="claude", + confluence_urls=[], + ) + run_record = repo.get_run(run_uuid) + assert run_record is not None + repo.upsert_sast_finding( + project_id=project_id, + fingerprint="fp-sqli", + run_id=run_record.id, + current_ref="F1", + title="SQL Injection", + severity="High", + cwe="CWE-89", + owasp="A03:2021", + verdict="Confirmed", + location_file="app.py", + location_line="42", + cvss_vector=None, + cvss_score=None, + description="User input directly concatenated", + recommendation="Use parameters", + ) + findings = repo.list_sast_findings(project_id=project_id) + finding = findings[0] + repo.close() + + url = f"/activities/sast/findings/{finding.fingerprint}/review" + data = {"finding_id": finding.id, "review_status": "confirmed", "reviewer": "Alice"} + + # Cross-origin Origin -> 403 + resp = client.post(url, data=data, headers={"Origin": "https://evil.example"}) + assert resp.status_code == 403 + + # Same-origin -> 303 redirect + resp = client.post( + url, + data=data, + headers={"Origin": "http://127.0.0.1:8787"}, + follow_redirects=False, + ) + assert resp.status_code == 303 + + +# --------------------------------------------------------------------------- # +# 4. Upload Size and Type Limits +# --------------------------------------------------------------------------- # + + +def test_upload_rejects_unsupported_file_extension(client): + """Uploading executables or unsupported file types gets 400 Bad Request.""" + _, a_id = _seed_assessment() + for bad_name in ("malware.exe", "backdoor.sh", "exploit.php", "test.bin"): + files = {"file": (bad_name, b"binary content", "application/octet-stream")} + resp = client.post( + f"/assessments/{a_id}/attachments", + files=files, + headers={"Origin": "http://127.0.0.1:8787"}, + ) + assert resp.status_code == 400 + assert "Unsupported file type" in resp.text + + +def test_upload_rejects_oversized_file_while_streaming(client, monkeypatch): + """Uploading a file exceeding MAX_UPLOAD_BYTES is aborted chunk-by-chunk with 413.""" + _, a_id = _seed_assessment() + # Lower MAX_UPLOAD_BYTES artificially for test speed + monkeypatch.setattr(docext, "MAX_UPLOAD_BYTES", 1024) + + oversized_data = b"A" * 2048 + files = {"file": ("large_doc.pdf", oversized_data, "application/pdf")} + resp = client.post( + f"/assessments/{a_id}/attachments", + files=files, + headers={"Origin": "http://127.0.0.1:8787"}, + ) + assert resp.status_code == 413 + assert "File too large" in resp.text + + +def test_upload_allowed_type_succeeds(client): + """Allowed file extensions upload successfully.""" + _, a_id = _seed_assessment() + for allowed_name in ("notes.txt", "spec.json", "vendor.pdf", "report.md"): + files = {"file": (allowed_name, b"valid content", "text/plain")} + resp = client.post( + f"/assessments/{a_id}/attachments", + files=files, + headers={"Origin": "http://127.0.0.1:8787"}, + follow_redirects=False, + ) + assert resp.status_code == 303 + + +# --------------------------------------------------------------------------- # +# 5. Attachment Download Safety +# --------------------------------------------------------------------------- # + + +def test_attachment_download_served_as_safe_octet_stream(client): + """Attachments are downloaded with application/octet-stream, Content-Disposition, and nosniff.""" + _, a_id = _seed_assessment() + # Upload an HTML attachment + files = {"file": ("malicious.html", b"", "text/html")} + upload_resp = client.post( + f"/assessments/{a_id}/attachments", + files=files, + headers={"Origin": "http://127.0.0.1:8787"}, + follow_redirects=False, + ) + assert upload_resp.status_code == 303 + + repo = RunRepository() + attachments = repo.list_attachments(a_id) + repo.close() + assert len(attachments) == 1 + att_id = attachments[0].id + + # Download attachment + download_resp = client.get(f"/assessments/{a_id}/attachments/{att_id}/download") + assert download_resp.status_code == 200 + assert download_resp.headers["Content-Type"] == "application/octet-stream" + assert ( + 'attachment; filename="malicious.html"' + in download_resp.headers["Content-Disposition"] + ) + assert download_resp.headers["X-Content-Type-Options"] == "nosniff" + assert download_resp.content == b"" + + +# --------------------------------------------------------------------------- # +# 6. XSS Regression Corpus +# --------------------------------------------------------------------------- # + + +XSS_PAYLOADS = [ + # Image onerror: must not render raw ", ["alert(1)]\n```", ["