Skip to content

The agent that grows with you

fix(webapp): send a Content-Security-Policy for the Webapp page

dokterdok538ed6c02a81
diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.py
index 5c8aa038750..61d8ae7713b 100644
--- a/hermes_cli/web_server_dashboard.py
+++ b/hermes_cli/web_server_dashboard.py
@@ -160,7 +160,7 @@ def mount_spa(application: FastAPI):
def web_dist() -> Path:
return getattr(application.state, "web_dist", None) or WEB_DIST
- def _serve_index(prefix: str = ""):
+ def _serve_index(request: Request, prefix: str = ""):
"""index.html with the session token + base-path injected.
When the OAuth auth gate is active (``app.state.auth_required``), the legacy
@@ -226,7 +226,8 @@ def mount_spa(application: FastAPI):
if theme_bootstrap:
html = html.replace("</head>", f"{theme_bootstrap}</head>", 1)
html = html.replace("</head>", f"{bootstrap_script}</head>", 1)
- return HTMLResponse(html, headers=_NO_STORE)
+ from hermes_cli.webapp_page_policy import page_headers
+ return HTMLResponse(html, headers=page_headers(request, html, _NO_STORE))
# Built CSS contains absolute ``url(/fonts/...)`` / ``url(/ds-assets/...)`` references that
# browsers resolve against the document origin — wrong under a proxy prefix. Intercept CSS
@@ -276,11 +277,13 @@ def mount_spa(application: FastAPI):
# real 404 JSON instead of index.html (which breaks JSON clients with a SyntaxError).
if full_path == "api" or full_path.startswith("api/"):
return JSONResponse({"detail": f"No such API endpoint: /{full_path}"}, status_code=404)
- if full_path == "index.html" and not policy(application.state).html_token:
- # Where HTML may not carry the session token, no entry serves the raw file.
- return _serve_index(prefix)
dist = web_dist()
file_path = dist / full_path
+ index = dist / "index.html"
+ if (not policy(application.state).html_token and file_path.is_file() and index.is_file()
+ and file_path.samefile(index)):
+ # No spelling of the entry document may bypass bootstrap or policy.
+ return _serve_index(request, prefix)
# Prevent path traversal via url-encoded sequences (%2e%2e/)
if (
full_path
@@ -294,7 +297,7 @@ def mount_spa(application: FastAPI):
if font is not None:
return FileResponse(font)
return JSONResponse({"error": "not found"}, status_code=404)
- return _serve_index(prefix)
+ return _serve_index(request, prefix)
# ---------------------------------------------------------------------------
diff --git a/hermes_cli/webapp_page_policy.py b/hermes_cli/webapp_page_policy.py
new file mode 100644
index 00000000000..e259c75ac45
--- /dev/null
+++ b/hermes_cli/webapp_page_policy.py
@@ -0,0 +1,58 @@
+"""CSP for the browser-hosted Desktop, independently of its preview documents."""
+
+import base64
+import hashlib
+from html.parser import HTMLParser
+
+from fastapi import Request
+
+
+class _ScriptHashes(HTMLParser):
+ """Hash the trusted build's inline scripts and the server's bootstrap verbatim."""
+
+ def __init__(self, html: str):
+ super().__init__(convert_charrefs=False)
+ self.script = None
+ self.hashes = []
+ self.feed(html)
+
+ def handle_starttag(self, tag, attrs):
+ if tag == "script" and "src" not in dict(attrs):
+ self.script = ""
+
+ def handle_data(self, data):
+ if self.script is not None:
+ self.script += data
+
+ def handle_endtag(self, tag):
+ if tag == "script" and self.script is not None:
+ digest = base64.b64encode(hashlib.sha256(self.script.encode("utf-8")).digest()).decode("ascii")
+ self.hashes.append(f"'sha256-{digest}'")
+ self.script = None
+
+
+def page_headers(request: Request, html: str, headers: dict) -> dict:
+ """Only gateway-served Webapp HTML gets this policy; native Desktop is not served here."""
+ if getattr(request.app.state, "ui_surface", None) != "webapp":
+ return headers
+ hashes = " ".join(_ScriptHashes(html).hashes)
+ # Keep fetch and media sources open for voice, catalogs, Radio, update notes,
+ # and local servers or sockets behind a Host-rewriting proxy.
+ policy = "; ".join((
+ "default-src 'none'",
+ f"script-src 'self' blob: 'wasm-unsafe-eval' {hashes}",
+ "script-src-attr 'none'",
+ "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
+ "font-src 'self' data: https://fonts.gstatic.com",
+ "connect-src * ws: wss: data: blob:",
+ "img-src 'self' data: blob: https: http:",
+ "media-src * data: blob:",
+ "worker-src 'self' blob:",
+ "frame-src 'self' blob: data: https: http:",
+ "manifest-src 'self'",
+ "object-src 'none'",
+ "base-uri 'none'",
+ "form-action 'none'",
+ "frame-ancestors 'none'",
+ ))
+ return {**headers, "Content-Security-Policy": policy, "X-Content-Type-Options": "nosniff"}
diff --git a/tests/hermes_cli/test_webapp_page_csp.py b/tests/hermes_cli/test_webapp_page_csp.py
new file mode 100644
index 00000000000..1b8f24b648d
--- /dev/null
+++ b/tests/hermes_cli/test_webapp_page_csp.py
@@ -0,0 +1,106 @@
+"""The privileged page authorizes its bootstrap and bundle, never arbitrary inline script."""
+import base64
+import hashlib
+from html.parser import HTMLParser
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+
+class Scripts(HTMLParser):
+ def __init__(self, html):
+ super().__init__()
+ self.inline = []
+ self.external = []
+ self.current = None
+ self.feed(html)
+
+ def handle_starttag(self, tag, attrs):
+ if tag == "script":
+ src = dict(attrs).get("src")
+ if src:
+ self.external.append(src)
+ else:
+ self.current = ""
+
+ def handle_data(self, data):
+ if self.current is not None:
+ self.current += data
+
+ def handle_endtag(self, tag):
+ if tag == "script" and self.current is not None:
+ self.inline.append(self.current)
+ self.current = None
+
+
+def page(monkeypatch, tmp_path):
+ from hermes_cli import web_server as server
+ from hermes_cli.web_server_dashboard import mount_spa
+
+ (tmp_path / "index.html").write_text(
+ '<html><head><script>window.booted = "<&>";</script>'
+ '<script type="module" src="/assets/app.js"></script></head><body></body></html>')
+ (tmp_path / "assets").mkdir()
+ (tmp_path / "assets/app.js").write_text('import("./lazy.js");')
+ (tmp_path / "assets/lazy.js").write_text('export const loaded = true;')
+ app = FastAPI()
+ app.state.ui_surface = "webapp"
+ app.state.auth_required = False
+ app.state.web_dist = tmp_path
+ monkeypatch.setattr(server, "app", app)
+ monkeypatch.delenv("HERMES_SERVE_HEADLESS", raising=False)
+ mount_spa(app)
+ return app
+
+
[email protected]("origin", ["http://testserver:9120", "https://webapp.example:9443"])
[email protected]("path", ["/", "/index.html", "/chat/session"])
+def test_page_allows_its_scripts_and_chunks_but_locks_privileged_execution(page, origin, path):
+ client = TestClient(page, base_url=origin)
+ response = client.get(path, headers={"X-Forwarded-Prefix": "/hermes"})
+ assert response.status_code == 200
+ policy = dict(part.strip().split(" ", 1) for part in response.headers["content-security-policy"].split(";"))
+ assert policy["object-src"] == policy["base-uri"] == policy["frame-ancestors"] == "'none'"
+ assert policy["script-src-attr"] == "'none'"
+ scripts = policy["script-src"].split()
+ assert "'self'" in scripts # the bundle and every relative import() chunk
+ assert "blob:" in scripts # runtime-loader's local plugin modules (#145072)
+ assert not {"'unsafe-inline'", "'unsafe-eval'", "https:", "http:", "*"}.intersection(scripts)
+ parsed = Scripts(response.text)
+ assert parsed.external == ["/hermes/assets/app.js"]
+ assert any("__HERMES_BASE_PATH__" in script for script in parsed.inline)
+ for script in parsed.inline:
+ digest = base64.b64encode(hashlib.sha256(script.encode()).digest()).decode()
+ assert f"'sha256-{digest}'" in scripts
+ injected = base64.b64encode(hashlib.sha256(b"window.injected=true").digest()).decode()
+ assert f"'sha256-{injected}'" not in scripts
+ # Connections stay open (provider-direct voice, catalogs, proxied sockets); execution does not.
+ assert policy["connect-src"] == "* ws: wss: data: blob:" # explicit sockets for older WebKit
+ for asset in ("app.js", "lazy.js"):
+ chunk = client.get(f"/assets/{asset}")
+ assert chunk.status_code == 200
+ assert "javascript" in chunk.headers["content-type"]
+ assert "'self'" in policy["img-src"].split()
+ assert policy["media-src"] == "* data: blob:" # gateway file routes and http: radio streams
+ assert "no-store" in response.headers["cache-control"]
+ preview = client.get("/assets/webapp-preview.html")
+ preview_scripts = dict(part.strip().split(" ", 1) for part in
+ preview.headers["content-security-policy"].split(";"))["script-src"].split()
+ assert {"'unsafe-inline'", "'unsafe-eval'"} <= set(preview_scripts) # widget scripts, d3.csvParse
+
+
[email protected]("path", ["/%2e%2findex.html", "/%2e/index.html", "/INDEX.HTML"])
+def test_every_spelling_of_the_entry_document_gets_the_policy(page, tmp_path, path):
+ if path == "/INDEX.HTML" and not (tmp_path / "INDEX.HTML").exists():
+ pytest.skip("case-sensitive filesystem")
+ response = TestClient(page).get(path)
+ assert response.status_code == 200
+ assert "'sha256-" in response.headers["content-security-policy"]
+ assert "__HERMES_BASE_PATH__" in response.text
+
+
+def test_dashboard_keeps_its_existing_document_headers(page):
+ page.state.ui_surface = "dashboard"
+ assert "content-security-policy" not in TestClient(page).get("/").headers