"""HTTP tests for the dashboard server. 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, 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. """ import csv from http.cookies import SimpleCookie from http.server import ThreadingHTTPServer import io import json import os import tempfile import threading import unittest from urllib.error import HTTPError 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 # The address path each key slot is configured with (sections 25.1 and 26.2). ADDRESS_PATH = "m/48'/0'/0'/2'" SECOND_ADDRESS_PATH = "m/48'/1'/0'/2'" THIRD_ADDRESS_PATH = "m/48'/2'/0'/2'" # The path a rotation of each key records: it must be new and unique # (section 26.3). ROTATION_PATHS = { 1: "m/48'/10'/0'/2'", 2: "m/48'/11'/0'/2'", 3: "m/48'/12'/0'/2'", } # The key setup most tests start from (section 23.2). DEFAULT_SETUP = [ {"key_number": 1, "name": "SeedSigner", "type": "hardware", "address_path": ADDRESS_PATH}, {"key_number": 2, "name": "Blockstream Jade", "type": "hardware", "address_path": SECOND_ADDRESS_PATH}, {"key_number": 3, "name": "Nunchuk", "type": "cloud", "address_path": THIRD_ADDRESS_PATH}, ] # A setup with the cloud key in the first slot, renamed hardware keys, and a # different address path per key. RENAMED_SETUP = [ {"key_number": 1, "name": "Coinbase", "type": "cloud", "address_path": ADDRESS_PATH}, {"key_number": 2, "name": "ColdCard", "type": "hardware", "address_path": SECOND_ADDRESS_PATH}, {"key_number": 3, "name": "Jade", "type": "hardware", "address_path": THIRD_ADDRESS_PATH}, ] 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. The recorded address path matches the stored one unless a test asks for another one (section 25.1). """ if wallet_software is None: wallet_software = key["name"] if key["type"] == "cloud" else "Sparrow Wallet" labels = list(dict.fromkeys((key["name"], wallet_software))) entry = { "key_id": key["id"], "available": 1, "address_path": address_path if address_path is not None else key["address_path"], "comments": "", } if key["type"] == "hardware": entry.update({ "hardware_works": 1, "firmware_version": "1.0.0", "seed_backup_verified": "OK", }) return { "checked_at": "2026-10-01", "wallet_software": wallet_software, "software_version": "1.8.0", "software_compatibility_status": "OK", "software_comments": "", "contact_info_verified": "Confirmed current", "comments": "Annual review", "key_check": entry, "ai_security_checks": [ {"provider": label, "status": "SECURE", "comments": ""} for label in labels ], } def unavailable_payload(key): """Return the payload the form sends for a key that was not available.""" return { "checked_at": "2026-10-01", "wallet_software": None, "software_compatibility_status": "NOT_ASSESSED", "contact_info_verified": "Confirmed current", "comments": "Annual review", "key_check": { "key_id": key["id"], "available": 0, "comments": "Key is with the third holder", }, "ai_security_checks": [], } def mismatch_payload(key, address_path="m/48'/9'/0'/2'"): """Return the minimal payload the form sends when the path does not match. Everything else about the key is left out, because the key could not be checked (section 25.1). """ return { "checked_at": "2026-10-01", "contact_info_verified": "Confirmed current", "comments": "Annual review", "key_check": { "key_id": key["id"], "available": 1, "address_path": address_path, "comments": "Path read from the device", }, } class ServerTestCase(unittest.TestCase): """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() self.database_path = os.path.join(self.temp_dir.name, "test.sqlite3") initialize_database(self.database_path) self.previous_database_path = os.environ.get("DATABASE_PATH") os.environ["DATABASE_PATH"] = self.database_path self.server = ThreadingHTTPServer(("127.0.0.1", 0), AppHandler) 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() self.server.server_close() self.thread.join(timeout=2) if self.previous_database_path is None: os.environ.pop("DATABASE_PATH", None) else: 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 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 authenticate(self): """Store the admin and sign in, so the tests act as the single user.""" self.store_admin() self.sign_in() # -- HTTP helpers ----------------------------------------------------- def cookie_header(self): return "; ".join(f"{name}={value}" for name, value in self.cookies.items()) 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): 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}, ) 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.""" with self.post_json("/api/health-checks", payload) as response: self.assertEqual(response.status, 201) return json.load(response)["id"] def post_setup(self, payload): return self.post_json("/api/setup", payload) def post_key_settings(self, payload): return self.post_json("/api/settings/keys", payload) def post_wallet_software(self, names): return self.post_json("/api/settings/wallet-software", {"wallet_software": names}) def post_rotation(self, key_id, payload): return self.post_json(f"/api/keys/{key_id}/rotate", payload) def post_acknowledgement(self, payload): return self.post_json("/api/alerts/acknowledge", payload) def get_export_rows(self): """Return the CSV export as parsed rows.""" 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.""" 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) def assert_setup_rejected(self, payload, status=400): self.assert_rejected_at("/api/setup", payload, status) def rotation_path(self, key_id): """Return the new address path a rotation of one key records.""" return ROTATION_PATHS[key_id] def rotate(self, key_id, keep_name=True, name="", address_path=None, **extra): """Rotate one key and return the stored settings the server answers.""" payload = { "replaced": True, "keep_name": keep_name, "name": name, "address_path": address_path or self.rotation_path(key_id), } payload.update(extra) with self.post_rotation(key_id, payload) as response: self.assertEqual(response.status, 200) return json.load(response) class AppHandlerTests(ServerTestCase): """The endpoints once the key setup is stored.""" 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: self.assertEqual(response.status, 200) self.assertEqual(json.load(response), {"status": "ok"}) self.assertEqual(response.headers["X-Content-Type-Options"], "nosniff") def test_key_api_returns_the_configured_profiles(self): keys = self.key_profiles() self.assertEqual([key["key_number"] for key in keys], [1, 2, 3]) self.assertEqual( [key["name"] for key in keys], ["SeedSigner", "Blockstream Jade", "Nunchuk"], ) self.assertEqual([key["type"] for key in keys], ["hardware", "hardware", "cloud"]) # The address path is part of the key's identity, and every key has its # own one (sections 25.1 and 26.2). self.assertEqual( [key["address_path"] for key in keys], [ADDRESS_PATH, SECOND_ADDRESS_PATH, THIRD_ADDRESS_PATH], ) # The configured name is the product label, so there is no device field. self.assertNotIn("device", keys[0]) def test_setup_api_reports_the_stored_setup(self): setup = self.get_setup() self.assertTrue(setup["configured"]) self.assertEqual([key["name"] for key in setup["keys"]], ["SeedSigner", "Blockstream Jade", "Nunchuk"]) def test_a_stored_setup_cannot_be_replaced(self): self.assert_setup_rejected({"keys": RENAMED_SETUP}, status=409) self.assertEqual([key["name"] for key in self.key_profiles()], ["SeedSigner", "Blockstream Jade", "Nunchuk"]) def test_key_status_api_is_empty_before_anything_is_saved(self): status = self.get_key_status() self.assertEqual([entry["key_number"] for entry in status], [1, 2, 3]) self.assertEqual([entry["last_checked_at"] for entry in status], [None, None, None]) self.assertEqual([entry["next_check_due"] for entry in status], [None, None, None]) def test_key_status_api_lists_each_key_with_its_newest_check(self): payload = sample_payload(self.key_profiles()[0]) payload["checked_at"] = "2027-03-01" self.post_health_check(payload) status = self.get_key_status() self.assertEqual([entry["key_number"] for entry in status], [1, 2, 3]) self.assertEqual([entry["type"] for entry in status], ["hardware", "hardware", "cloud"]) self.assertEqual(status[0]["name"], "SeedSigner") self.assertEqual(status[0]["last_checked_at"], "2027-03-01") self.assertEqual(status[0]["next_check_due"], "2028-03-01") self.assertIsNone(status[1]["last_checked_at"]) self.assertIsNone(status[2]["last_checked_at"]) def test_previous_values_api_is_empty_before_anything_is_saved(self): values = self.get_previous_values() 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"]) def test_previous_values_api_reports_the_last_saved_values(self): key = self.key_profiles()[0] payload = sample_payload(key) payload["checked_at"] = "2027-06-01" payload["software_version"] = "1.8.5" payload["key_check"]["firmware_version"] = "1.2.3" self.post_health_check(payload) values = self.get_previous_values() 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) self.assertEqual(by_key[key["id"]]["wallet_software"], "Sparrow Wallet") self.assertEqual(by_key[key["id"]]["software_version"], "1.8.5") def test_export_api_returns_a_csv_download(self): payload = sample_payload(self.key_profiles()[0]) payload["checked_at"] = "2027-04-01" saved_id = self.post_health_check(payload) with self.get("/api/export") as response: body = response.read().decode("utf-8") content_type = response.headers["Content-Type"] disposition = response.headers["Content-Disposition"] self.assertEqual(response.status, 200) self.assertEqual(content_type, "text/csv; charset=utf-8") self.assertIn("vardkey-export.csv", disposition) rows = list(csv.reader(io.StringIO(body))) self.assertEqual(rows[0], list(HEADERS)) self.assertEqual(len(rows), 2) self.assertEqual(rows[1][0], str(saved_id)) values = dict(zip(HEADERS, rows[1])) self.assertEqual(values["Check date"], "2027-04-01") self.assertEqual(values["Next check due"], "2028-04-01") self.assertEqual(values["Key number"], "1") self.assertEqual(values["Key name"], "SeedSigner") self.assertEqual(values["Available"], "Yes") self.assertEqual(values["Hardware works"], "Yes") self.assertEqual(values["Seed backup verified"], "OK") self.assertEqual(values["Address path"], ADDRESS_PATH) self.assertEqual(values["Address path verified"], "OK") self.assertEqual(values["Wallet software"], "Sparrow Wallet") # The contact confirmation is a status, not a yes/no flag (section 23.1). self.assertEqual(values["Contact details confirmed"], "Confirmed current") self.assertIn("SeedSigner: SECURE", values["Security status"]) # The new closure column is last, and an open check leaves it empty # (section 27). self.assertEqual(HEADERS[-1], "Follow-up closed") self.assertEqual(values["Follow-up closed"], "") # The two derived cloud columns are gone (section 25.6). self.assertNotIn("Cloud health status", HEADERS) self.assertNotIn("Cloud provider operational", HEADERS) def test_export_api_leaves_the_skipped_columns_empty(self): saved_id = self.post_health_check(unavailable_payload(self.key_profiles()[1])) rows = self.get_export_rows() values = dict(zip(HEADERS, rows[1])) self.assertEqual(values["Check id"], str(saved_id)) self.assertEqual(values["Available"], "No") self.assertEqual(values["Key comments"], "Key is with the third holder") self.assertEqual(values["Wallet software"], "") self.assertEqual(values["Software compatibility"], "NOT_ASSESSED") self.assertEqual(values["Security status"], "") def test_the_export_lists_the_closures_that_belong_to_a_key(self): key = self.key_profiles()[1] saved_id = self.post_health_check(unavailable_payload(key)) self.rotate(key["id"]) rows = self.get_export_rows() values = dict(zip(HEADERS, rows[1])) self.assertEqual(values["Check id"], str(saved_id)) # A closure is written as the code, the action and the date, in the last # column (section 27). self.assertRegex( values["Follow-up closed"], r"^key_unavailable: rotate \(\d{4}-\d{2}-\d{2}\)$", ) def test_health_check_form_is_served_in_english(self): with self.get("/health-check") as response: body = response.read().decode("utf-8") self.assertEqual(response.status, 200) self.assertIn('', body) self.assertIn('id="health-check-form"', body) self.assertIn('id="key-select"', body) self.assertIn('id="address-path-warning"', body) # The form names the keys that an open alert blocks (section 26.1). self.assertIn('id="blocked-keys-note"', body) self.assertIn('id="blocked-keys-list"', body) self.assertIn("Never enter seed phrases", body) self.assertIn("Save health check", body) def test_setup_page_is_served_in_english(self): with self.get("/setup") as response: body = response.read().decode("utf-8") self.assertEqual(response.status, 200) self.assertIn('', body) self.assertIn('id="setup-form"', body) self.assertIn('name="key_1_address_path"', body) self.assertIn("Never enter seed phrases", body) self.assertIn("Save key setup", body) def test_settings_page_is_served_in_english(self): with self.get("/settings") as response: body = response.read().decode("utf-8") self.assertEqual(response.status, 200) self.assertIn('', body) self.assertIn('id="wallet-software-list"', body) self.assertIn('id="rotation-list"', body) self.assertIn('id="save-keys"', body) self.assertIn("Save keys", body) self.assertIn("01 / Wallet software", body) self.assertIn("02 / Key rotation", body) # The key names, the address paths and the type are changed in the # rotation section, so the page has no separate keys section # (section 28). self.assertNotIn('id="keys-list"', body) self.assertIn("Rotating a key creates a new wallet", body) self.assertIn("The address path must change", body) self.assertIn("Never enter seed phrases", body) def test_history_page_is_served_in_english(self): with self.get("/history") as response: body = response.read().decode("utf-8") self.assertEqual(response.status, 200) self.assertIn('', body) 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('