feat(server): allow extra CSP connect sources

This commit is contained in:
Frank Song
2026-05-25 21:48:52 +08:00
parent 4ea762ae0d
commit 3ee0173cd3
4 changed files with 130 additions and 14 deletions

View File

@@ -3,6 +3,10 @@
## [Unreleased]
### Added
- Operators can now set `HERMES_WEBUI_CSP_CONNECT_EXTRA` to append validated extra origins to the report-only CSP `connect-src` directive for reverse-proxy or tunnel deployments.
## [v0.51.134] — 2026-05-25 — Release DF (stage-batch16 — single-PR Windows path defaults)
### Fixed

View File

@@ -279,6 +279,7 @@ Full list of environment variables:
| `HERMES_WEBUI_DEFAULT_WORKSPACE` | `~/workspace` | Default workspace |
| `HERMES_WEBUI_DEFAULT_MODEL` | *(provider default)* | Optional model override; leave unset to use the active Hermes provider default |
| `HERMES_WEBUI_PASSWORD` | *(unset)* | Set to enable password authentication |
| `HERMES_WEBUI_CSP_CONNECT_EXTRA` | *(unset)* | Optional space-separated `http(s)://` or `ws(s)://` origins to append to the report-only CSP `connect-src` directive for reverse-proxy or tunnel deployments |
| `HERMES_WEBUI_EXTENSION_DIR` | *(unset)* | Optional local directory served at `/extensions/`; must point to an existing directory before extension injection is enabled |
| `HERMES_WEBUI_EXTENSION_SCRIPT_URLS` | *(unset)* | Optional comma-separated same-origin script URLs to inject; see [WebUI Extensions](docs/EXTENSIONS.md) |
| `HERMES_WEBUI_EXTENSION_STYLESHEET_URLS` | *(unset)* | Optional comma-separated same-origin stylesheet URLs to inject; see [WebUI Extensions](docs/EXTENSIONS.md) |

View File

@@ -5,6 +5,7 @@ All business logic lives in api/*.
"""
import logging
import os
import re
import socket
import sys
import time
@@ -111,6 +112,55 @@ from urllib.parse import urlparse
logger = logging.getLogger(__name__)
_CSP_CONNECT_BASE = (
"'self' http://127.0.0.1:* http://localhost:* "
"ws://127.0.0.1:* ws://localhost:*"
)
_CSP_EXTRA_CONNECT_RE = re.compile(
r"^(?:https?|wss?)://(?:\*\.)?[A-Za-z0-9._~-]+(?::(?P<port>\d{1,5}|\*))?$"
)
def _valid_csp_extra_connect_source(source: str) -> bool:
match = _CSP_EXTRA_CONNECT_RE.fullmatch(source)
if not match:
return False
port = match.group("port")
if not port or port == "*":
return True
try:
return 1 <= int(port) <= 65535
except ValueError:
return False
def _csp_extra_connect_src() -> str:
raw = os.getenv("HERMES_WEBUI_CSP_CONNECT_EXTRA", "").strip()
if not raw:
return ""
sources = raw.split()
if not sources or any(not _valid_csp_extra_connect_source(src) for src in sources):
logger.warning("Ignoring invalid HERMES_WEBUI_CSP_CONNECT_EXTRA value")
return ""
return " " + " ".join(sources)
def _build_csp_report_only_policy() -> str:
connect_src = _CSP_CONNECT_BASE + _csp_extra_connect_src()
return (
"default-src 'self'; "
"base-uri 'self'; "
"object-src 'none'; "
"frame-ancestors 'self'; "
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"img-src 'self' data: blob:; "
"font-src 'self' data:; "
"media-src 'self' data: blob:; "
f"connect-src {connect_src}; "
"report-uri /api/csp-report; report-to csp-endpoint"
)
from api.auth import check_auth
from api.config import HOST, PORT, STATE_DIR, SESSION_DIR, DEFAULT_WORKSPACE
from api.helpers import j, get_profile_cookie
@@ -207,24 +257,11 @@ class Handler(BaseHTTPRequestHandler):
pass
_ver_suffix = WEBUI_VERSION.removeprefix('v')
server_version = ('HermesWebUI/' + _ver_suffix) if _ver_suffix != 'unknown' else 'HermesWebUI'
_CSP_REPORT_ONLY = (
"default-src 'self'; "
"base-uri 'self'; "
"object-src 'none'; "
"frame-ancestors 'self'; "
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"img-src 'self' data: blob:; "
"font-src 'self' data:; "
"media-src 'self' data: blob:; "
"connect-src 'self' http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:*; "
"report-uri /api/csp-report; report-to csp-endpoint"
)
_CSP_REPORT_TO = '{"group":"csp-endpoint","max_age":10886400,"endpoints":[{"url":"/api/csp-report"}]}'
@classmethod
def csp_report_only_policy(cls) -> str:
return cls._CSP_REPORT_ONLY
return _build_csp_report_only_policy()
def end_headers(self) -> None:
self.send_header("Content-Security-Policy-Report-Only", self.csp_report_only_policy())

View File

@@ -0,0 +1,74 @@
"""Regression coverage for configurable CSP connect-src extras (#2901)."""
from __future__ import annotations
def test_csp_connect_src_default_header_unchanged(monkeypatch):
from server import Handler
monkeypatch.delenv("HERMES_WEBUI_CSP_CONNECT_EXTRA", raising=False)
policy = Handler.csp_report_only_policy()
assert (
"connect-src 'self' http://127.0.0.1:* http://localhost:* "
"ws://127.0.0.1:* ws://localhost:*; "
) in policy
def test_csp_connect_src_includes_valid_extra_origins(monkeypatch):
from server import Handler
monkeypatch.setenv(
"HERMES_WEBUI_CSP_CONNECT_EXTRA",
"https://metrics.example.com wss://events.example.com:443",
)
policy = Handler.csp_report_only_policy()
assert (
"connect-src 'self' http://127.0.0.1:* http://localhost:* "
"ws://127.0.0.1:* ws://localhost:* "
"https://metrics.example.com wss://events.example.com:443; "
) in policy
def test_csp_connect_src_rejects_directive_injection(monkeypatch, caplog):
from server import Handler
monkeypatch.setenv(
"HERMES_WEBUI_CSP_CONNECT_EXTRA",
"https://metrics.example.com; script-src *",
)
policy = Handler.csp_report_only_policy()
assert "https://metrics.example.com" not in policy
assert "script-src *" not in policy
assert "Ignoring invalid HERMES_WEBUI_CSP_CONNECT_EXTRA" in caplog.text
def test_csp_connect_src_rejects_paths(monkeypatch):
from server import Handler
monkeypatch.setenv(
"HERMES_WEBUI_CSP_CONNECT_EXTRA",
"https://metrics.example.com/api",
)
policy = Handler.csp_report_only_policy()
assert "https://metrics.example.com/api" not in policy
def test_csp_connect_src_rejects_invalid_ports(monkeypatch):
from server import Handler
monkeypatch.setenv(
"HERMES_WEBUI_CSP_CONNECT_EXTRA",
"https://metrics.example.com:99999",
)
policy = Handler.csp_report_only_policy()
assert "https://metrics.example.com:99999" not in policy