Cover the settings, rotation and acknowledgement endpoints and the address path over HTTP (section 25.7)

This commit is contained in:
ai-bot committed 2026-10-04 11:45:01 +00:00
1 parent 47599e4785
commit 435c0c4a7a
1 file changed
+592 -55
+592 -55
View File
@@ -21,30 +21,36 @@ from database import initialize_database, save_key_setup
from export import HEADERS
# The address path the keys are configured with (section 25.1).
ADDRESS_PATH = "m/48'/0'/0'/2'"
# The key setup most tests start from (section 23.2).
DEFAULT_SETUP = [
{"key_number": 1, "name": "SeedSigner", "type": "hardware"},
{"key_number": 2, "name": "Blockstream Jade", "type": "hardware"},
{"key_number": 3, "name": "Nunchuk", "type": "cloud"},
{"key_number": 1, "name": "SeedSigner", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 2, "name": "Blockstream Jade", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 3, "name": "Nunchuk", "type": "cloud", "address_path": ADDRESS_PATH},
]
# A setup with the cloud key in the first slot and a renamed hardware key.
# 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"},
{"key_number": 2, "name": "ColdCard", "type": "hardware"},
{"key_number": 3, "name": "Jade", "type": "hardware"},
{"key_number": 1, "name": "Coinbase", "type": "cloud", "address_path": ADDRESS_PATH},
{"key_number": 2, "name": "ColdCard", "type": "hardware", "address_path": "m/48'/1'/0'/2'"},
{"key_number": 3, "name": "Jade", "type": "hardware", "address_path": "m/48'/2'/0'/2'"},
]
def sample_payload(key, wallet_software=None):
"""Return a valid single-key payload for the given key profile."""
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_verified": "OK",
"address_path": "m/48'/0'/0'/2'/0/0",
"address_path": address_path if address_path is not None else key["address_path"],
"comments": "",
}
if key["type"] == "hardware":
@@ -53,8 +59,6 @@ def sample_payload(key, wallet_software=None):
"firmware_version": "1.0.0",
"seed_backup_verified": "OK",
})
else:
entry.update({"cloud_health_status": "OK", "cloud_provider_operational": 1})
return {
"checked_at": "2026-10-01",
"wallet_software": wallet_software,
@@ -72,25 +76,40 @@ def sample_payload(key, wallet_software=None):
def unavailable_payload(key):
"""Return the payload the form sends for a key that was not available."""
entry = {
"key_id": key["id"],
"available": 0,
"comments": "Key is with the third holder",
}
if key["type"] == "cloud":
# The form derives these from availability alone (section 20).
entry.update({"cloud_health_status": "PROBLEM", "cloud_provider_operational": 0})
return {
"checked_at": "2026-10-01",
"wallet_software": None,
"software_compatibility_status": "NOT_ASSESSED",
"contact_info_verified": "Confirmed current",
"comments": "Annual review",
"key_check": entry,
"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."""
@@ -129,6 +148,16 @@ class ServerTestCase(unittest.TestCase):
self.assertEqual(response.status, 200)
return json.load(response)
def get_settings(self):
with urlopen(f"{self.base_url}/api/settings") as response:
self.assertEqual(response.status, 200)
return json.load(response)
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 post_json(self, path, payload):
request = Request(
f"{self.base_url}{path}",
@@ -147,6 +176,18 @@ class ServerTestCase(unittest.TestCase):
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_record(self, health_check_id):
with urlopen(f"{self.base_url}/api/health-checks/{health_check_id}") as response:
self.assertEqual(response.status, 200)
@@ -157,9 +198,10 @@ class ServerTestCase(unittest.TestCase):
self.assertEqual(response.status, 200)
return json.load(response)
def assert_rejected(self, payload, status=400):
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("/api/health-checks", payload) as response:
with self.post_json(path, payload) as response:
self.fail(f"Expected {status}, received {response.status}")
except HTTPError as error:
try:
@@ -168,16 +210,24 @@ class ServerTestCase(unittest.TestCase):
finally:
error.close()
def assert_rejected(self, payload, status=400):
self.assert_rejected_at("/api/health-checks", payload, status)
def assert_setup_rejected(self, payload, status=400):
try:
with self.post_setup(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_rejected_at("/api/setup", payload, status)
def rotate(self, key_id, keep_name=True, name="", **extra):
"""Rotate one key and return the stored settings the server answers."""
payload = {
"replaced": True,
"address_path_unchanged": True,
"keep_name": keep_name,
"name": name,
}
payload.update(extra)
with self.post_rotation(key_id, payload) as response:
self.assertEqual(response.status, 200)
return json.load(response)
class AppHandlerTests(ServerTestCase):
@@ -202,6 +252,8 @@ class AppHandlerTests(ServerTestCase):
["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 (section 25.1).
self.assertEqual([key["address_path"] for key in keys], [ADDRESS_PATH] * 3)
# The configured name is the product label, so there is no device field.
self.assertNotIn("device", keys[0])
@@ -267,7 +319,7 @@ class AppHandlerTests(ServerTestCase):
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"], "m/48'/0'/0'/2'/0/0")
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")
@@ -298,10 +350,15 @@ class AppHandlerTests(ServerTestCase):
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 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]))
@@ -327,6 +384,7 @@ class AppHandlerTests(ServerTestCase):
self.assertIn('<html lang="en">', body)
self.assertIn('id="health-check-form"', body)
self.assertIn('id="key-select"', body)
self.assertIn('id="address-path-warning"', body)
self.assertIn("Never enter seed phrases", body)
self.assertIn("Save health check", body)
@@ -337,9 +395,24 @@ class AppHandlerTests(ServerTestCase):
self.assertEqual(response.status, 200)
self.assertIn('<html lang="en">', 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 urlopen(f"{self.base_url}/settings") as response:
body = response.read().decode("utf-8")
self.assertEqual(response.status, 200)
self.assertIn('<html lang="en">', body)
self.assertIn('id="keys-list"', body)
self.assertIn('id="wallet-software-list"', body)
self.assertIn('id="rotation-list"', body)
self.assertIn("Rotate selected keys", body)
# The funds have to be moved to the new wallet (section 25.2).
self.assertIn("Rotating a key creates a new wallet", body)
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:
body = response.read().decode("utf-8")
@@ -349,13 +422,14 @@ class AppHandlerTests(ServerTestCase):
self.assertIn('id="history-list"', body)
self.assertIn("Saved health checks", body)
def test_dashboard_links_to_the_form_the_history_and_the_export(self):
def test_dashboard_links_to_the_form_the_history_the_export_and_the_settings(self):
with urlopen(self.base_url) as response:
body = response.read().decode("utf-8")
self.assertIn('href="/health-check"', body)
self.assertIn('href="/history"', body)
self.assertIn('href="/api/export"', body)
self.assertIn('href="/settings"', body)
self.assertIn("Download CSV", body)
self.assertNotIn("Report export is not implemented", body)
@@ -373,6 +447,10 @@ class AppHandlerTests(ServerTestCase):
self.assertIn("Key 2", alerts[0]["source"])
self.assertEqual(alerts[0]["check_id"], saved_id)
self.assertEqual(alerts[0]["checked_at"], "2026-10-01")
# The alert names the action that closes it and the key it came from
# (sections 25.2 and 25.3).
self.assertEqual(alerts[0]["actions"], ["rotate"])
self.assertEqual(alerts[0]["key_id"], self.key_profiles()[1]["id"])
def test_alerts_api_keeps_alerts_from_older_checks(self):
older = unavailable_payload(self.key_profiles()[1])
@@ -430,9 +508,7 @@ class AppHandlerTests(ServerTestCase):
key = self.key_profiles()[0]
saved_id = self.post_health_check(sample_payload(key))
with urlopen(f"{self.base_url}/api/health-checks") as response:
summaries = json.load(response)
summary = next(entry for entry in summaries if entry["id"] == saved_id)
summary = next(entry for entry in self.get_health_checks() if entry["id"] == saved_id)
self.assertEqual(summary["key_numbers"], [1])
record = self.get_record(saved_id)
@@ -442,6 +518,8 @@ class AppHandlerTests(ServerTestCase):
self.assertEqual(record["contact_info_verified"], "Confirmed current")
self.assertEqual(len(record["key_checks"]), 1)
self.assertEqual(record["key_checks"][0]["key_number"], 1)
self.assertEqual(record["key_checks"][0]["address_path"], ADDRESS_PATH)
self.assertEqual(record["key_checks"][0]["address_path_verified"], "OK")
self.assertEqual(
[entry["provider"] for entry in record["ai_security_checks"]],
["SeedSigner", "Sparrow Wallet"],
@@ -516,7 +594,7 @@ class AppHandlerTests(ServerTestCase):
del payload["key_check"]["hardware_works"]
self.assert_rejected(payload)
def test_an_unavailable_cloud_key_keeps_its_derived_cloud_results(self):
def test_an_unavailable_cloud_key_records_nothing_else(self):
key = self.key_profiles()[2]
saved_id = self.post_health_check(unavailable_payload(key))
@@ -525,14 +603,14 @@ class AppHandlerTests(ServerTestCase):
self.assertIsNone(record["wallet_software"])
self.assertEqual(record["software_compatibility_status"], "NOT_ASSESSED")
self.assertEqual(record["ai_security_checks"], [])
self.assertEqual(record["key_checks"][0]["cloud_health_status"], "PROBLEM")
self.assertEqual(record["key_checks"][0]["cloud_provider_operational"], 0)
self.assertEqual(record["key_checks"][0]["available"], 0)
self.assertIsNone(record["key_checks"][0]["address_path_verified"])
self.assertIsNone(record["key_checks"][0]["address_path"])
alerts = self.get_alerts()
self.assertEqual([alert["code"] for alert in alerts], ["key_unavailable"])
self.assertIn("cloud provider", alerts[0]["message"])
self.assertIn("Key 3", alerts[0]["source"])
def test_invalid_health_check_is_rejected(self):
payload = sample_payload(self.key_profiles()[0])
@@ -569,6 +647,81 @@ class AppHandlerTests(ServerTestCase):
rejected["software_compatibility_status"] = "PROBLEM"
self.assert_rejected(rejected)
def test_the_server_records_the_address_path_result(self):
key = self.key_profiles()[0]
matching = self.post_health_check(sample_payload(key))
self.assertEqual(
self.get_record(matching)["key_checks"][0]["address_path_verified"], "OK"
)
mismatch = self.post_health_check(mismatch_payload(key))
self.assertEqual(
self.get_record(mismatch)["key_checks"][0]["address_path_verified"], "PROBLEM"
)
def test_a_mismatch_records_only_the_minimal_content(self):
key = self.key_profiles()[0]
saved_id = self.post_health_check(mismatch_payload(key))
record = self.get_record(saved_id)
key_check = record["key_checks"][0]
# The recorded path and the key note are kept, while everything else
# stays empty (section 25.1).
self.assertEqual(key_check["address_path"], "m/48'/9'/0'/2'")
self.assertEqual(key_check["address_path_verified"], "PROBLEM")
self.assertEqual(key_check["comments"], "Path read from the device")
self.assertIsNone(key_check["hardware_works"])
self.assertIsNone(key_check["firmware_version"])
self.assertIsNone(key_check["seed_backup_verified"])
self.assertIsNone(record["wallet_software"])
self.assertEqual(record["software_compatibility_status"], "NOT_ASSESSED")
self.assertEqual(record["ai_security_checks"], [])
self.assertEqual(record["comments"], "Annual review")
alerts = self.get_alerts()
self.assertEqual([alert["code"] for alert in alerts], ["address_path_mismatch"])
self.assertEqual(alerts[0]["severity"], "critical")
self.assertEqual(alerts[0]["check_id"], saved_id)
def test_a_mismatch_rejects_software_or_security_results(self):
key = self.key_profiles()[0]
recorded = (
("wallet_software", "Sparrow Wallet"),
("ai_security_checks", [{"provider": "SeedSigner", "status": "SECURE", "comments": ""}]),
("software_compatibility_status", "OK"),
)
for field, value in recorded:
payload = mismatch_payload(key)
payload[field] = value
self.assert_rejected(payload)
def test_an_unavailable_key_never_reports_a_mismatch(self):
key = self.key_profiles()[1]
payload = unavailable_payload(key)
payload["key_check"]["address_path"] = ADDRESS_PATH
saved_id = self.post_health_check(payload)
record = self.get_record(saved_id)
self.assertIsNone(record["key_checks"][0]["address_path"])
self.assertIsNone(record["key_checks"][0]["address_path_verified"])
self.assertEqual([alert["code"] for alert in self.get_alerts()], ["key_unavailable"])
def test_a_submitted_address_path_result_is_ignored(self):
# The client never sends the result, and the server overrules it anyway
# (section 25.1).
key = self.key_profiles()[0]
payload = mismatch_payload(key)
payload["key_check"]["address_path_verified"] = "OK"
saved_id = self.post_health_check(payload)
self.assertEqual(
self.get_record(saved_id)["key_checks"][0]["address_path_verified"], "PROBLEM"
)
def test_the_old_contact_flag_is_rejected(self):
# Only the two contact statuses are recorded (section 23.1).
for value in (1, 0, "yes"):
@@ -679,6 +832,22 @@ class RenamedSetupTests(ServerTestCase):
["ColdCard", "Sparrow Wallet"],
)
def test_the_address_path_of_the_selected_key_is_the_one_that_counts(self):
# The three keys have different paths, so a path that belongs to another
# key is a mismatch for this one (section 25.1).
key = self.key_profiles()[2]
matching = self.post_health_check(sample_payload(key))
self.assertEqual(
self.get_record(matching)["key_checks"][0]["address_path_verified"], "OK"
)
other_path = self.key_profiles()[1]["address_path"]
mismatch = self.post_health_check(mismatch_payload(key, other_path))
self.assertEqual(
self.get_record(mismatch)["key_checks"][0]["address_path_verified"], "PROBLEM"
)
def test_the_dashboard_reports_the_configured_names(self):
with urlopen(f"{self.base_url}/api/key-status") as response:
status = json.load(response)
@@ -701,6 +870,340 @@ class RenamedSetupTests(ServerTestCase):
self.assertEqual(values["Security status"], "ColdCard: SECURE; Sparrow Wallet: SECURE")
class SettingsApiTests(ServerTestCase):
"""The settings page reads and writes one section at a time (section 25.4)."""
def setUp(self):
super().setUp()
self.store_setup()
def test_the_settings_api_returns_the_keys_and_the_software_list(self):
settings = self.get_settings()
self.assertEqual(
[key["name"] for key in settings["keys"]],
["SeedSigner", "Blockstream Jade", "Nunchuk"],
)
self.assertEqual(
[key["address_path"] for key in settings["keys"]], [ADDRESS_PATH] * 3
)
self.assertEqual(settings["wallet_software"], ["Sparrow Wallet"])
def test_the_settings_api_reports_whether_a_key_has_checks(self):
self.assertEqual([key["has_checks"] for key in self.get_settings()["keys"]],
[False, False, False])
self.post_health_check(sample_payload(self.key_profiles()[0]))
self.assertEqual([key["has_checks"] for key in self.get_settings()["keys"]],
[True, False, False])
def test_a_key_name_can_be_changed(self):
key = self.key_profiles()[0]
with self.post_key_settings({
"key_id": key["id"],
"name": " ColdCard ",
"address_path": ADDRESS_PATH,
}) as response:
self.assertEqual(response.status, 200)
body = json.load(response)
self.assertEqual(body["keys"][0]["name"], "ColdCard")
self.assertEqual(self.key_profiles()[0]["name"], "ColdCard")
# The type is locked (section 25.2).
self.assertEqual(self.key_profiles()[0]["type"], "hardware")
def test_the_address_path_can_be_changed_until_the_key_has_a_check(self):
key = self.key_profiles()[0]
with self.post_key_settings({
"key_id": key["id"],
"name": key["name"],
"address_path": "m/48'/7'/0'/2'",
}) as response:
self.assertEqual(response.status, 200)
self.assertEqual(self.key_profiles()[0]["address_path"], "m/48'/7'/0'/2'")
def test_the_address_path_is_locked_after_the_first_check(self):
key = self.key_profiles()[0]
self.post_health_check(sample_payload(key))
# A different path is refused, while the stored one may be sent again
# (section 25.1).
self.assert_rejected_at("/api/settings/keys", {
"key_id": key["id"],
"name": key["name"],
"address_path": "m/48'/8'/0'/2'",
}, status=409)
with self.post_key_settings({
"key_id": key["id"],
"name": "ColdCard",
"address_path": ADDRESS_PATH,
}) as response:
self.assertEqual(response.status, 200)
self.assertEqual(self.key_profiles()[0]["name"], "ColdCard")
self.assertEqual(self.key_profiles()[0]["address_path"], ADDRESS_PATH)
def test_a_name_that_repeats_another_key_is_rejected(self):
key = self.key_profiles()[0]
for name in ("Nunchuk", "nunchuk"):
self.assert_rejected_at("/api/settings/keys", {
"key_id": key["id"],
"name": name,
"address_path": ADDRESS_PATH,
})
def test_an_unknown_key_or_a_missing_path_is_rejected(self):
key = self.key_profiles()[0]
for payload in (
{"key_id": 999, "name": "ColdCard", "address_path": ADDRESS_PATH},
{"key_id": key["id"], "name": "ColdCard", "address_path": ""},
{"key_id": key["id"], "name": "", "address_path": ADDRESS_PATH},
):
self.assert_rejected_at("/api/settings/keys", payload)
def test_the_wallet_software_list_is_stored_whole(self):
with self.post_wallet_software(["Sparrow Wallet", "BlueWallet"]) as response:
self.assertEqual(response.status, 200)
body = json.load(response)
self.assertEqual(body["wallet_software"], ["Sparrow Wallet", "BlueWallet"])
self.assertEqual(self.get_settings()["wallet_software"], ["Sparrow Wallet", "BlueWallet"])
# Replacing the list removes the entries that are not sent again.
with self.post_wallet_software(["BlueWallet"]) as response:
self.assertEqual(response.status, 200)
self.assertEqual(self.get_settings()["wallet_software"], ["BlueWallet"])
def test_the_settings_list_completes_the_wallet_software_choices(self):
key = self.key_profiles()[0]
with self.post_wallet_software(["BlueWallet"]) as response:
self.assertEqual(response.status, 200)
# A name from the settings list is a choice, and a name that is in
# neither the list nor a cloud key is not (section 25.4).
saved_id = self.post_health_check(sample_payload(key, wallet_software="BlueWallet"))
self.assertEqual(self.get_record(saved_id)["wallet_software"], "BlueWallet")
self.assert_rejected(sample_payload(key, wallet_software="Sparrow Wallet"))
def test_a_removed_software_name_still_renders_in_the_history(self):
key = self.key_profiles()[0]
with self.post_wallet_software(["BlueWallet"]) as response:
self.assertEqual(response.status, 200)
saved_id = self.post_health_check(sample_payload(key, wallet_software="BlueWallet"))
with self.post_wallet_software(["Sparrow Wallet"]) as response:
self.assertEqual(response.status, 200)
# The selected software is kept as free text, so an earlier check is not
# changed by removing the name (section 25.4).
self.assertEqual(self.get_record(saved_id)["wallet_software"], "BlueWallet")
def test_an_empty_list_or_a_cloud_key_name_is_rejected(self):
for names in ([], [" "], ["Nunchuk"], ["nunchuk"], ["Sparrow Wallet", "sparrow wallet"]):
self.assert_rejected_at(
"/api/settings/wallet-software", {"wallet_software": names}
)
def test_a_missing_software_list_is_rejected(self):
for payload in ({}, {"wallet_software": None}, {"wallet_software": "Sparrow Wallet"}):
self.assert_rejected_at("/api/settings/wallet-software", payload)
class RotationApiTests(ServerTestCase):
"""A rotation replaces one key and closes the alerts it raised (section 25.2)."""
def setUp(self):
super().setUp()
self.store_setup()
def test_a_rotation_keeps_the_name(self):
key = self.key_profiles()[0]
body = self.rotate(key["id"])
self.assertEqual(body["acknowledged"], [])
stored = self.key_profiles()[0]
self.assertEqual(stored["name"], key["name"])
self.assertEqual(stored["type"], key["type"])
self.assertEqual(stored["address_path"], key["address_path"])
def test_a_rotation_changes_the_name(self):
key = self.key_profiles()[1]
self.rotate(key["id"], keep_name=False, name=" Replacement ")
stored = self.key_profiles()[1]
self.assertEqual(stored["name"], "Replacement")
self.assertEqual(stored["address_path"], key["address_path"])
def test_a_rotation_needs_the_two_confirmations(self):
key = self.key_profiles()[0]
for field in ("replaced", "address_path_unchanged"):
for value in (None, False, 1, "yes"):
payload = {
"replaced": True,
"address_path_unchanged": True,
"keep_name": True,
}
payload[field] = value
self.assert_rejected_at(f"/api/keys/{key['id']}/rotate", payload)
def test_a_rotation_of_an_unknown_key_is_rejected(self):
self.assert_rejected_at("/api/keys/999/rotate", {
"replaced": True,
"address_path_unchanged": True,
"keep_name": True,
}, status=404)
def test_a_rotation_closes_the_alerts_of_its_key(self):
key = self.key_profiles()[1]
self.post_health_check(unavailable_payload(key))
self.assertEqual([alert["code"] for alert in self.get_alerts()], ["key_unavailable"])
body = self.rotate(key["id"])
self.assertEqual(
body["acknowledged"],
[{"code": "key_unavailable", "source": "Key 2: Blockstream Jade"}],
)
self.assertEqual(self.get_alerts(), [])
def test_a_rotation_leaves_the_other_keys_alone(self):
other = self.key_profiles()[1]
self.post_health_check(unavailable_payload(other))
self.rotate(self.key_profiles()[0]["id"])
alerts = self.get_alerts()
self.assertEqual([alert["code"] for alert in alerts], ["key_unavailable"])
self.assertIn("Key 2", alerts[0]["source"])
def test_a_rotation_does_not_close_a_software_alert(self):
key = self.key_profiles()[0]
payload = sample_payload(key)
payload["software_compatibility_status"] = "PROBLEM"
self.post_health_check(payload)
self.assertEqual([alert["code"] for alert in self.get_alerts()], ["software_incompatible"])
body = self.rotate(key["id"])
self.assertEqual(body["acknowledged"], [])
self.assertEqual([alert["code"] for alert in self.get_alerts()], ["software_incompatible"])
def test_a_rotation_does_not_change_an_earlier_check(self):
key = self.key_profiles()[1]
saved_id = self.post_health_check(unavailable_payload(key))
before = self.get_record(saved_id)
self.rotate(key["id"], keep_name=False, name="Replacement")
after = self.get_record(saved_id)
self.assertEqual(len(self.get_health_checks()), 1)
self.assertEqual(after["key_checks"][0]["available"], before["key_checks"][0]["available"])
self.assertEqual(after["key_checks"][0]["comments"], before["key_checks"][0]["comments"])
self.assertEqual(after["key_checks"][0]["key_number"], 2)
# The name shown is the name the key has now (section 25.2).
self.assertEqual(after["key_checks"][0]["name"], "Replacement")
class AcknowledgementApiTests(ServerTestCase):
"""An acknowledged alert stays hidden until a newer check raises it (section 25.3)."""
def setUp(self):
super().setUp()
self.store_setup()
def test_an_acknowledged_alert_disappears(self):
key = self.key_profiles()[1]
saved_id = self.post_health_check(unavailable_payload(key))
alerts = self.get_alerts()
self.assertEqual(len(alerts), 1)
with self.post_acknowledgement({
"code": alerts[0]["code"],
"source": alerts[0]["source"],
"reason": "The key was replaced",
}) as response:
self.assertEqual(response.status, 201)
self.assertEqual(self.get_alerts(), [])
# The saved check itself is untouched.
self.assertEqual(self.get_record(saved_id)["key_checks"][0]["available"], 0)
def test_a_newer_check_raises_the_alert_again(self):
key = self.key_profiles()[1]
older = unavailable_payload(key)
older["checked_at"] = "2026-10-01"
self.post_health_check(older)
alerts = self.get_alerts()
with self.post_acknowledgement({
"code": alerts[0]["code"],
"source": alerts[0]["source"],
"reason": "The key was replaced",
}) as response:
self.assertEqual(response.status, 201)
self.assertEqual(self.get_alerts(), [])
newer = unavailable_payload(key)
newer["checked_at"] = "2027-10-01"
self.post_health_check(newer)
alerts = self.get_alerts()
self.assertEqual([alert["code"] for alert in alerts], ["key_unavailable"])
self.assertEqual(alerts[0]["checked_at"], "2027-10-01")
def test_an_unknown_alert_is_rejected(self):
self.post_health_check(unavailable_payload(self.key_profiles()[1]))
for payload in (
{"code": "key_unavailable", "source": "Key 3: Nunchuk", "reason": "Done"},
{"code": "address_path_mismatch", "source": "Key 2: Blockstream Jade", "reason": "Done"},
):
self.assert_rejected_at("/api/alerts/acknowledge", payload, status=404)
def test_an_unknown_code_or_a_missing_reason_is_rejected(self):
self.post_health_check(unavailable_payload(self.key_profiles()[1]))
source = self.get_alerts()[0]["source"]
for payload in (
{"code": "cloud_provider_problem", "source": source, "reason": "Done"},
{"code": "address_verification_failed", "source": source, "reason": "Done"},
{"code": "key_unavailable", "source": source, "reason": ""},
{"code": "key_unavailable", "source": source},
{"code": "key_unavailable", "source": "", "reason": "Done"},
):
self.assert_rejected_at("/api/alerts/acknowledge", payload)
def test_an_informational_alert_can_be_closed_too(self):
payload = sample_payload(self.key_profiles()[0])
payload["contact_info_verified"] = "Needs external update"
self.post_health_check(payload)
alerts = self.get_alerts()
self.assertEqual([alert["code"] for alert in alerts], ["contact_info_unconfirmed"])
with self.post_acknowledgement({
"code": alerts[0]["code"],
"source": alerts[0]["source"],
"reason": "The contact details were updated externally",
}) as response:
self.assertEqual(response.status, 201)
self.assertEqual(self.get_alerts(), [])
class KeySetupApiTests(ServerTestCase):
"""The endpoints on a new database, before the key setup is stored."""
@@ -721,14 +1224,15 @@ class KeySetupApiTests(ServerTestCase):
self.assertTrue(body["configured"])
self.assertEqual([key["name"] for key in body["keys"]],
["SeedSigner", "Blockstream Jade", "Nunchuk"])
self.assertEqual([key["address_path"] for key in body["keys"]], [ADDRESS_PATH] * 3)
self.assertTrue(self.get_setup()["configured"])
self.assertEqual(len(self.key_profiles()), 3)
def test_a_setup_with_all_three_keys_as_cloud_keys_is_accepted(self):
payload = {"keys": [
{"key_number": 1, "name": "Provider one", "type": "cloud"},
{"key_number": 2, "name": "Provider two", "type": "cloud"},
{"key_number": 3, "name": "Provider three", "type": "cloud"},
{"key_number": 1, "name": "Provider one", "type": "cloud", "address_path": ADDRESS_PATH},
{"key_number": 2, "name": "Provider two", "type": "cloud", "address_path": ADDRESS_PATH},
{"key_number": 3, "name": "Provider three", "type": "cloud", "address_path": ADDRESS_PATH},
]}
with self.post_setup(payload) as response:
@@ -738,9 +1242,9 @@ class KeySetupApiTests(ServerTestCase):
def test_a_duplicate_name_is_rejected(self):
payload = {"keys": [
{"key_number": 1, "name": "Jade", "type": "hardware"},
{"key_number": 2, "name": "jade", "type": "hardware"},
{"key_number": 3, "name": "Nunchuk", "type": "cloud"},
{"key_number": 1, "name": "Jade", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 2, "name": "jade", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 3, "name": "Nunchuk", "type": "cloud", "address_path": ADDRESS_PATH},
]}
self.assert_setup_rejected(payload)
@@ -748,13 +1252,30 @@ class KeySetupApiTests(ServerTestCase):
def test_an_empty_name_is_rejected(self):
payload = {"keys": [
{"key_number": 1, "name": " ", "type": "hardware"},
{"key_number": 2, "name": "Jade", "type": "hardware"},
{"key_number": 3, "name": "Nunchuk", "type": "cloud"},
{"key_number": 1, "name": " ", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 2, "name": "Jade", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 3, "name": "Nunchuk", "type": "cloud", "address_path": ADDRESS_PATH},
]}
self.assert_setup_rejected(payload)
def test_a_missing_or_empty_address_path_is_rejected(self):
# The setup records the address path of every key (section 25.1).
for value in (None, "", " "):
payload = {"keys": [
{"key_number": 1, "name": "ColdCard", "type": "hardware", "address_path": value},
{"key_number": 2, "name": "Jade", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 3, "name": "Nunchuk", "type": "cloud", "address_path": ADDRESS_PATH},
]}
self.assert_setup_rejected(payload)
payload = {"keys": [
{"key_number": 1, "name": "ColdCard", "type": "hardware"},
{"key_number": 2, "name": "Jade", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 3, "name": "Nunchuk", "type": "cloud", "address_path": ADDRESS_PATH},
]}
self.assert_setup_rejected(payload)
def test_the_wrong_number_of_keys_is_rejected(self):
self.assert_setup_rejected({"keys": DEFAULT_SETUP[:2]})
self.assert_setup_rejected({"keys": DEFAULT_SETUP + [DEFAULT_SETUP[0]]})
@@ -762,15 +1283,16 @@ class KeySetupApiTests(ServerTestCase):
def test_an_unknown_type_is_rejected(self):
payload = {"keys": [
{"key_number": 1, "name": "ColdCard", "type": "usb"},
{"key_number": 2, "name": "Jade", "type": "hardware"},
{"key_number": 3, "name": "Nunchuk", "type": "cloud"},
{"key_number": 1, "name": "ColdCard", "type": "usb", "address_path": ADDRESS_PATH},
{"key_number": 2, "name": "Jade", "type": "hardware", "address_path": ADDRESS_PATH},
{"key_number": 3, "name": "Nunchuk", "type": "cloud", "address_path": ADDRESS_PATH},
]}
self.assert_setup_rejected(payload)
def test_a_health_check_cannot_be_posted_before_the_setup(self):
key = {"id": 1, "key_number": 1, "name": "SeedSigner", "type": "hardware"}
key = {"id": 1, "key_number": 1, "name": "SeedSigner", "type": "hardware",
"address_path": ADDRESS_PATH}
self.assert_rejected(sample_payload(key))
@@ -778,6 +1300,21 @@ class KeySetupApiTests(ServerTestCase):
with urlopen(f"{self.base_url}/api/key-status") as response:
self.assertEqual(json.load(response), [])
def test_the_settings_report_an_empty_setup_and_the_software_list(self):
settings = self.get_settings()
self.assertEqual(settings["keys"], [])
# The list a new database starts with is there before the keys are
# configured (section 25.4).
self.assertEqual(settings["wallet_software"], ["Sparrow Wallet"])
def test_a_key_cannot_be_rotated_before_the_setup(self):
self.assert_rejected_at("/api/keys/1/rotate", {
"replaced": True,
"address_path_unchanged": True,
"keep_name": True,
}, status=404)
if __name__ == "__main__":
unittest.main()