Offer a 24-word master seed, and put the entropy draw beyond reach of any handler

L2: generate_bip85_seed and create_profile_from_generated_seed now take
words_num, accepting 12 or 24 and rejecting anything else with a clear
message. The default stays 12 -- every existing profile uses it, 128 bits is
entirely adequate, and moving the default would change nothing about
existing vaults while surprising anyone creating a new one. 24 is offered
because the master seed protects the whole vault and was the one secret
shorter than the seeds derived beneath it, which already default to 24.

L3: fixed structurally rather than by narrowing exception types.
os.urandom(32) now sits OUTSIDE the try block, so no handler can stand
between the entropy draw and the caller -- an entropy failure is unreachable
by anything that could substitute a value. Also removes a redundant
`except Exception` whose body was identical to the `Bip85Error` branch above
it.

The structural form is stronger than an exception list, and the test says so
precisely: it asserts the OSError reaching the caller is the SAME OBJECT
os.urandom threw, which holds only if nothing caught and repackaged it.
Listing exception types would still leave a handler in the path for someone
to widen later.

Adds five tests: the identity assertion above, 12- and 24-word generation,
the default staying 12, and rejection of 0/11/18/25/-12.

Determinism gate green (89 tests, up from 84). The seed/profile regression
subset is 143 passed with one failure --
test_profile_export_import_round_trip -- confirmed against the pre-change
baseline as pre-existing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HtNMsKzzFTPURemX7tT19u
This commit is contained in:
thePR0M3TH3ANandClaude Opus 5 committed 2026-07-31 17:43:24 -04:00
1 parent 6ac40d2e15
commit 3192c9f306
5 files changed
+138 -17

No files matched your search

+11
View File
@@ -49,6 +49,17 @@ MAX_PASSWORD_LENGTH = 128 # Maximum allowed password length
# Characters considered safe for passwords when limiting punctuation
SAFE_SPECIAL_CHARS = "!@#$%^*-_+=?"
# Master seed word count.
# -----------------------------------
# 12 words = 128 bits, 24 words = 256 bits. The default stays 12: it is
# entirely adequate and every existing profile uses it, so changing the default
# would alter nothing about existing vaults but would surprise. 24 is offered
# because the master seed protects the whole vault and was previously the one
# secret shorter than the seeds derived beneath it, which default to 24
# (entropy audit L2, docs/entropy_audit_2026-07-31.md).
DEFAULT_SEED_WORD_COUNT = 12
SUPPORTED_SEED_WORD_COUNTS = frozenset({12, 24})
# Timeout in seconds before the vault locks due to inactivity
INACTIVITY_TIMEOUT = 15 * 60 # 15 minutes
+32 -11
View File
@@ -89,6 +89,8 @@ from constants import (
DEFAULT_PASSWORD_LENGTH,
INACTIVITY_TIMEOUT,
DEFAULT_SEED_BACKUP_FILENAME,
DEFAULT_SEED_WORD_COUNT,
SUPPORTED_SEED_WORD_COUNTS,
NOTIFICATION_DURATION,
initialize_app,
)
@@ -1802,35 +1804,54 @@ class PasswordManager:
logging.error(f"Error validating BIP-85 seed: {e}")
return False
def generate_bip85_seed(self) -> str:
def generate_bip85_seed(self, words_num: int = DEFAULT_SEED_WORD_COUNT) -> str:
"""
Generates a new BIP-85 seed phrase.
Parameters:
words_num (int): 12 (128-bit, default) or 24 (256-bit). The default
stays 12 so existing callers are unaffected; 24 is offered
because the master seed protects the whole vault and was
previously shorter than the seeds derived beneath it, which
default to 24 (entropy audit L2).
Returns:
str: The generated 12-word mnemonic seed phrase.
str: The generated mnemonic seed phrase.
"""
if words_num not in SUPPORTED_SEED_WORD_COUNTS:
raise SeedPassError(
f"Seed word count must be one of {sorted(SUPPORTED_SEED_WORD_COUNTS)}, "
f"got {words_num!r}."
)
# Deliberately OUTSIDE the try block (entropy audit L3). Nothing below
# may catch an entropy failure and substitute a value -- that is the
# COLDCARD defect class. If os.urandom raises, it propagates unchanged
# and the operation aborts, which is the only acceptable outcome.
master_seed = os.urandom(32)
try:
master_seed = os.urandom(32) # Generate a random 32-byte seed
bip85 = BIP85(master_seed)
mnemonic = bip85.derive_mnemonic(index=0, words_num=12)
return mnemonic
return bip85.derive_mnemonic(index=0, words_num=words_num)
except Bip85Error as e:
logging.error(f"Failed to generate BIP-85 seed: {e}", exc_info=True)
print(colored(f"Error: Failed to generate BIP-85 seed: {e}", "red"))
raise SeedPassError(f"Failed to generate BIP-85 seed: {e}") from e
except Exception as e:
logging.error(f"Failed to generate BIP-85 seed: {e}", exc_info=True)
print(colored(f"Error: Failed to generate BIP-85 seed: {e}", "red"))
raise SeedPassError(f"Failed to generate BIP-85 seed: {e}") from e
def create_profile_from_generated_seed(
self,
*,
password: str,
seed: Optional[str] = None,
words_num: int = DEFAULT_SEED_WORD_COUNT,
) -> tuple[str, str]:
"""Create a new profile from a generated seed and return ``(fingerprint, seed)``."""
new_seed = seed or self.generate_bip85_seed()
"""Create a new profile from a generated seed and return ``(fingerprint, seed)``.
``words_num`` selects the master seed length (12 or 24) and is ignored
when ``seed`` is supplied, since that phrase already fixes its own
length.
"""
new_seed = seed or self.generate_bip85_seed(words_num=words_num)
fingerprint = self._finalize_existing_seed(new_seed, password=password)
if not fingerprint:
raise SeedPassError("Failed to create profile from generated seed.")
+50
View File
@@ -191,6 +191,56 @@ def test_seed_generation_aborts_on_short_read(monkeypatch):
manager_module.PasswordManager.generate_bip85_seed(object())
def test_entropy_draw_sits_outside_the_try_block(monkeypatch):
"""L3: no except clause may stand between os.urandom and the caller.
The generator's exception handling wraps BIP-85 failures in SeedPassError,
which is fine -- but an entropy failure must never be reachable by any
handler that could substitute a value. Keeping the draw outside the try is
the structural version of that guarantee, stronger than narrowing which
exception types get caught.
"""
from seedpass.core import manager as manager_module
sentinel = OSError("entropy pool unavailable")
def _explode(_n):
raise sentinel
monkeypatch.setattr(manager_module.os, "urandom", _explode)
with pytest.raises(OSError) as excinfo:
manager_module.PasswordManager.generate_bip85_seed(object())
# Propagates as itself, not repackaged -- proof nothing caught it.
assert excinfo.value is sentinel
@pytest.mark.parametrize("words_num,expected", [(12, 12), (24, 24)])
def test_master_seed_word_count_is_selectable(words_num, expected):
"""L2: the master seed can now be 256-bit, not only 128-bit."""
from seedpass.core.manager import PasswordManager
mnemonic = PasswordManager.generate_bip85_seed(object(), words_num=words_num)
assert len(mnemonic.split()) == expected
def test_master_seed_default_is_unchanged():
"""Existing profiles are 12-word; the default must not move under them."""
from seedpass.core.manager import PasswordManager
assert len(PasswordManager.generate_bip85_seed(object()).split()) == 12
def test_unsupported_word_count_is_rejected():
from seedpass.core.errors import SeedPassError
from seedpass.core.manager import PasswordManager
for bad in (0, 11, 18, 25, -12):
with pytest.raises(SeedPassError, match="Seed word count"):
PasswordManager.generate_bip85_seed(object(), words_num=bad)
def test_all_zero_entropy_is_not_currently_detected(monkeypatch):
"""Recorded gap, not an endorsement.