From 8ea681102b1d24f1ac9f2652469953c16f78969b Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 29 Jul 2026 11:29:34 +0000 Subject: [PATCH 1/7] Add CSP report-only middleware and report collector (OHE-2815) - New SecurityHeadersMiddleware emits Content-Security-Policy-Report-Only plus X-Content-Type-Options, Referrer-Policy, Permissions-Policy and X-Frame-Options on every response. - POST /api/v1/security/csp-report accepts both application/csp-report and application/reports+json payloads and logs each violation. - Default policy uses 'unsafe-inline' on script-src/style-src so React Router's inline bootstrap does not flood the report; tighten before flipping to enforce mode. - New env vars: CONTENT_SECURITY_POLICY_REPORT_ONLY (override), CONTENT_SECURITY_POLICY_REPORT_URI, OH_FRAME_SRC_ALLOWLIST. Co-authored-by: openhands --- openhands/app_server/app.py | 4 + openhands/app_server/middleware.py | 88 +++++++ openhands/app_server/security/__init__.py | 1 + .../app_server/security/security_router.py | 79 +++++++ openhands/app_server/v1_router.py | 4 + .../test_security_headers_middleware.py | 222 ++++++++++++++++++ 6 files changed, 398 insertions(+) create mode 100644 openhands/app_server/security/__init__.py create mode 100644 openhands/app_server/security/security_router.py create mode 100644 tests/unit/app_server/test_security_headers_middleware.py diff --git a/openhands/app_server/app.py b/openhands/app_server/app.py index d7aca4ff35..b110872601 100644 --- a/openhands/app_server/app.py +++ b/openhands/app_server/app.py @@ -22,6 +22,7 @@ InMemoryRateLimiter, LocalhostCORSMiddleware, RateLimitMiddleware, + SecurityHeadersMiddleware, ) from openhands.app_server.static import SPAStaticFiles from openhands.app_server.status.status_router import router as health_router @@ -84,3 +85,6 @@ async def authentication_error_handler(request: Request, exc: AuthenticationErro RateLimitMiddleware, rate_limiter=InMemoryRateLimiter(requests=10, seconds=1), ) +# OHE-2815: must be added last so the header is applied to every response, +# including the SPA static mount and the CSP report endpoint itself. +app.add_middleware(SecurityHeadersMiddleware) diff --git a/openhands/app_server/middleware.py b/openhands/app_server/middleware.py index 1d521fde84..87bf6595b5 100644 --- a/openhands/app_server/middleware.py +++ b/openhands/app_server/middleware.py @@ -1,5 +1,6 @@ import asyncio import logging +import os import re from collections import defaultdict from datetime import datetime, timedelta @@ -18,6 +19,93 @@ _RESUME_RE = re.compile(r'^/api/v1/sandboxes/[^/]+/resume/?$') +# OHE-2815: default Content-Security-Policy for report-only mode. +# `unsafe-inline` is included for script-src/style-src to avoid flooding +# violation reports with the inline scripts that React Router's SPA mode +# emits and any inline styles Tailwind/Vite generate. Tightening to nonces +# or static hashes is a follow-up before flipping to enforce mode. +_DEFAULT_CSP_DIRECTIVES: dict[str, str] = { + 'default-src': "'self'", + 'script-src': "'self' 'unsafe-inline'", + 'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com", + 'font-src': "'self' https://fonts.gstatic.com data:", + 'img-src': "'self' data: blob: https:", + 'connect-src': "'self' ws: wss: https://us.i.posthog.com", + 'frame-src': "'self' {frame_src_extras}", + 'frame-ancestors': "'self'", + 'object-src': "'none'", + 'base-uri': "'self'", + 'form-action': "'self'", + 'worker-src': "'self' blob:", + 'report-uri': '{report_uri}', +} + + +def _build_csp(directives: dict[str, str]) -> str: + """Render a directive map as a CSP header value, dropping empty entries.""" + parts: list[str] = [] + for name, value in directives.items(): + if value == '' or value is None: + continue + parts.append(f'{name} {value}') + return '; '.join(parts) + + +def _split_csv(value: str) -> list[str]: + return [item.strip() for item in value.split(',') if item.strip()] + + +class SecurityHeadersMiddleware(BaseHTTPMiddleware): + """Adds browser security headers to every HTTP response. + + OHE-2815: Content-Security-Policy is added in *report-only* mode by + default so violations surface without breaking functionality. Switch to + enforcement by setting ``CONTENT_SECURITY_POLICY`` and clearing + ``CONTENT_SECURITY_POLICY_REPORT_ONLY``. + """ + + def __init__(self, app: ASGIApp) -> None: + super().__init__(app) + + def _policy(self) -> str: + override = os.getenv('CONTENT_SECURITY_POLICY_REPORT_ONLY', '').strip() + if override: + return override + + report_uri = ( + os.getenv('CONTENT_SECURITY_POLICY_REPORT_URI', '').strip() + or '/api/v1/security/csp-report' + ) + frame_extras = ' '.join(_split_csv(os.getenv('OH_FRAME_SRC_ALLOWLIST', ''))) + directives = { + name: value.format( + frame_src_extras=frame_extras, report_uri=report_uri + ).strip() + for name, value in _DEFAULT_CSP_DIRECTIVES.items() + } + return _build_csp(directives) + + async def dispatch( + self, request: Request, call_next: RequestResponseEndpoint + ) -> Response: + response = await call_next(request) + headers = response.headers + + # OHE-2815: report-only CSP. Replace with `Content-Security-Policy` + # (and clear the report-only env var) to enforce. + headers['Content-Security-Policy-Report-Only'] = self._policy() + + headers['X-Content-Type-Options'] = 'nosniff' + headers['Referrer-Policy'] = 'strict-origin-when-cross-origin' + headers['Permissions-Policy'] = ( + 'camera=(), microphone=(), geolocation=(), interest-cohort=()' + ) + # Defence-in-depth alongside CSP `frame-ancestors 'self'`. + headers['X-Frame-Options'] = 'SAMEORIGIN' + # HSTS is intentionally left to the edge reverse proxy. + return response + + class LocalhostCORSMiddleware(CORSMiddleware): """Custom CORS middleware that allows any request from localhost/127.0.0.1 domains, while using standard CORS rules for other origins. diff --git a/openhands/app_server/security/__init__.py b/openhands/app_server/security/__init__.py new file mode 100644 index 0000000000..e36ee87c32 --- /dev/null +++ b/openhands/app_server/security/__init__.py @@ -0,0 +1 @@ +"""Browser-facing security endpoints (CSP violation reports, etc.).""" diff --git a/openhands/app_server/security/security_router.py b/openhands/app_server/security/security_router.py new file mode 100644 index 0000000000..6717164366 --- /dev/null +++ b/openhands/app_server/security/security_router.py @@ -0,0 +1,79 @@ +"""Endpoint that accepts browser Content-Security-Policy violation reports. + +Browsers send reports in two formats: + +* Legacy: ``Content-Type: application/csp-report`` with body + ``{"csp-report": {...}}``. +* Reporting API: ``Content-Type: application/reports+json`` with body + ``[{"type": "csp-violation", "body": {...}, ...}, ...]``. + +We accept both, log a single line per violation, and return 204. +""" + +import logging +from typing import Any + +from fastapi import APIRouter, Request, Response + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix='/security', tags=['Security']) + + +_LEGACY_CONTENT_TYPE = 'application/csp-report' +_REPORTING_CONTENT_TYPE = 'application/reports+json' + + +def _summarise(report: dict[str, Any]) -> str: + """Return a short, log-safe summary of a single CSP report payload.""" + directive = report.get('violated-directive') or report.get('effective-directive') + blocked = report.get('blocked-uri') or report.get('blockedURL') + document = report.get('document-uri') or report.get('url') + return f'directive={directive!r} blocked={blocked!r} document={document!r}' + + +def _extract_legacy(payload: Any) -> list[dict[str, Any]]: + if not isinstance(payload, dict): + return [] + nested = payload.get('csp-report') + return [nested] if isinstance(nested, dict) else [] + + +def _extract_reporting(payload: Any) -> list[dict[str, Any]]: + if not isinstance(payload, list): + return [] + reports: list[dict[str, Any]] = [] + for entry in payload: + if not isinstance(entry, dict): + continue + body = entry.get('body') + if isinstance(body, dict): + reports.append(body) + return reports + + +@router.post('/csp-report', status_code=204) +async def report_csp_violation(request: Request) -> Response: + """Receive a Content-Security-Policy violation report from the browser.""" + content_type = ( + (request.headers.get('content-type') or '').split(';', 1)[0].strip().lower() + ) + + try: + payload = await request.json() + except Exception: + logger.warning('CSP report received with invalid JSON body') + return Response(status_code=204) + + if content_type == _LEGACY_CONTENT_TYPE: + reports = _extract_legacy(payload) + elif content_type == _REPORTING_CONTENT_TYPE: + reports = _extract_reporting(payload) + else: + # Tolerate browsers that omit the content-type. + reports = _extract_legacy(payload) + _extract_reporting(payload) + + for report in reports: + logger.info('CSP report: %s', _summarise(report)) + + return Response(status_code=204) diff --git a/openhands/app_server/v1_router.py b/openhands/app_server/v1_router.py index eae32aa933..5427724dcc 100644 --- a/openhands/app_server/v1_router.py +++ b/openhands/app_server/v1_router.py @@ -14,6 +14,9 @@ from openhands.app_server.secrets.secrets_router import ( router as secrets_router, ) +from openhands.app_server.security.security_router import ( + router as security_router, +) from openhands.app_server.settings.settings_router import ( router as settings_router, ) @@ -35,3 +38,4 @@ router.include_router(web_client_router.router) router.include_router(git_router) router.include_router(config_router) +router.include_router(security_router) diff --git a/tests/unit/app_server/test_security_headers_middleware.py b/tests/unit/app_server/test_security_headers_middleware.py new file mode 100644 index 0000000000..d90e7c761f --- /dev/null +++ b/tests/unit/app_server/test_security_headers_middleware.py @@ -0,0 +1,222 @@ +"""Tests for OHE-2815 security headers and CSP report endpoint.""" + +from __future__ import annotations + +import logging +from collections.abc import Iterator + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from openhands.app_server.middleware import SecurityHeadersMiddleware +from openhands.app_server.security.security_router import router as security_router + + +@pytest.fixture +def app() -> FastAPI: + app = FastAPI() + app.add_middleware(SecurityHeadersMiddleware) + + @app.get('/sample') + def sample() -> dict[str, str]: + return {'ok': 'yes'} + + @app.get('/assets/sample.js') + def asset() -> dict[str, str]: + return {'ok': 'asset'} + + app.include_router(security_router) + return app + + +@pytest.fixture +def client(app: FastAPI) -> TestClient: + return TestClient(app) + + +@pytest.fixture +def clear_csp_env(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + for var in ( + 'CONTENT_SECURITY_POLICY_REPORT_ONLY', + 'CONTENT_SECURITY_POLICY', + 'OH_FRAME_SRC_ALLOWLIST', + 'CONTENT_SECURITY_POLICY_REPORT_URI', + ): + monkeypatch.delenv(var, raising=False) + yield + + +def _csp(response) -> str: + return response.headers['Content-Security-Policy-Report-Only'] + + +class TestSecurityHeadersMiddleware: + def test_sets_report_only_header( + self, client: TestClient, clear_csp_env: None + ) -> None: + response = client.get('/sample') + + assert response.status_code == 200 + csp = _csp(response) + assert "default-src 'self'" in csp + assert "script-src 'self' 'unsafe-inline'" in csp + assert 'report-uri /api/v1/security/csp-report' in csp + + def test_sets_companion_headers( + self, client: TestClient, clear_csp_env: None + ) -> None: + response = client.get('/sample') + + assert response.headers['X-Content-Type-Options'] == 'nosniff' + assert response.headers['Referrer-Policy'] == 'strict-origin-when-cross-origin' + assert 'camera=()' in response.headers['Permissions-Policy'] + assert 'interest-cohort=()' in response.headers['Permissions-Policy'] + assert response.headers['X-Frame-Options'] == 'SAMEORIGIN' + + def test_no_enforced_csp_header( + self, client: TestClient, clear_csp_env: None + ) -> None: + response = client.get('/sample') + + assert 'Content-Security-Policy' not in response.headers + assert 'Content-Security-Policy-Report-Only' in response.headers + + def test_header_applied_to_static_paths( + self, client: TestClient, clear_csp_env: None + ) -> None: + response = client.get('/assets/sample.js') + + assert response.status_code == 200 + assert 'Content-Security-Policy-Report-Only' in response.headers + + def test_frame_src_allowlist_appended( + self, client: TestClient, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv( + 'OH_FRAME_SRC_ALLOWLIST', + 'runtime.staging.all-hands.dev, .runtime.example.com', + ) + + response = client.get('/sample') + + csp = _csp(response) + assert "frame-src 'self'" in csp + assert 'runtime.staging.all-hands.dev' in csp + assert '.runtime.example.com' in csp + + def test_empty_frame_src_allowlist_omits_extras( + self, client: TestClient, clear_csp_env: None + ) -> None: + response = client.get('/sample') + + # No trailing whitespace when no extras are configured. + assert "frame-src 'self';" in _csp(response) + assert "frame-src 'self' ;" not in _csp(response) + + def test_policy_override_takes_precedence( + self, client: TestClient, monkeypatch: pytest.MonkeyPatch + ) -> None: + custom = "default-src 'none'; report-uri /custom" + monkeypatch.setenv('CONTENT_SECURITY_POLICY_REPORT_ONLY', custom) + + response = client.get('/sample') + + assert _csp(response) == custom + + def test_report_uri_override( + self, + client: TestClient, + clear_csp_env: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setenv( + 'CONTENT_SECURITY_POLICY_REPORT_URI', '/api/v1/custom-report' + ) + + response = client.get('/sample') + + assert 'report-uri /api/v1/custom-report' in _csp(response) + + +class TestCspReportEndpoint: + def test_legacy_report_returns_204( + self, client: TestClient, caplog: pytest.LogCaptureFixture + ) -> None: + body = { + 'csp-report': { + 'document-uri': 'https://example.test/page', + 'violated-directive': "script-src 'self'", + 'blocked-uri': 'https://evil.test/x.js', + 'original-policy': "default-src 'self'", + } + } + with caplog.at_level( + logging.INFO, logger='openhands.app_server.security.security_router' + ): + response = client.post( + '/api/v1/security/csp-report', + json=body, + headers={'Content-Type': 'application/csp-report'}, + ) + + assert response.status_code == 204 + assert any('CSP report:' in rec.message for rec in caplog.records) + assert any("script-src 'self'" in rec.message for rec in caplog.records) + + def test_reporting_api_format( + self, client: TestClient, caplog: pytest.LogCaptureFixture + ) -> None: + body = [ + { + 'type': 'csp-violation', + 'age': 0, + 'url': 'https://example.test/page', + 'body': { + 'violated_directive': "img-src 'self'", + 'blockedURL': 'https://tracker.test/pixel.png', + }, + } + ] + with caplog.at_level( + logging.INFO, logger='openhands.app_server.security.security_router' + ): + response = client.post( + '/api/v1/security/csp-report', + json=body, + headers={'Content-Type': 'application/reports+json'}, + ) + + assert response.status_code == 204 + assert any('img-src' in rec.message for rec in caplog.records) + + def test_invalid_json_returns_204(self, client: TestClient) -> None: + response = client.post( + '/api/v1/security/csp-report', + content=b'not-json', + headers={'Content-Type': 'application/csp-report'}, + ) + + assert response.status_code == 204 + + def test_unknown_content_type_still_logged( + self, client: TestClient, caplog: pytest.LogCaptureFixture + ) -> None: + body = { + 'csp-report': { + 'document-uri': 'https://example.test/page', + 'violated-directive': "frame-ancestors 'self'", + 'blocked-uri': 'https://attacker.test', + } + } + with caplog.at_level( + logging.INFO, logger='openhands.app_server.security.security_router' + ): + response = client.post( + '/api/v1/security/csp-report', + json=body, + headers={'Content-Type': 'application/json'}, + ) + + assert response.status_code == 204 + assert any('frame-ancestors' in rec.message for rec in caplog.records) From 87dac6e505d594c52d54f1527e5f5192d30bd8cd Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 29 Jul 2026 13:39:51 +0000 Subject: [PATCH 2/7] Fix CSP defaults: add posthog assets host and apply runtime hosts to connect-src Staging surfaced three missing pieces in the default policy: - PostHog SDK scripts are loaded from us-assets.i.posthog.com, not just us.i.posthog.com (which is the event-ingest endpoint). Added the assets host to script-src and connect-src by default. - Runtime API calls (e.g. /api/conversations/.../events/count) and the VS Code iframe both target *.staging-runtime.all-hands.dev, so the runtime host set has to be in connect-src as well as frame-src. Renamed OH_FRAME_SRC_ALLOWLIST to OH_RUNTIME_HOSTS since it now drives both directives, and added coverage for wildcards and the posthog asset host. Co-authored-by: openhands --- openhands/app_server/middleware.py | 19 ++++-- .../test_security_headers_middleware.py | 62 +++++++++++++++---- 2 files changed, 65 insertions(+), 16 deletions(-) diff --git a/openhands/app_server/middleware.py b/openhands/app_server/middleware.py index 87bf6595b5..e4e282f64c 100644 --- a/openhands/app_server/middleware.py +++ b/openhands/app_server/middleware.py @@ -24,14 +24,19 @@ # violation reports with the inline scripts that React Router's SPA mode # emits and any inline styles Tailwind/Vite generate. Tightening to nonces # or static hashes is a follow-up before flipping to enforce mode. +# +# PostHog hosts: +# - us.i.posthog.com — event ingest (fetch / xhr) +# - us-assets.i.posthog.com — SDK scripts, exception-autocapture, +# web-vitals, recorder, surveys, tracing-headers _DEFAULT_CSP_DIRECTIVES: dict[str, str] = { 'default-src': "'self'", - 'script-src': "'self' 'unsafe-inline'", + 'script-src': "'self' 'unsafe-inline' https://us-assets.i.posthog.com", 'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com", 'font-src': "'self' https://fonts.gstatic.com data:", 'img-src': "'self' data: blob: https:", - 'connect-src': "'self' ws: wss: https://us.i.posthog.com", - 'frame-src': "'self' {frame_src_extras}", + 'connect-src': "'self' ws: wss: https://us.i.posthog.com https://us-assets.i.posthog.com {runtime_hosts}", + 'frame-src': "'self' {runtime_hosts}", 'frame-ancestors': "'self'", 'object-src': "'none'", 'base-uri': "'self'", @@ -76,10 +81,14 @@ def _policy(self) -> str: os.getenv('CONTENT_SECURITY_POLICY_REPORT_URI', '').strip() or '/api/v1/security/csp-report' ) - frame_extras = ' '.join(_split_csv(os.getenv('OH_FRAME_SRC_ALLOWLIST', ''))) + # Runtime hosts are appended to both frame-src (VS Code iframe on + # `vscode-.`) and connect-src (REST + WS calls + # against `.`). Wildcards are supported: e.g. + # `https://*.staging-runtime.all-hands.dev`. + runtime_hosts = ' '.join(_split_csv(os.getenv('OH_RUNTIME_HOSTS', ''))) directives = { name: value.format( - frame_src_extras=frame_extras, report_uri=report_uri + runtime_hosts=runtime_hosts, report_uri=report_uri ).strip() for name, value in _DEFAULT_CSP_DIRECTIVES.items() } diff --git a/tests/unit/app_server/test_security_headers_middleware.py b/tests/unit/app_server/test_security_headers_middleware.py index d90e7c761f..004978f742 100644 --- a/tests/unit/app_server/test_security_headers_middleware.py +++ b/tests/unit/app_server/test_security_headers_middleware.py @@ -40,7 +40,7 @@ def clear_csp_env(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: for var in ( 'CONTENT_SECURITY_POLICY_REPORT_ONLY', 'CONTENT_SECURITY_POLICY', - 'OH_FRAME_SRC_ALLOWLIST', + 'OH_RUNTIME_HOSTS', 'CONTENT_SECURITY_POLICY_REPORT_URI', ): monkeypatch.delenv(var, raising=False) @@ -90,29 +90,69 @@ def test_header_applied_to_static_paths( assert response.status_code == 200 assert 'Content-Security-Policy-Report-Only' in response.headers - def test_frame_src_allowlist_appended( - self, client: TestClient, monkeypatch: pytest.MonkeyPatch + def test_runtime_hosts_appended_to_frame_and_connect( + self, + client: TestClient, + clear_csp_env: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setenv( + 'OH_RUNTIME_HOSTS', 'https://*.staging-runtime.all-hands.dev' + ) + + response = client.get('/sample') + + csp = _csp(response) + assert "frame-src 'self' https://*.staging-runtime.all-hands.dev;" in csp + assert ( + "connect-src 'self' ws: wss: https://us.i.posthog.com" + ' https://us-assets.i.posthog.com' + ' https://*.staging-runtime.all-hands.dev;' in csp + ) + + def test_runtime_hosts_supports_multiple_wildcards( + self, + client: TestClient, + clear_csp_env: None, + monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setenv( - 'OH_FRAME_SRC_ALLOWLIST', - 'runtime.staging.all-hands.dev, .runtime.example.com', + 'OH_RUNTIME_HOSTS', + ( + 'https://*.staging-runtime.all-hands.dev,' + ' https://*.runtime.all-hands.dev,' + ' https://vscode-staging.example.com' + ), ) response = client.get('/sample') csp = _csp(response) - assert "frame-src 'self'" in csp - assert 'runtime.staging.all-hands.dev' in csp - assert '.runtime.example.com' in csp + assert 'https://*.staging-runtime.all-hands.dev' in csp + assert 'https://*.runtime.all-hands.dev' in csp + assert 'https://vscode-staging.example.com' in csp + # Both directives carry the whole host set. + assert csp.count('https://*.runtime.all-hands.dev') == 2 - def test_empty_frame_src_allowlist_omits_extras( + def test_posthog_assets_in_default_script_src( self, client: TestClient, clear_csp_env: None ) -> None: response = client.get('/sample') + csp = _csp(response) + assert "script-src 'self' 'unsafe-inline'" in csp + assert 'https://us-assets.i.posthog.com' in csp + assert 'https://us.i.posthog.com' in csp + + def test_empty_runtime_hosts_omits_extras( + self, client: TestClient, clear_csp_env: None + ) -> None: + response = client.get('/sample') + + csp = _csp(response) # No trailing whitespace when no extras are configured. - assert "frame-src 'self';" in _csp(response) - assert "frame-src 'self' ;" not in _csp(response) + assert "frame-src 'self';" in csp + assert "frame-src 'self' ;" not in csp def test_policy_override_takes_precedence( self, client: TestClient, monkeypatch: pytest.MonkeyPatch From 4d333ab6f670d3715f36427c8a24d22f490e8585 Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 29 Jul 2026 13:48:21 +0000 Subject: [PATCH 3/7] Drop CSP report collector: rely on DevTools instead - Remove openhands/app_server/security/ package and its router include in v1_router.py. Violations still surface in the browser DevTools / console under report-only mode, which is enough for the user to triage. - Drop report-uri directive from the default policy and the CONTENT_SECURITY_POLICY_REPORT_URI env var (now unused). - Trim the corresponding tests. Co-authored-by: openhands --- openhands/app_server/middleware.py | 16 +-- openhands/app_server/security/__init__.py | 1 - .../app_server/security/security_router.py | 79 ------------- openhands/app_server/v1_router.py | 4 - .../test_security_headers_middleware.py | 107 +----------------- 5 files changed, 8 insertions(+), 199 deletions(-) delete mode 100644 openhands/app_server/security/__init__.py delete mode 100644 openhands/app_server/security/security_router.py diff --git a/openhands/app_server/middleware.py b/openhands/app_server/middleware.py index e4e282f64c..5e2e58dc51 100644 --- a/openhands/app_server/middleware.py +++ b/openhands/app_server/middleware.py @@ -42,7 +42,6 @@ 'base-uri': "'self'", 'form-action': "'self'", 'worker-src': "'self' blob:", - 'report-uri': '{report_uri}', } @@ -64,9 +63,10 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware): """Adds browser security headers to every HTTP response. OHE-2815: Content-Security-Policy is added in *report-only* mode by - default so violations surface without breaking functionality. Switch to - enforcement by setting ``CONTENT_SECURITY_POLICY`` and clearing - ``CONTENT_SECURITY_POLICY_REPORT_ONLY``. + default so violations surface (in DevTools / browser console) without + breaking functionality. Switch to enforcement by changing the header + name in :meth:`dispatch` from ``Content-Security-Policy-Report-Only`` + to ``Content-Security-Policy``. """ def __init__(self, app: ASGIApp) -> None: @@ -77,19 +77,13 @@ def _policy(self) -> str: if override: return override - report_uri = ( - os.getenv('CONTENT_SECURITY_POLICY_REPORT_URI', '').strip() - or '/api/v1/security/csp-report' - ) # Runtime hosts are appended to both frame-src (VS Code iframe on # `vscode-.`) and connect-src (REST + WS calls # against `.`). Wildcards are supported: e.g. # `https://*.staging-runtime.all-hands.dev`. runtime_hosts = ' '.join(_split_csv(os.getenv('OH_RUNTIME_HOSTS', ''))) directives = { - name: value.format( - runtime_hosts=runtime_hosts, report_uri=report_uri - ).strip() + name: value.format(runtime_hosts=runtime_hosts).strip() for name, value in _DEFAULT_CSP_DIRECTIVES.items() } return _build_csp(directives) diff --git a/openhands/app_server/security/__init__.py b/openhands/app_server/security/__init__.py deleted file mode 100644 index e36ee87c32..0000000000 --- a/openhands/app_server/security/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Browser-facing security endpoints (CSP violation reports, etc.).""" diff --git a/openhands/app_server/security/security_router.py b/openhands/app_server/security/security_router.py deleted file mode 100644 index 6717164366..0000000000 --- a/openhands/app_server/security/security_router.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Endpoint that accepts browser Content-Security-Policy violation reports. - -Browsers send reports in two formats: - -* Legacy: ``Content-Type: application/csp-report`` with body - ``{"csp-report": {...}}``. -* Reporting API: ``Content-Type: application/reports+json`` with body - ``[{"type": "csp-violation", "body": {...}, ...}, ...]``. - -We accept both, log a single line per violation, and return 204. -""" - -import logging -from typing import Any - -from fastapi import APIRouter, Request, Response - -logger = logging.getLogger(__name__) - -router = APIRouter(prefix='/security', tags=['Security']) - - -_LEGACY_CONTENT_TYPE = 'application/csp-report' -_REPORTING_CONTENT_TYPE = 'application/reports+json' - - -def _summarise(report: dict[str, Any]) -> str: - """Return a short, log-safe summary of a single CSP report payload.""" - directive = report.get('violated-directive') or report.get('effective-directive') - blocked = report.get('blocked-uri') or report.get('blockedURL') - document = report.get('document-uri') or report.get('url') - return f'directive={directive!r} blocked={blocked!r} document={document!r}' - - -def _extract_legacy(payload: Any) -> list[dict[str, Any]]: - if not isinstance(payload, dict): - return [] - nested = payload.get('csp-report') - return [nested] if isinstance(nested, dict) else [] - - -def _extract_reporting(payload: Any) -> list[dict[str, Any]]: - if not isinstance(payload, list): - return [] - reports: list[dict[str, Any]] = [] - for entry in payload: - if not isinstance(entry, dict): - continue - body = entry.get('body') - if isinstance(body, dict): - reports.append(body) - return reports - - -@router.post('/csp-report', status_code=204) -async def report_csp_violation(request: Request) -> Response: - """Receive a Content-Security-Policy violation report from the browser.""" - content_type = ( - (request.headers.get('content-type') or '').split(';', 1)[0].strip().lower() - ) - - try: - payload = await request.json() - except Exception: - logger.warning('CSP report received with invalid JSON body') - return Response(status_code=204) - - if content_type == _LEGACY_CONTENT_TYPE: - reports = _extract_legacy(payload) - elif content_type == _REPORTING_CONTENT_TYPE: - reports = _extract_reporting(payload) - else: - # Tolerate browsers that omit the content-type. - reports = _extract_legacy(payload) + _extract_reporting(payload) - - for report in reports: - logger.info('CSP report: %s', _summarise(report)) - - return Response(status_code=204) diff --git a/openhands/app_server/v1_router.py b/openhands/app_server/v1_router.py index 5427724dcc..eae32aa933 100644 --- a/openhands/app_server/v1_router.py +++ b/openhands/app_server/v1_router.py @@ -14,9 +14,6 @@ from openhands.app_server.secrets.secrets_router import ( router as secrets_router, ) -from openhands.app_server.security.security_router import ( - router as security_router, -) from openhands.app_server.settings.settings_router import ( router as settings_router, ) @@ -38,4 +35,3 @@ router.include_router(web_client_router.router) router.include_router(git_router) router.include_router(config_router) -router.include_router(security_router) diff --git a/tests/unit/app_server/test_security_headers_middleware.py b/tests/unit/app_server/test_security_headers_middleware.py index 004978f742..bd73e7dfb2 100644 --- a/tests/unit/app_server/test_security_headers_middleware.py +++ b/tests/unit/app_server/test_security_headers_middleware.py @@ -1,8 +1,7 @@ -"""Tests for OHE-2815 security headers and CSP report endpoint.""" +"""Tests for OHE-2815 security headers middleware.""" from __future__ import annotations -import logging from collections.abc import Iterator import pytest @@ -10,7 +9,6 @@ from fastapi.testclient import TestClient from openhands.app_server.middleware import SecurityHeadersMiddleware -from openhands.app_server.security.security_router import router as security_router @pytest.fixture @@ -26,7 +24,6 @@ def sample() -> dict[str, str]: def asset() -> dict[str, str]: return {'ok': 'asset'} - app.include_router(security_router) return app @@ -41,7 +38,6 @@ def clear_csp_env(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: 'CONTENT_SECURITY_POLICY_REPORT_ONLY', 'CONTENT_SECURITY_POLICY', 'OH_RUNTIME_HOSTS', - 'CONTENT_SECURITY_POLICY_REPORT_URI', ): monkeypatch.delenv(var, raising=False) yield @@ -61,7 +57,7 @@ def test_sets_report_only_header( csp = _csp(response) assert "default-src 'self'" in csp assert "script-src 'self' 'unsafe-inline'" in csp - assert 'report-uri /api/v1/security/csp-report' in csp + assert 'report-uri' not in csp def test_sets_companion_headers( self, client: TestClient, clear_csp_env: None @@ -157,106 +153,9 @@ def test_empty_runtime_hosts_omits_extras( def test_policy_override_takes_precedence( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: - custom = "default-src 'none'; report-uri /custom" + custom = "default-src 'none'" monkeypatch.setenv('CONTENT_SECURITY_POLICY_REPORT_ONLY', custom) response = client.get('/sample') assert _csp(response) == custom - - def test_report_uri_override( - self, - client: TestClient, - clear_csp_env: None, - monkeypatch: pytest.MonkeyPatch, - ) -> None: - monkeypatch.setenv( - 'CONTENT_SECURITY_POLICY_REPORT_URI', '/api/v1/custom-report' - ) - - response = client.get('/sample') - - assert 'report-uri /api/v1/custom-report' in _csp(response) - - -class TestCspReportEndpoint: - def test_legacy_report_returns_204( - self, client: TestClient, caplog: pytest.LogCaptureFixture - ) -> None: - body = { - 'csp-report': { - 'document-uri': 'https://example.test/page', - 'violated-directive': "script-src 'self'", - 'blocked-uri': 'https://evil.test/x.js', - 'original-policy': "default-src 'self'", - } - } - with caplog.at_level( - logging.INFO, logger='openhands.app_server.security.security_router' - ): - response = client.post( - '/api/v1/security/csp-report', - json=body, - headers={'Content-Type': 'application/csp-report'}, - ) - - assert response.status_code == 204 - assert any('CSP report:' in rec.message for rec in caplog.records) - assert any("script-src 'self'" in rec.message for rec in caplog.records) - - def test_reporting_api_format( - self, client: TestClient, caplog: pytest.LogCaptureFixture - ) -> None: - body = [ - { - 'type': 'csp-violation', - 'age': 0, - 'url': 'https://example.test/page', - 'body': { - 'violated_directive': "img-src 'self'", - 'blockedURL': 'https://tracker.test/pixel.png', - }, - } - ] - with caplog.at_level( - logging.INFO, logger='openhands.app_server.security.security_router' - ): - response = client.post( - '/api/v1/security/csp-report', - json=body, - headers={'Content-Type': 'application/reports+json'}, - ) - - assert response.status_code == 204 - assert any('img-src' in rec.message for rec in caplog.records) - - def test_invalid_json_returns_204(self, client: TestClient) -> None: - response = client.post( - '/api/v1/security/csp-report', - content=b'not-json', - headers={'Content-Type': 'application/csp-report'}, - ) - - assert response.status_code == 204 - - def test_unknown_content_type_still_logged( - self, client: TestClient, caplog: pytest.LogCaptureFixture - ) -> None: - body = { - 'csp-report': { - 'document-uri': 'https://example.test/page', - 'violated-directive': "frame-ancestors 'self'", - 'blocked-uri': 'https://attacker.test', - } - } - with caplog.at_level( - logging.INFO, logger='openhands.app_server.security.security_router' - ): - response = client.post( - '/api/v1/security/csp-report', - json=body, - headers={'Content-Type': 'application/json'}, - ) - - assert response.status_code == 204 - assert any('frame-ancestors' in rec.message for rec in caplog.records) From f21e8227e33ebeccb3f69fffca12bcff653ca12f Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 29 Jul 2026 15:44:44 +0000 Subject: [PATCH 4/7] Derive CSP runtime hosts from WEB_HOST instead of new env var Per reviewer feedback, drop OH_RUNTIME_HOSTS and reuse the existing WEB_HOST (the deployment's bare apex hostname): inject a single 'https://*.WEB_HOST' source into both frame-src and connect-src. CSP3 '*.host' matches the host itself plus any number of subdomains, so one entry covers '.' (REST + WS) and 'vscode-.' (iframe). Returns empty when WEB_HOST is unset, so local dev keeps frame-src 'self' without further config. Tolerate accidental 'https://WEB_HOST' or trailing '/' since operators set WEB_HOST inconsistently across the codebase. Co-authored-by: openhands --- openhands/app_server/middleware.py | 36 +++++++++++++--- .../test_security_headers_middleware.py | 43 ++++++++++--------- 2 files changed, 52 insertions(+), 27 deletions(-) diff --git a/openhands/app_server/middleware.py b/openhands/app_server/middleware.py index 5e2e58dc51..6b2443ca2b 100644 --- a/openhands/app_server/middleware.py +++ b/openhands/app_server/middleware.py @@ -55,8 +55,34 @@ def _build_csp(directives: dict[str, str]) -> str: return '; '.join(parts) -def _split_csv(value: str) -> list[str]: - return [item.strip() for item in value.split(',') if item.strip()] +def _runtime_hosts_from_web_host() -> str: + """Derive the runtime-host wildcard entry from ``WEB_HOST``. + + ``WEB_HOST`` is the deployment's bare apex hostname (see + ``get_default_web_url`` and ``web_client_deployment_mode.get_deployment_mode``). + In staging it's ``staging-runtime.all-hands.dev``; in prod it's + ``app.all-hands.dev`` (the runtime lives on a subdomain pattern under it + such as ``.`` and ``vscode-.``). + + A CSP3 ``*.host`` source matches the host itself and any number of + subdomains, so a single ``https://*.{WEB_HOST}`` entry covers both + the API calls (``.``) and the VS Code iframe + (``vscode-.``). + + Returns an empty string when ``WEB_HOST`` is unset (e.g. local dev, + where ``frame-src 'self'`` already covers ``localhost``). + """ + web_host = os.getenv('WEB_HOST', '').strip().rstrip('/') + if not web_host: + return '' + # Tolerate schemes accidentally set in WEB_HOST (some operators set + # `https://app.all-hands.dev`); strip them so we don't end up with + # `https://https://*.host`. + for prefix in ('https://', 'http://'): + if web_host.startswith(prefix): + web_host = web_host[len(prefix) :] + break + return f'https://*.{web_host}' class SecurityHeadersMiddleware(BaseHTTPMiddleware): @@ -77,11 +103,7 @@ def _policy(self) -> str: if override: return override - # Runtime hosts are appended to both frame-src (VS Code iframe on - # `vscode-.`) and connect-src (REST + WS calls - # against `.`). Wildcards are supported: e.g. - # `https://*.staging-runtime.all-hands.dev`. - runtime_hosts = ' '.join(_split_csv(os.getenv('OH_RUNTIME_HOSTS', ''))) + runtime_hosts = _runtime_hosts_from_web_host() directives = { name: value.format(runtime_hosts=runtime_hosts).strip() for name, value in _DEFAULT_CSP_DIRECTIVES.items() diff --git a/tests/unit/app_server/test_security_headers_middleware.py b/tests/unit/app_server/test_security_headers_middleware.py index bd73e7dfb2..24c51cfa52 100644 --- a/tests/unit/app_server/test_security_headers_middleware.py +++ b/tests/unit/app_server/test_security_headers_middleware.py @@ -37,7 +37,7 @@ def clear_csp_env(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: for var in ( 'CONTENT_SECURITY_POLICY_REPORT_ONLY', 'CONTENT_SECURITY_POLICY', - 'OH_RUNTIME_HOSTS', + 'WEB_HOST', ): monkeypatch.delenv(var, raising=False) yield @@ -86,15 +86,13 @@ def test_header_applied_to_static_paths( assert response.status_code == 200 assert 'Content-Security-Policy-Report-Only' in response.headers - def test_runtime_hosts_appended_to_frame_and_connect( + def test_web_host_wildcard_appended_to_frame_and_connect( self, client: TestClient, clear_csp_env: None, monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.setenv( - 'OH_RUNTIME_HOSTS', 'https://*.staging-runtime.all-hands.dev' - ) + monkeypatch.setenv('WEB_HOST', 'staging-runtime.all-hands.dev') response = client.get('/sample') @@ -106,29 +104,33 @@ def test_runtime_hosts_appended_to_frame_and_connect( ' https://*.staging-runtime.all-hands.dev;' in csp ) - def test_runtime_hosts_supports_multiple_wildcards( + def test_web_host_with_scheme_prefix_is_stripped( self, client: TestClient, clear_csp_env: None, monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.setenv( - 'OH_RUNTIME_HOSTS', - ( - 'https://*.staging-runtime.all-hands.dev,' - ' https://*.runtime.all-hands.dev,' - ' https://vscode-staging.example.com' - ), - ) + monkeypatch.setenv('WEB_HOST', 'https://staging-runtime.all-hands.dev') + + response = client.get('/sample') + + csp = _csp(response) + assert 'https://*.staging-runtime.all-hands.dev' in csp + assert 'https://https://' not in csp + + def test_web_host_with_trailing_slash_is_stripped( + self, + client: TestClient, + clear_csp_env: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setenv('WEB_HOST', 'staging-runtime.all-hands.dev/') response = client.get('/sample') csp = _csp(response) assert 'https://*.staging-runtime.all-hands.dev' in csp - assert 'https://*.runtime.all-hands.dev' in csp - assert 'https://vscode-staging.example.com' in csp - # Both directives carry the whole host set. - assert csp.count('https://*.runtime.all-hands.dev') == 2 + assert 'https://*.staging-runtime.all-hands.dev/' not in csp def test_posthog_assets_in_default_script_src( self, client: TestClient, clear_csp_env: None @@ -140,15 +142,16 @@ def test_posthog_assets_in_default_script_src( assert 'https://us-assets.i.posthog.com' in csp assert 'https://us.i.posthog.com' in csp - def test_empty_runtime_hosts_omits_extras( + def test_empty_web_host_omits_wildcard( self, client: TestClient, clear_csp_env: None ) -> None: response = client.get('/sample') csp = _csp(response) - # No trailing whitespace when no extras are configured. + # No trailing whitespace / leftover placeholder when WEB_HOST is unset. assert "frame-src 'self';" in csp assert "frame-src 'self' ;" not in csp + assert 'https://*.' not in csp def test_policy_override_takes_precedence( self, client: TestClient, monkeypatch: pytest.MonkeyPatch From 877ede3345c0ed9de21f413f90a15cc2ec73e6ce Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 30 Jul 2026 08:52:53 +0000 Subject: [PATCH 5/7] Strip leftmost DNS label from WEB_HOST for the runtime wildcard Staging reported new connect-src violations: the public app lives at 'staging.all-hands.dev' (the WEB_HOST value), but the runtime lives at '.staging-runtime.all-hands.dev' - a *sibling* subdomain tree under 'all-hands.dev'. Wildcarding '*.staging.all-hands.dev' misses those siblings. Drop the leftmost DNS label so WEB_HOST is wildcarded at the registrable domain (eTLD+1): staging.all-hands.dev -> https://*.all-hands.dev app.all-hands.dev -> https://*.all-hands.dev openhands.example.com -> https://*.example.com app.example.co.uk -> https://*.example.co.uk CSP3 '*.host' matches the host itself plus any number of subdomains, so a single entry covers the API calls, the VS Code iframe, and any other sibling subdomain the runtime team spins up. WEB_HOST=localhost (single label) is skipped - the wildcard would either be invalid or too broad. Co-authored-by: openhands --- openhands/app_server/middleware.py | 45 ++++++++--- .../test_security_headers_middleware.py | 78 +++++++++++++++++-- 2 files changed, 104 insertions(+), 19 deletions(-) diff --git a/openhands/app_server/middleware.py b/openhands/app_server/middleware.py index 6b2443ca2b..ddbbb162eb 100644 --- a/openhands/app_server/middleware.py +++ b/openhands/app_server/middleware.py @@ -58,19 +58,33 @@ def _build_csp(directives: dict[str, str]) -> str: def _runtime_hosts_from_web_host() -> str: """Derive the runtime-host wildcard entry from ``WEB_HOST``. - ``WEB_HOST`` is the deployment's bare apex hostname (see + ``WEB_HOST`` is the deployment's bare hostname for the public app (see ``get_default_web_url`` and ``web_client_deployment_mode.get_deployment_mode``). - In staging it's ``staging-runtime.all-hands.dev``; in prod it's - ``app.all-hands.dev`` (the runtime lives on a subdomain pattern under it - such as ``.`` and ``vscode-.``). + In staging it's ``staging.all-hands.dev``; in prod it's + ``app.all-hands.dev``; in self-hosted it's the customer apex such as + ``openhands.example.com``. + + The runtime, however, lives on a *sibling* subdomain tree: in staging + that's ``.staging-runtime.all-hands.dev`` and + ``vscode-.staging-runtime.all-hands.dev``. A wildcard built + directly off ``WEB_HOST`` (e.g. ``*.staging.all-hands.dev``) misses + those siblings, so we instead drop the leftmost DNS label and wildcard + the registrable domain (eTLD+1): + + ``staging.all-hands.dev`` -> ``https://*.all-hands.dev`` + ``app.all-hands.dev`` -> ``https://*.all-hands.dev`` + ``openhands.example.com`` -> ``https://*.example.com`` + ``app.example.co.uk`` -> ``https://*.example.co.uk`` A CSP3 ``*.host`` source matches the host itself and any number of - subdomains, so a single ``https://*.{WEB_HOST}`` entry covers both - the API calls (``.``) and the VS Code iframe - (``vscode-.``). - - Returns an empty string when ``WEB_HOST`` is unset (e.g. local dev, - where ``frame-src 'self'`` already covers ``localhost``). + subdomains, so one entry covers both the API calls + (``..``) and the VS Code iframe + (``vscode-..``). + + Returns an empty string when ``WEB_HOST`` is unset or single-label + (e.g. ``localhost``), where the wildcard would either be invalid or + too broad — ``frame-src 'self'`` already covers ``localhost`` in that + case. """ web_host = os.getenv('WEB_HOST', '').strip().rstrip('/') if not web_host: @@ -82,7 +96,16 @@ def _runtime_hosts_from_web_host() -> str: if web_host.startswith(prefix): web_host = web_host[len(prefix) :] break - return f'https://*.{web_host}' + # Strip port (e.g. `localhost:3000`) so the dot-split below is sane. + if ':' in web_host: + web_host = web_host.split(':', 1)[0] + parts = web_host.split('.') + if len(parts) < 2: + # Single-label host (`localhost`, `nginx`, ...); no registrable + # domain we can wildcard without becoming `*` itself. + return '' + registrable = '.'.join(parts[1:]) + return f'https://*.{registrable}' class SecurityHeadersMiddleware(BaseHTTPMiddleware): diff --git a/tests/unit/app_server/test_security_headers_middleware.py b/tests/unit/app_server/test_security_headers_middleware.py index 24c51cfa52..57b4b8dcff 100644 --- a/tests/unit/app_server/test_security_headers_middleware.py +++ b/tests/unit/app_server/test_security_headers_middleware.py @@ -92,30 +92,63 @@ def test_web_host_wildcard_appended_to_frame_and_connect( clear_csp_env: None, monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.setenv('WEB_HOST', 'staging-runtime.all-hands.dev') + monkeypatch.setenv('WEB_HOST', 'app.all-hands.dev') response = client.get('/sample') csp = _csp(response) - assert "frame-src 'self' https://*.staging-runtime.all-hands.dev;" in csp + assert "frame-src 'self' https://*.all-hands.dev;" in csp assert ( "connect-src 'self' ws: wss: https://us.i.posthog.com" ' https://us-assets.i.posthog.com' - ' https://*.staging-runtime.all-hands.dev;' in csp + ' https://*.all-hands.dev;' in csp ) + def test_web_host_wildcard_reaches_runtime_subdomain_tree( + self, + client: TestClient, + clear_csp_env: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """Staging: WEB_HOST=staging.all-hands.dev but the runtime lives at + ``.staging-runtime.all-hands.dev`` — a sibling subdomain + tree under the registrable domain. The wildcard must reach it. + """ + monkeypatch.setenv('WEB_HOST', 'staging.all-hands.dev') + + response = client.get('/sample') + + csp = _csp(response) + assert 'https://*.all-hands.dev' in csp + # ``*.staging.all-hands.dev`` would NOT have matched the runtime. + assert 'https://*.staging.all-hands.dev' not in csp + + def test_web_host_self_hosted_apex( + self, + client: TestClient, + clear_csp_env: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setenv('WEB_HOST', 'openhands.example.com') + + response = client.get('/sample') + + csp = _csp(response) + assert 'https://*.example.com' in csp + assert 'https://*.openhands.example.com' not in csp + def test_web_host_with_scheme_prefix_is_stripped( self, client: TestClient, clear_csp_env: None, monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.setenv('WEB_HOST', 'https://staging-runtime.all-hands.dev') + monkeypatch.setenv('WEB_HOST', 'https://app.all-hands.dev') response = client.get('/sample') csp = _csp(response) - assert 'https://*.staging-runtime.all-hands.dev' in csp + assert 'https://*.all-hands.dev' in csp assert 'https://https://' not in csp def test_web_host_with_trailing_slash_is_stripped( @@ -124,13 +157,27 @@ def test_web_host_with_trailing_slash_is_stripped( clear_csp_env: None, monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.setenv('WEB_HOST', 'staging-runtime.all-hands.dev/') + monkeypatch.setenv('WEB_HOST', 'app.all-hands.dev/') + + response = client.get('/sample') + + csp = _csp(response) + assert 'https://*.all-hands.dev' in csp + assert 'https://*.all-hands.dev/' not in csp + + def test_web_host_with_port_strips_port( + self, + client: TestClient, + clear_csp_env: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setenv('WEB_HOST', 'app.example.com:8443') response = client.get('/sample') csp = _csp(response) - assert 'https://*.staging-runtime.all-hands.dev' in csp - assert 'https://*.staging-runtime.all-hands.dev/' not in csp + assert 'https://*.example.com' in csp + assert ':8443' not in csp def test_posthog_assets_in_default_script_src( self, client: TestClient, clear_csp_env: None @@ -153,6 +200,21 @@ def test_empty_web_host_omits_wildcard( assert "frame-src 'self' ;" not in csp assert 'https://*.' not in csp + def test_single_label_web_host_omits_wildcard( + self, + client: TestClient, + clear_csp_env: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """``localhost`` has no registrable domain to wildcard.""" + monkeypatch.setenv('WEB_HOST', 'localhost') + + response = client.get('/sample') + + csp = _csp(response) + assert 'https://*.' not in csp + assert "frame-src 'self';" in csp + def test_policy_override_takes_precedence( self, client: TestClient, monkeypatch: pytest.MonkeyPatch ) -> None: From c360f1f4cc7ed5ed159d2379ca42c1c094603270 Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 30 Jul 2026 09:45:12 +0000 Subject: [PATCH 6/7] Switch CSP middleware to enforce mode (OHE-2815) Staging report was clean after the registrable-domain fix, so flip the header from 'Content-Security-Policy-Report-Only' to 'Content-Security-Policy' in dispatch(). Violations are now blocked by the browser; DevTools still logs them for triage. Rename the override env var from CONTENT_SECURITY_POLICY_REPORT_ONLY to CONTENT_SECURITY_POLICY (it's now the policy itself, not a report-only variant). Detection uses os.getenv without a default so an explicit empty value disables CSP entirely - useful as a kill switch without a redeploy. Test changes: - _csp helper now reads 'Content-Security-Policy'. - New 'test_no_report_only_header' asserts the report-only header is not emitted and the enforced header is. - New 'test_explicit_empty_override_disables_csp' covers the kill switch. - Renamed test method that asserted on the old header name. Co-authored-by: openhands --- openhands/app_server/middleware.py | 39 ++++++++++--------- .../test_security_headers_middleware.py | 30 +++++++++----- 2 files changed, 41 insertions(+), 28 deletions(-) diff --git a/openhands/app_server/middleware.py b/openhands/app_server/middleware.py index ddbbb162eb..7fd9630846 100644 --- a/openhands/app_server/middleware.py +++ b/openhands/app_server/middleware.py @@ -19,13 +19,10 @@ _RESUME_RE = re.compile(r'^/api/v1/sandboxes/[^/]+/resume/?$') -# OHE-2815: default Content-Security-Policy for report-only mode. -# `unsafe-inline` is included for script-src/style-src to avoid flooding -# violation reports with the inline scripts that React Router's SPA mode -# emits and any inline styles Tailwind/Vite generate. Tightening to nonces -# or static hashes is a follow-up before flipping to enforce mode. -# -# PostHog hosts: +# OHE-2815: default Content-Security-Policy. Enforced by the browser. +# `unsafe-inline` is kept on script-src/style-src because React Router's +# SPA bootstrap emits inline