gabriel / muse public
test_derived_key_zeroing.py python
174 lines 6.8 KB
Raw
sha256:88ac91129873e6a496e9189515aa690eb893ae25d69c8f72af141a2be5068eb3 docs: docstring sprint contract→find-symbol — idiomatic run… Sonnet 4.6 patch 141 days ago
1 """Tests for DerivedKey memory zeroing after use.
2
3 DerivedKey.private_bytes and DerivedKey.chain_code used to be immutable
4 ``bytes`` — they could not be zeroed, so raw key material lingered in the
5 Python heap indefinitely after derivation.
6
7 Fix:
8 - Fields changed to ``bytearray`` so contents can be overwritten.
9 - ``DerivedKey.zero()`` sets both fields to all-zero bytes.
10 - ``derive_path`` zeroes each intermediate DerivedKey after deriving the
11 next child.
12 - ``generate_hd_keypair`` zeroes the final DerivedKey after the Ed25519
13 PrivateKey object has been created.
14
15 Coverage
16 --------
17 I DerivedKey fields are bytearray
18 I1 private_bytes is bytearray, not bytes
19 I2 chain_code is bytearray, not bytes
20
21 II DerivedKey.zero() wipes both fields
22 II1 after zero(), private_bytes is all-zero
23 II2 after zero(), chain_code is all-zero
24 II3 zero() does not affect the length (still 32 bytes)
25
26 III generate_hd_keypair zeroes the final DerivedKey
27 III1 private_bytes is all-zero in the DerivedKey after generate_hd_keypair returns
28 III2 chain_code is all-zero in the DerivedKey after generate_hd_keypair returns
29
30 IV Derivation still correct after zeroing changes
31 IV1 same seed → same fingerprint (deterministic derivation unchanged)
32 """
33
34 from __future__ import annotations
35
36 import pathlib
37 from unittest.mock import patch
38
39 import pytest
40
41 from muse.core import keypair as kp_module
42 from muse.core import identity as id_module
43 from muse.core import hdkeys as _hdkeys
44 from muse.core.slip010 import master_key, DerivedKey
45 from muse.core.bip39 import mnemonic_to_seed
46
47 _MNEMONIC = (
48 "abandon abandon abandon abandon abandon abandon abandon abandon "
49 "abandon abandon abandon about"
50 )
51 _SEED = mnemonic_to_seed(_MNEMONIC)
52
53
54 @pytest.fixture()
55 def isolated(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path) -> pathlib.Path:
56 fake_home = tmp_path / "home"
57 fake_home.mkdir(parents=True, exist_ok=True)
58 monkeypatch.setattr(pathlib.Path, "home", staticmethod(lambda: fake_home))
59 monkeypatch.setattr(kp_module, "_KEYS_DIR", fake_home / ".muse" / "keys")
60 monkeypatch.setattr(id_module, "_IDENTITY_DIR", fake_home / ".muse")
61 monkeypatch.setattr(id_module, "_IDENTITY_FILE", fake_home / ".muse" / "identity.toml")
62 return fake_home
63
64
65 # ---------------------------------------------------------------------------
66 # I DerivedKey fields are bytearray
67 # ---------------------------------------------------------------------------
68
69 class TestDerivedKeyFieldTypes:
70 def test_I1_private_bytes_is_bytearray(self) -> None:
71 """I1: DerivedKey.private_bytes must be bytearray, not bytes."""
72 dk = master_key(_SEED)
73 assert isinstance(dk.private_bytes, bytearray), (
74 f"private_bytes must be bytearray, got {type(dk.private_bytes).__name__}"
75 )
76
77 def test_I2_chain_code_is_bytearray(self) -> None:
78 """I2: DerivedKey.chain_code must be bytearray, not bytes."""
79 dk = master_key(_SEED)
80 assert isinstance(dk.chain_code, bytearray), (
81 f"chain_code must be bytearray, got {type(dk.chain_code).__name__}"
82 )
83
84
85 # ---------------------------------------------------------------------------
86 # II DerivedKey.zero() wipes both fields
87 # ---------------------------------------------------------------------------
88
89 class TestDerivedKeyZero:
90 def test_II1_zero_wipes_private_bytes(self) -> None:
91 """II1: after zero(), private_bytes contains only null bytes."""
92 dk = master_key(_SEED)
93 assert any(b != 0 for b in dk.private_bytes), "pre-condition: key must not already be zero"
94 dk.zero()
95 assert dk.private_bytes == bytearray(32), "private_bytes must be all-zero after zero()"
96
97 def test_II2_zero_wipes_chain_code(self) -> None:
98 """II2: after zero(), chain_code contains only null bytes."""
99 dk = master_key(_SEED)
100 assert any(b != 0 for b in dk.chain_code), "pre-condition: chain_code must not already be zero"
101 dk.zero()
102 assert dk.chain_code == bytearray(32), "chain_code must be all-zero after zero()"
103
104 def test_II3_zero_preserves_length(self) -> None:
105 """II3: zero() does not change the field lengths."""
106 dk = master_key(_SEED)
107 dk.zero()
108 assert len(dk.private_bytes) == 32
109 assert len(dk.chain_code) == 32
110
111
112 # ---------------------------------------------------------------------------
113 # III generate_hd_keypair zeroes the final DerivedKey
114 # ---------------------------------------------------------------------------
115
116 class TestGenerateHdKeypairZeroing:
117 def test_III1_private_bytes_zeroed_after_keygen(
118 self, isolated: pathlib.Path
119 ) -> None:
120 """III1: the DerivedKey's private_bytes are all-zero after generate_hd_keypair."""
121 captured: list[DerivedKey] = []
122 original_derive = _hdkeys.derive_identity_key
123
124 def capturing_derive(*args, **kwargs):
125 dk = original_derive(*args, **kwargs)
126 captured.append(dk)
127 return dk
128
129 with patch.object(_hdkeys, "derive_identity_key", side_effect=capturing_derive):
130 kp_module.generate_hd_keypair("localhost:10003", _SEED)
131
132 assert captured, "derive_identity_key was not called"
133 dk = captured[0]
134 assert dk.private_bytes == bytearray(32), (
135 "private_bytes must be zeroed after generate_hd_keypair"
136 )
137
138 def test_III2_chain_code_zeroed_after_keygen(
139 self, isolated: pathlib.Path
140 ) -> None:
141 """III2: the DerivedKey's chain_code is all-zero after generate_hd_keypair."""
142 captured: list[DerivedKey] = []
143 original_derive = _hdkeys.derive_identity_key
144
145 def capturing_derive(*args, **kwargs):
146 dk = original_derive(*args, **kwargs)
147 captured.append(dk)
148 return dk
149
150 with patch.object(_hdkeys, "derive_identity_key", side_effect=capturing_derive):
151 kp_module.generate_hd_keypair("localhost:10003", _SEED)
152
153 dk = captured[0]
154 assert dk.chain_code == bytearray(32), (
155 "chain_code must be zeroed after generate_hd_keypair"
156 )
157
158
159 # ---------------------------------------------------------------------------
160 # IV Derivation still correct
161 # ---------------------------------------------------------------------------
162
163 class TestDerivedKeyZeroingCorrectness:
164 def test_IV1_same_seed_same_fingerprint(self, isolated: pathlib.Path) -> None:
165 """IV1: zeroing does not affect determinism — same seed → same fingerprint."""
166 _, fp1 = kp_module.generate_hd_keypair("localhost:10003", _SEED)
167
168 import os
169 pem_path = isolated / ".muse" / "keys" / "localhost_10003.pem"
170 pem_path.unlink()
171
172 _, fp2 = kp_module.generate_hd_keypair("localhost:10003", _SEED)
173
174 assert fp1 == fp2, "Zeroing must not break deterministic derivation"
File History 1 commit
sha256:88ac91129873e6a496e9189515aa690eb893ae25d69c8f72af141a2be5068eb3 docs: docstring sprint contract→find-symbol — idiomatic run… Sonnet 4.6 patch 141 days ago