homepage puts the same handful of things on every page - who is logged in, whether the weather and system widgets are enabled, whether to show the admin link. Flask did that with two context processors. There is no equivalent here, and passing the same eight keys at every render site is the kind of repetition that goes stale one call at a time. `ui.page_context` is a callable taking a Request and returning a dict. It runs per render rather than once at startup, because what it returns depends on who is asking: which group a visitor is in decides whether a tile is even mentioned. An explicit value at the render site still wins, which is what the test pins down. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
312 lines
10 KiB
Python
312 lines
10 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
|
|
|
|
|
|
def test_a_service_can_move_both_static_trees_under_one_prefix(tmp_path):
|
|
"""agent-bridge is proxied on exactly two prefixes, /ui and /api.
|
|
|
|
Assets at a third top-level path would be unreachable behind Caddy, so
|
|
the whole shell has to be mountable underneath one of them.
|
|
"""
|
|
static = tmp_path / "static"
|
|
static.mkdir()
|
|
(static / "app.css").write_text("/* svc */")
|
|
templates = tmp_path / "templates"
|
|
templates.mkdir()
|
|
(templates / "index.html").write_text('{% extends "base.html" %}')
|
|
|
|
app = FastAPI()
|
|
ui = Chrome(app, service="t", version="1", title="T",
|
|
templates_dir=templates, static_dir=static,
|
|
mount_prefix="/ui")
|
|
|
|
@app.get("/ui/")
|
|
def page(request: Request):
|
|
return ui.render(request, "index.html")
|
|
|
|
client = TestClient(app)
|
|
html = client.get("/ui/").text
|
|
|
|
assert f"/ui/chrome/wa-{WEBAWESOME_VERSION}/" in html
|
|
assert "/ui/chrome/tokens.css" in html
|
|
assert '"/ui/chrome/vendor/preact.module.js?v=' in html
|
|
# Nothing may be served from a path the proxy does not forward.
|
|
assert 'href="/chrome/' not in html and 'src="/chrome/' not in html
|
|
|
|
assert client.get("/ui/chrome/tokens.css").status_code == 200
|
|
assert client.get("/ui/static/app.css").text == "/* svc */"
|
|
assert client.get(
|
|
f"/ui/chrome/wa-{WEBAWESOME_VERSION}/components/button/button.js"
|
|
).status_code == 200
|
|
# The default prefix must still be empty for services that want it.
|
|
assert client.get("/chrome/tokens.css").status_code == 404
|
|
|
|
|
|
def test_a_service_can_inject_per_request_context(tmp_path):
|
|
"""Flask's context processors, without the app object.
|
|
|
|
The hook runs per render, not once at startup, because what it returns
|
|
depends on who is asking - which group a visitor is in decides whether
|
|
a tile is even mentioned.
|
|
"""
|
|
templates = tmp_path / "templates"
|
|
templates.mkdir()
|
|
(templates / "index.html").write_text(
|
|
'{% extends "base.html" %}{% block content %}<p>{{ who }}</p>{% endblock %}'
|
|
)
|
|
app = FastAPI()
|
|
ui = Chrome(app, service="t", version="1", title="T", templates_dir=templates)
|
|
ui.page_context = lambda request: {"who": request.headers.get("x-who", "nobody")}
|
|
|
|
@app.get("/")
|
|
def page(request: Request):
|
|
return ui.render(request, "index.html")
|
|
|
|
client = TestClient(app)
|
|
assert "<p>alice</p>" in client.get("/", headers={"x-who": "alice"}).text
|
|
assert "<p>nobody</p>" in client.get("/").text
|
|
# An explicit value at the render site beats the hook.
|
|
@app.get("/explicit")
|
|
def explicit(request: Request):
|
|
return ui.render(request, "index.html", who="override")
|
|
|
|
assert "<p>override</p>" in TestClient(app).get("/explicit").text
|