One page frame, one palette, one set of components, one implementation of config readers, proxy auth, /healthz, i18n and cache-busted asset URLs. The design tokens had been copied into homepage, marketplace, agent-bridge and scribe and had started to drift; so had theme.js and the asset() helper, which existed in two incompatible versions. board.css carried the instruction "Copy the values from homepage's style.css when they change there", which is the problem stated as a procedure. Components come from Web Awesome 3.14.0 (MIT), vendored under static/wa by vendor-webawesome.sh - curl and tar against the npm registry, so there is no node_modules, no lockfile and nothing for CI or a Containerfile to run. The script prunes type definitions and IDE metadata, 13M down to 3.4M, and keeps only the en and pl translations. Components style themselves inside a shadow root, so a page rule cannot reach into one: "this input is the wrong width" stops being a thing that can happen rather than a thing to be careful about. Two decisions worth recording here: - Asset versioning is a content digest over the whole static tree, not each file's mtime. mtime is wrong in a container, where every COPY'd file carries the build timestamp, so every asset appeared to change on every build. A single tree-wide token also means a cached page can never pair itself with a newer script. - Pages keep the data-theme="light|dark|system" attribute the services have always used. Web Awesome drives light/dark from a wa-light/wa-dark class instead; base.html and theme.js own that mapping so nothing else learns it. The compatibility aliases in tokens.css (--bg, --surface, --accent, ...) are deliberate: they let a service move page by page instead of all at once. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
187 lines
5.9 KiB
Python
187 lines
5.9 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 "wa/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
|