diff --git a/tests/test_app.py b/tests/test_app.py index f12244b..605649d 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -2,11 +2,17 @@ Every test gets its own database and server, so the tests stay independent of each other and of the order they run in. ``AppHandlerTests`` starts from a -stored key setup; ``KeySetupApiTests`` starts from a new, empty database. +stored key setup; ``KeySetupApiTests`` starts from a new, empty database, and +``AuthApiTests`` from a database with no admin yet. + +Section 31 point 1 puts every route except ``GET /health`` behind a session, so +``ServerTestCase`` keeps the session and CSRF cookies a sign-in returns and +sends them with every later request, exactly as the browser does. """ -from http.server import ThreadingHTTPServer import csv +from http.cookies import SimpleCookie +from http.server import ThreadingHTTPServer import io import json import os @@ -14,9 +20,10 @@ import tempfile import threading import unittest from urllib.error import HTTPError -from urllib.request import Request, urlopen +from urllib.request import HTTPRedirectHandler, Request, build_opener, urlopen from app import AppHandler +from auth import CSRF_COOKIE, CSRF_HEADER, SESSION_COOKIE, set_admin from database import initialize_database, save_key_setup from export import HEADERS @@ -47,6 +54,13 @@ RENAMED_SETUP = [ ] +class _NoRedirect(HTTPRedirectHandler): + """Refuse to follow a redirect, so a test can read the 302 itself.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + def sample_payload(key, wallet_software=None, address_path=None): """Return a valid single-key payload for the given key profile. @@ -120,7 +134,12 @@ def mismatch_payload(key, address_path="m/48'/9'/0'/2'"): class ServerTestCase(unittest.TestCase): - """Start a server on a temporary database.""" + """Start a server on a temporary database, and act as the single user. + + A test either creates the admin directly and signs in through the API + (``authenticate``), or creates it through the first-run endpoint + (``create_admin_via_api``). ``AuthApiTests`` starts from no admin at all. + """ def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() @@ -133,6 +152,10 @@ class ServerTestCase(unittest.TestCase): self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) self.thread.start() self.base_url = f"http://127.0.0.1:{self.server.server_port}" + self.admin_username = "admin" + self.admin_password = "test-password" + # The session and the CSRF token a sign-in returned (section 31 point 1). + self.cookies = {} def tearDown(self): self.server.shutdown() @@ -144,42 +167,144 @@ class ServerTestCase(unittest.TestCase): os.environ["DATABASE_PATH"] = self.previous_database_path self.temp_dir.cleanup() + # -- setup helpers ---------------------------------------------------- + def store_setup(self, setup=DEFAULT_SETUP): """Store the key setup directly, without going through the API.""" save_key_setup(setup, self.database_path) - def key_profiles(self): - with urlopen(f"{self.base_url}/api/keys") as response: - return json.load(response) + def store_admin(self): + """Store the admin account directly, without going through the API.""" + set_admin(self.admin_username, self.admin_password, self.database_path) - def get_setup(self): - with urlopen(f"{self.base_url}/api/setup") as response: - self.assertEqual(response.status, 200) - return json.load(response) + def authenticate(self): + """Store the admin and sign in, so the tests act as the single user.""" + self.store_admin() + self.sign_in() - def get_settings(self): - with urlopen(f"{self.base_url}/api/settings") as response: - self.assertEqual(response.status, 200) - return json.load(response) + # -- HTTP helpers ----------------------------------------------------- - def get_health_checks(self): - with urlopen(f"{self.base_url}/api/health-checks") as response: - self.assertEqual(response.status, 200) - return json.load(response) + def cookie_header(self): + return "; ".join(f"{name}={value}" for name, value in self.cookies.items()) - def get_key_status(self): - with urlopen(f"{self.base_url}/api/key-status") as response: + def remember_cookies(self, response): + """Keep the cookies a response set, so the next request carries them.""" + for header in response.headers.get_all("Set-Cookie") or []: + jar = SimpleCookie() + jar.load(header) + for name, morsel in jar.items(): + self.cookies[name] = morsel.value + + def request(self, path, method="GET", payload=None, csrf=True, headers=None): + """Build a request that carries the session, and the CSRF token.""" + request_headers = {"Accept": "application/json"} + if self.cookies: + request_headers["Cookie"] = self.cookie_header() + if method == "POST" and csrf and self.cookies.get(CSRF_COOKIE): + request_headers[CSRF_HEADER] = self.cookies[CSRF_COOKIE] + if payload is not None: + request_headers["Content-Type"] = "application/json" + if headers: + request_headers.update(headers) + data = None if payload is None else json.dumps(payload).encode("utf-8") + return Request( + f"{self.base_url}{path}", + data=data, + headers=request_headers, + method=method, + ) + + def get(self, path): + return urlopen(self.request(path)) + + def get_json(self, path): + with self.get(path) as response: self.assertEqual(response.status, 200) return json.load(response) def post_json(self, path, payload): - request = Request( - f"{self.base_url}{path}", - data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json"}, + return urlopen(self.request(path, method="POST", payload=payload)) + + def sign_in(self): + """Sign in through the API and keep the session and CSRF cookies.""" + request = self.request( + "/api/login", method="POST", + csrf=False, + payload={"username": self.admin_username, "password": self.admin_password}, ) - return urlopen(request) + with urlopen(request) as response: + self.assertEqual(response.status, 200) + self.remember_cookies(response) + return self.cookies + + def create_admin_via_api(self): + """Create the admin through the first-run endpoint and start a session.""" + request = self.request( + "/api/admin", + method="POST", + csrf=False, + payload={"username": self.admin_username, "password": self.admin_password}, + ) + with urlopen(request) as response: + self.assertEqual(response.status, 201) + self.remember_cookies(response) + return self.cookies + + def assert_status(self, path, status, method="GET", payload=None, csrf=True, headers=None): + """Send a request and expect an error status.""" + request = self.request( + path, method=method, payload=payload, csrf=csrf, headers=headers + ) + try: + with urlopen(request) as response: + self.fail(f"Expected {status}, received {response.status}") + except HTTPError as error: + try: + self.assertEqual(error.code, status) + error.read() + finally: + error.close() + + def assert_redirects_to_login(self, path): + """Expect a page to redirect to the login page (section 31 point 1).""" + opener = build_opener(_NoRedirect) + try: + with opener.open(self.request(path)) as response: + self.fail(f"Expected a redirect, received {response.status}") + except HTTPError as error: + try: + self.assertEqual(error.code, 302) + self.assertEqual(error.headers["Location"], "/login") + error.read() + finally: + error.close() + + # -- endpoint helpers ------------------------------------------------- + + def key_profiles(self): + return self.get_json("/api/keys") + + def get_setup(self): + return self.get_json("/api/setup") + + def get_settings(self): + return self.get_json("/api/settings") + + def get_health_checks(self): + return self.get_json("/api/health-checks") + + def get_key_status(self): + return self.get_json("/api/key-status") + + def get_previous_values(self): + return self.get_json("/api/previous-values") + + def get_alerts(self): + return self.get_json("/api/alerts") + + def get_record(self, health_check_id): + return self.get_json(f"/api/health-checks/{health_check_id}") def post_health_check(self, payload): """Store one check and return its id.""" @@ -202,33 +327,15 @@ class ServerTestCase(unittest.TestCase): def post_acknowledgement(self, payload): return self.post_json("/api/alerts/acknowledge", payload) - def get_record(self, health_check_id): - with urlopen(f"{self.base_url}/api/health-checks/{health_check_id}") as response: - self.assertEqual(response.status, 200) - return json.load(response) - - def get_alerts(self): - with urlopen(f"{self.base_url}/api/alerts") as response: - self.assertEqual(response.status, 200) - return json.load(response) - def get_export_rows(self): """Return the CSV export as parsed rows.""" - with urlopen(f"{self.base_url}/api/export") as response: + with self.get("/api/export") as response: body = response.read().decode("utf-8") return list(csv.reader(io.StringIO(body))) def assert_rejected_at(self, path, payload, status=400): """Post a payload to one endpoint and expect an error status.""" - try: - with self.post_json(path, payload) as response: - self.fail(f"Expected {status}, received {response.status}") - except HTTPError as error: - try: - self.assertEqual(error.code, status) - error.read() - finally: - error.close() + self.assert_status(path, status, method="POST", payload=payload) def assert_rejected(self, payload, status=400): self.assert_rejected_at("/api/health-checks", payload, status) @@ -260,6 +367,7 @@ class AppHandlerTests(ServerTestCase): def setUp(self): super().setUp() self.store_setup() + self.authenticate() def test_health_endpoint_returns_json(self): with urlopen(f"{self.base_url}/health") as response: @@ -321,10 +429,8 @@ class AppHandlerTests(ServerTestCase): self.assertIsNone(status[2]["last_checked_at"]) def test_previous_values_api_is_empty_before_anything_is_saved(self): - with urlopen(f"{self.base_url}/api/previous-values") as response: - values = json.load(response) + values = self.get_previous_values() - self.assertEqual(response.status, 200) self.assertEqual([entry["key_id"] for entry in values["keys"]], [1, 2, 3]) self.assertIsNone(values["keys"][0]["firmware_version"]) self.assertIsNone(values["keys"][0]["software_version"]) @@ -337,10 +443,8 @@ class AppHandlerTests(ServerTestCase): payload["key_check"]["firmware_version"] = "1.2.3" self.post_health_check(payload) - with urlopen(f"{self.base_url}/api/previous-values") as response: - values = json.load(response) + values = self.get_previous_values() - self.assertEqual(response.status, 200) by_key = {entry["key_id"]: entry for entry in values["keys"]} self.assertEqual(by_key[key["id"]]["firmware_version"], "1.2.3") self.assertEqual(by_key[key["id"]]["address_path"], ADDRESS_PATH) @@ -352,7 +456,7 @@ class AppHandlerTests(ServerTestCase): payload["checked_at"] = "2027-04-01" saved_id = self.post_health_check(payload) - with urlopen(f"{self.base_url}/api/export") as response: + with self.get("/api/export") as response: body = response.read().decode("utf-8") content_type = response.headers["Content-Type"] disposition = response.headers["Content-Disposition"] @@ -418,7 +522,7 @@ class AppHandlerTests(ServerTestCase): ) def test_health_check_form_is_served_in_english(self): - with urlopen(f"{self.base_url}/health-check") as response: + with self.get("/health-check") as response: body = response.read().decode("utf-8") self.assertEqual(response.status, 200) @@ -433,7 +537,7 @@ class AppHandlerTests(ServerTestCase): self.assertIn("Save health check", body) def test_setup_page_is_served_in_english(self): - with urlopen(f"{self.base_url}/setup") as response: + with self.get("/setup") as response: body = response.read().decode("utf-8") self.assertEqual(response.status, 200) @@ -444,7 +548,7 @@ class AppHandlerTests(ServerTestCase): self.assertIn("Save key setup", body) def test_settings_page_is_served_in_english(self): - with urlopen(f"{self.base_url}/settings") as response: + with self.get("/settings") as response: body = response.read().decode("utf-8") self.assertEqual(response.status, 200) @@ -464,7 +568,7 @@ class AppHandlerTests(ServerTestCase): self.assertIn("Never enter seed phrases", body) def test_history_page_is_served_in_english(self): - with urlopen(f"{self.base_url}/history") as response: + with self.get("/history") as response: body = response.read().decode("utf-8") self.assertEqual(response.status, 200) @@ -472,8 +576,18 @@ class AppHandlerTests(ServerTestCase): self.assertIn('id="history-list"', body) self.assertIn("Saved health checks", body) + def test_every_page_loads_the_session_script(self): + # The five pages load session.js, which puts the CSRF header on every + # fetch, so the existing page scripts do not have to change + # (section 31 point 1). + for path in ("/", "/setup", "/settings", "/health-check", "/history"): + with self.get(path) as response: + body = response.read().decode("utf-8") + self.assertEqual(response.status, 200) + self.assertIn('