The head linked `icons/favicon.svg` under the service's static files and nothing else, so a service that kept its icon elsewhere (scribe) or had none (agent-bridge) showed no icon at all, and clients that ignore SVG (Safari, bookmark bars) or ask /favicon.ico without reading the page got a 404 everywhere. Chrome now resolves five icon kinds - svg, 32 px png, the Apple touch icon, 192 and 512 - from the service's static dir with a few accepted paths each, falling back per kind to a generic set shipped here, links svg + png + touch icon in the head, and answers /favicon.ico and /apple-touch-icon.png at the root and under the mount prefix. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
422 lines
15 KiB
Python
422 lines
15 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_under_both_conventional_keys(client):
|
|
"""`error` is what chrome started with and what marketplace and
|
|
agent-bridge read; `detail` is FastAPI's own, which scribe's client was
|
|
written against years earlier. Sending both spares a rewrite over a
|
|
naming difference - and a client reading the missing one degrades
|
|
silently to the HTTP status text, which is the worst way to find out."""
|
|
r = client.get("/api/boom")
|
|
assert r.status_code == 404
|
|
assert r.json() == {"error": "no such thing", "detail": "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
|
|
|
|
|
|
def test_a_redirect_raised_from_a_dependency_stays_a_redirect(tmp_path):
|
|
"""A dependency saying "you are not logged in, go here" is a destination,
|
|
not an error. JSON-ifying it drops the Location and leaves a blank 307."""
|
|
from fastapi import Depends, HTTPException
|
|
|
|
app = FastAPI()
|
|
Chrome(app, service="t", version="1", title="T")
|
|
|
|
def needs_login():
|
|
raise HTTPException(307, "", headers={"Location": "/login"})
|
|
|
|
@app.get("/private")
|
|
def private(_user=Depends(needs_login)):
|
|
return {"never": "reached"}
|
|
|
|
r = TestClient(app).get("/private", follow_redirects=False)
|
|
assert r.status_code == 307
|
|
assert r.headers["location"] == "/login"
|
|
|
|
|
|
def test_the_language_route_honours_a_local_next_and_refuses_anything_else(tmp_path):
|
|
app = FastAPI()
|
|
Chrome(app, service="t", version="1", title="T")
|
|
client = TestClient(app)
|
|
|
|
r = client.get("/language/en?next=/access", follow_redirects=False)
|
|
assert r.headers["location"] == "/access"
|
|
|
|
for hostile in ("https://evil.example.invalid/x", "//evil.example.invalid/x",
|
|
"javascript:alert(1)"):
|
|
r = client.get(f"/language/en?next={hostile}", follow_redirects=False)
|
|
assert r.headers["location"] == "/", f"{hostile} was not rejected"
|
|
|
|
|
|
def test_a_service_can_supply_its_own_language_control(tmp_path):
|
|
"""scribe stores the language per USER, in its database, so the choice
|
|
follows you to another machine. chrome's is a browser cookie, which is
|
|
strictly weaker - so the shell has to be able to stand down rather than
|
|
show a second switcher that disagrees with the first."""
|
|
templates = tmp_path / "templates"
|
|
templates.mkdir()
|
|
(templates / "page.html").write_text('{% extends "base.html" %}')
|
|
|
|
def build(switcher):
|
|
app = FastAPI()
|
|
ui = Chrome(app, service="t", version="1", title="T",
|
|
templates_dir=templates, language_switcher=switcher)
|
|
|
|
@app.get("/")
|
|
def page(request: Request):
|
|
return ui.render(request, "page.html")
|
|
|
|
return TestClient(app).get("/").text
|
|
|
|
with_switcher = build(True)
|
|
without = build(False)
|
|
|
|
assert "data-lang-select" in with_switcher
|
|
assert "data-lang-select" not in without
|
|
# Only the language control stands down; the theme toggle is unaffected.
|
|
assert "data-theme-choice" in without
|
|
|
|
|
|
def test_a_service_can_keep_its_own_health_probe(tmp_path):
|
|
"""scribe's reports which speech engines it can reach, which is the
|
|
thing worth knowing when it is unwell. chrome's would otherwise win by
|
|
being registered first."""
|
|
app = FastAPI()
|
|
Chrome(app, service="t", version="1", title="T", health=False)
|
|
|
|
@app.get("/healthz")
|
|
def healthz():
|
|
return {"ok": True, "engine": "reachable"}
|
|
|
|
assert TestClient(app).get("/healthz").json() == {"ok": True, "engine": "reachable"}
|
|
|
|
|
|
def test_icons_fall_back_to_chromes_and_are_served(tmp_path: Path) -> None:
|
|
from fastapi import FastAPI
|
|
# a service with no icons of its own
|
|
app = FastAPI()
|
|
ui = Chrome(app, service="bare", version="0", title="Bare", mount_prefix="/ui")
|
|
c = TestClient(app)
|
|
assert ui.icon("svg").startswith("/ui/chrome-static/icons/favicon.svg") or "chrome" in ui.icon("svg")
|
|
for path in ("/favicon.ico", "/ui/favicon.ico"):
|
|
r = c.get(path); assert r.status_code == 200 and r.headers["content-type"] == "image/png"
|
|
r = c.get("/ui/apple-touch-icon.png"); assert r.status_code == 200 and len(r.content) > 100
|
|
# a service with icons under static/icons/ gets its own, and chrome's for what it lacks
|
|
static = tmp_path / "static"; (static / "icons").mkdir(parents=True)
|
|
(static / "icons" / "favicon.svg").write_text("<svg xmlns='http://www.w3.org/2000/svg'/>")
|
|
(static / "icons" / "favicon-32.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\0" * 40)
|
|
app2 = FastAPI()
|
|
ui2 = Chrome(app2, service="own", version="0", title="Own", static_dir=static, templates_dir=None)
|
|
c2 = TestClient(app2)
|
|
assert ui2.icon("svg").startswith("/static/icons/favicon.svg?v=") and ui2.icon("png32").startswith("/static/icons/favicon-32.png")
|
|
assert ui2.icon("apple").startswith("/chrome/icons/apple-touch-icon.png") # not shipped by the service: chrome's
|
|
assert c2.get("/favicon.ico").content.startswith(b"\x89PNG")
|
|
# the page links all three
|
|
@app2.get("/")
|
|
def index(request: Request):
|
|
return ui2.render(request, "base.html")
|
|
html = c2.get("/").text
|
|
assert 'rel="icon" href="/static/icons/favicon.svg?v=' in html and 'type="image/png" sizes="32x32"' in html and 'rel="apple-touch-icon"' in html
|