"""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 %}
hello
{% 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 'hello
' 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": "{{ who }}
{% 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 "alice
" in client.get("/", headers={"x-who": "alice"}).text assert "nobody
" 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 "override
" 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