Three fixes found by driving a real page, not by reading the code. Its autoloader works out where to fetch components from by finding the <script> whose src *ends with* "webawesome.loader.js". The cache-busting `?v=` defeated that match, so it fell back to the site root and every component 404'd - a page that merely looks unstyled, with nothing in the browser console and only 404s in the server log to say why. Web Awesome now lives at /chrome/wa-<version>/, which removes the query string and, because component filenames are stable across releases, also busts caches properly on an upgrade. There are regression tests for both halves. The brand ramp pointed at yellow but buttons came out brown: Web Awesome picks step 50 for a loud fill because that is the darkest point that still carries white text, and yellow-50 is #b45f04. The services have always used bright yellow with dark text, so the fill/on pair is now set explicitly rather than taken from the ramp. TemplateResponse's old (name, context) signature is gone in Starlette 1.7, and the error handler was returning its 404 page with an HTTP 200. Also adds the import map for Preact/hooks/htm to the shell. hooks.module.js carries a bare "preact" specifier internally, so the map is required rather than a convenience, and it belongs here once instead of in every service. strings_json() hands an island its translations with `<` escaped. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
241 lines
7.7 KiB
Python
241 lines
7.7 KiB
Python
"""The shell's own contract. Thin on purpose: this tests what services rely
|
|
on chrome for, not Web Awesome, and not FastAPI."""
|
|
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from fastapi.testclient import TestClient
|
|
|
|
from chrome import WEBAWESOME_VERSION, config, i18n
|
|
from chrome.app import Chrome
|
|
from chrome.auth import ProxyAuth
|
|
|
|
|
|
@pytest.fixture
|
|
def client(tmp_path: Path) -> TestClient:
|
|
static = tmp_path / "static"
|
|
static.mkdir()
|
|
(static / "app.css").write_text("/* service css */")
|
|
templates = tmp_path / "templates"
|
|
templates.mkdir()
|
|
(templates / "index.html").write_text(
|
|
'{% extends "base.html" %}{% block content %}<p id="x">hello</p>{% endblock %}'
|
|
)
|
|
|
|
app = FastAPI()
|
|
ui = Chrome(
|
|
app,
|
|
service="test",
|
|
version="9.9.9",
|
|
title="Test Service",
|
|
subtitle="a subtitle",
|
|
templates_dir=templates,
|
|
static_dir=static,
|
|
)
|
|
|
|
@app.get("/")
|
|
def index(request: Request):
|
|
return ui.render(request, "index.html")
|
|
|
|
@app.get("/boom")
|
|
def boom():
|
|
raise HTTPException(404)
|
|
|
|
@app.get("/api/boom")
|
|
def api_boom():
|
|
raise HTTPException(404, "no such thing")
|
|
|
|
return TestClient(app)
|
|
|
|
|
|
def test_healthz_reports_service_and_version(client):
|
|
body = client.get("/healthz").json()
|
|
assert body == {"status": "ok", "service": "test", "version": "9.9.9"}
|
|
|
|
|
|
def test_page_extends_the_shell(client):
|
|
html = client.get("/").text
|
|
assert '<p id="x">hello</p>' in html # the service's content
|
|
assert "Test Service" in html # the shell's header
|
|
assert "webawesome.loader.js" in html # Web Awesome is wired up
|
|
assert 'data-theme="system"' in html
|
|
|
|
|
|
def test_assets_are_versioned_and_stable(client):
|
|
html = client.get("/").text
|
|
stamps = {part.split('"')[0] for part in html.split("?v=")[1:]}
|
|
assert len(stamps) == 1, "one token for the whole tree, or pages can mix versions"
|
|
assert client.get("/").text == html, "the token must not move between requests"
|
|
|
|
|
|
def test_chrome_and_service_static_are_both_served(client):
|
|
assert client.get("/chrome/tokens.css").status_code == 200
|
|
assert client.get("/static/app.css").text == "/* service css */"
|
|
|
|
|
|
def test_html_errors_render_the_themed_page(client):
|
|
r = client.get("/boom")
|
|
assert r.status_code == 404
|
|
assert "error-code" in r.text and "Test Service" in r.text
|
|
|
|
|
|
def test_api_errors_stay_json(client):
|
|
r = client.get("/api/boom")
|
|
assert r.status_code == 404
|
|
assert r.json() == {"error": "no such thing"}
|
|
|
|
|
|
def test_language_cookie_round_trips(client):
|
|
r = client.get("/language/en", headers={"referer": "/"}, follow_redirects=False)
|
|
assert r.status_code == 303
|
|
assert r.cookies["lang"] == "en"
|
|
# An unsupported code must not set anything.
|
|
r = client.get("/language/xx", follow_redirects=False)
|
|
assert "lang" not in r.cookies
|
|
|
|
|
|
def test_locale_falls_back_through_cookie_then_header_then_default():
|
|
t = i18n.Translations()
|
|
|
|
class R:
|
|
def __init__(self, cookies, header):
|
|
self.cookies = cookies
|
|
self.headers = {"accept-language": header}
|
|
|
|
assert t.locale_for(R({"lang": "en"}, "pl")) == "en"
|
|
assert t.locale_for(R({}, "en-GB,en;q=0.9")) == "en"
|
|
assert t.locale_for(R({}, "")) == i18n.DEFAULT
|
|
|
|
|
|
def test_missing_translation_shows_the_key_not_a_blank():
|
|
assert i18n.Translations().translate("nope", "pl") == "nope"
|
|
|
|
|
|
def test_service_locales_override_shell_strings(tmp_path):
|
|
locales = tmp_path / "locales"
|
|
locales.mkdir()
|
|
(locales / "pl.json").write_text('{"theme_light": "Jasny!", "own": "moje"}', "utf-8")
|
|
t = i18n.Translations(locales)
|
|
assert t.translate("theme_light", "pl") == "Jasny!"
|
|
assert t.translate("own", "pl") == "moje"
|
|
assert t.translate("theme_dark", "pl") == "Ciemny"
|
|
|
|
|
|
# --- config -----------------------------------------------------------------
|
|
|
|
|
|
def test_config_readers(monkeypatch):
|
|
monkeypatch.setenv("B", "YES")
|
|
monkeypatch.setenv("I", " 42 ")
|
|
monkeypatch.setenv("L", "a, b ,, c")
|
|
assert config.boolean("B") is True
|
|
assert config.boolean("MISSING", True) is True
|
|
assert config.integer("I", 0) == 42
|
|
assert config.integer("NOPE", 7) == 7
|
|
assert config.csv("L") == ["a", "b", "c"]
|
|
|
|
|
|
def test_required_refuses_to_start_without_a_value(monkeypatch):
|
|
monkeypatch.delenv("GONE", raising=False)
|
|
with pytest.raises(RuntimeError, match="GONE"):
|
|
config.required("GONE")
|
|
|
|
|
|
# --- auth -------------------------------------------------------------------
|
|
|
|
|
|
def _request(headers):
|
|
app = FastAPI()
|
|
ui_app = TestClient(app) # noqa: F841 - only need a Request-shaped object
|
|
|
|
class R:
|
|
def __init__(self, h):
|
|
self.headers = h
|
|
|
|
return R(headers)
|
|
|
|
|
|
def test_proxy_auth_rejects_a_forged_header_without_the_key():
|
|
auth = ProxyAuth(proxy_key="s3cret")
|
|
with pytest.raises(HTTPException) as exc:
|
|
auth(_request({"remote-user": "mallory"}))
|
|
assert exc.value.status_code == 403
|
|
|
|
|
|
def test_proxy_auth_accepts_the_header_with_the_key():
|
|
auth = ProxyAuth(proxy_key="s3cret")
|
|
user = auth(_request({"x-proxy-key": "s3cret", "remote-user": "michal",
|
|
"remote-name": "Michal K", "remote-groups": "admins, family"}))
|
|
assert user.name == "michal"
|
|
assert user.display_name == "Michal K"
|
|
assert user.in_group("admins") and not user.in_group("nope")
|
|
|
|
|
|
def test_proxy_auth_is_off_not_open_when_no_key_is_configured():
|
|
with pytest.raises(HTTPException) as exc:
|
|
ProxyAuth(proxy_key=None)(_request({"remote-user": "mallory"}))
|
|
assert exc.value.status_code == 503
|
|
|
|
|
|
def test_unauthenticated_mode_must_be_asked_for_explicitly():
|
|
auth = ProxyAuth(proxy_key=None, allow_unauthenticated=True, local_user="dev")
|
|
assert auth(_request({})).name == "dev"
|
|
|
|
|
|
def test_webawesome_is_vendored():
|
|
assert WEBAWESOME_VERSION.count(".") == 2
|
|
|
|
|
|
def test_preact_is_mapped_for_islands(client):
|
|
html = client.get("/").text
|
|
assert '"preact":' in html and "vendor/preact.module.js" in html
|
|
assert '"preact/hooks":' in html, "hooks has a bare 'preact' import; the map is required"
|
|
assert client.get("/chrome/vendor/preact.module.js").status_code == 200
|
|
|
|
|
|
def test_strings_json_cannot_break_out_of_its_script_tag(tmp_path):
|
|
locales = tmp_path / "locales"
|
|
locales.mkdir()
|
|
(locales / "pl.json").write_text('{"evil": "</script><img src=x>"}', "utf-8")
|
|
app = FastAPI()
|
|
ui = Chrome(app, service="t", version="1", title="T", locales_dir=locales)
|
|
|
|
class R:
|
|
cookies = {"lang": "pl"}
|
|
headers = {}
|
|
|
|
blob = ui.strings_json(R(), ("evil",))
|
|
assert "</script>" not in blob
|
|
import json as _json
|
|
|
|
assert _json.loads(blob)["evil"] == "</script><img src=x>"
|
|
|
|
|
|
def test_webawesome_loader_url_has_no_query_string(client):
|
|
"""Its autoloader finds its own base path with src.endsWith(...).
|
|
|
|
A `?v=` here makes every component 404 against the site root, which is
|
|
silent in the server log of a page that merely looks unstyled.
|
|
"""
|
|
import re
|
|
|
|
html = client.get("/").text
|
|
src = re.search(r'src="([^"]*webawesome\.loader\.js[^"]*)"', html).group(1)
|
|
assert "?" not in src
|
|
assert client.get(src).status_code == 200
|
|
|
|
|
|
def test_webawesome_path_carries_its_version(client):
|
|
from chrome import WEBAWESOME_VERSION
|
|
|
|
html = client.get("/").text
|
|
assert f"/chrome/wa-{WEBAWESOME_VERSION}/" in html
|
|
assert f'data-webawesome="/chrome/wa-{WEBAWESOME_VERSION}/"' in html
|
|
|
|
|
|
def test_a_component_resolves_under_the_versioned_path(client):
|
|
from chrome import WEBAWESOME_VERSION
|
|
|
|
r = client.get(f"/chrome/wa-{WEBAWESOME_VERSION}/components/button/button.js")
|
|
assert r.status_code == 200
|