diff options
| author | Christophe Besson <cbesson@gmail.com> | 2026-09-01 01:03:43 +0200 |
|---|---|---|
| committer | Christophe Besson <cbesson@gmail.com> | 2026-09-01 01:03:43 +0200 |
| commit | fe30860c58e0f1b1efd457ff5eb5146d1e592da0 (patch) | |
| tree | 99a3e96994738c4e96f969a365679475dc4cf5cd /packages/meshbay-hub/tests/test_password_change.py | |
| parent | 51d2d734c228f1e46670962480258abfe586d6c4 (diff) | |
| download | meshbay-fe30860c58e0f1b1efd457ff5eb5146d1e592da0.tar.gz | |
feat: passphrase change and account recovery (auth-confirm)
The passphrase derives two independent client-side values: auth_key (the
hub verifier) and bundle_key (AES-GCM key for the per-node identity
bundles, which live on nodes and never on the hub). Changing or
recovering a passphrase is therefore two operations — swap the hub
verifier, and re-wrap every reachable node's identity bundle.
Flow A — change a known passphrase (Profile page)
- POST /v1/users/password re-proves the current passphrase, swaps
pw_hash/salt/version, revokes every refresh token and returns a fresh
pair so the tab that made the change stays signed in.
- MeshBayTransport.rewrapAllNodes: for every group's online node, connect
with the old key, read the identity off the handshake, store it back
under the new key. Returns updated / unreachable / failed so the UI can
point at the operator-unpin fallback for the gaps. Always-shown
confirmation dialog listing reachable and unreachable groups.
Recovery key
- keyderive.js generateRecoveryKey (32 random bytes, grouped Base32) and
deriveRecoveryKey (HKDF-SHA256, domain meshbay:recovery:v1:<username>).
- Every per-node identity gets a second copy wrapped under the recovery
key: keypair_bundles.bundle_enc_recovery (node-only column, added in
_SCHEMA_KEYPAIR and via a PRAGMA-guarded ALTER for existing DBs),
carried on keypair_bundle_store / _resp. MNP 0.13 -> 0.14, additive.
- session.recoveryKey is persisted in IndexedDB (slot rk) and lazy-loaded
on connect, so a group joined in any later session still leaves a
recovery copy.
- Shown once at registration; optionally folded into the verification
e-mail as a pass-through the hub never stores or logs, with an opt-out.
- Profile -> Recovery key re-loads R and backfills every reachable node
via rewrapAllNodes in bundleKey mode (no passphrase re-entry).
Flow B — recover a lost passphrase (#/reset, linked from sign-in)
- POST /v1/users/password/reset-request {username, email}: both must be
the pair on file, checked against the blind email_hash (never
decrypted). A mismatch — wrong e-mail, unknown username, non-active
account — takes the identical no-op path (no code, no mail, same 200),
so it reveals nothing and cannot be used to spray reset mail from a
username alone. 5/min, 1-hour single-use code.
- POST /v1/users/password/reset {username, code, new_auth_key}: same
expiry / attempts / single-use checks as e-mail verification; revokes
every session and deletes every registered device key so a stored one
cannot sign back in past the reset.
- ResetPasswordPage: request code -> code + optional recovery key + new
passphrase -> reset + sign-in -> fan-out. connect() falls back to the
recovery-wrapped copy when the passphrase key cannot open bundle_enc.
Without a recovery key: sign-in is restored and each group needs the
operator-unpin fallback.
Supporting fixes (found in live testing)
- member unpin now also deletes the keypair bundle; connect() mints a
fresh identity when handed a bundle it cannot open (unless _rewrapOnly,
set by rewrapAllNodes), so a rejoin completes instead of dead-ending
before the invite-code prompt.
- A browser with no bundle key gets a passphrase prompt on the group page
instead of a "go back to the browser you registered on" message.
- RegisterPage / LoginPage / ResetPasswordPage trim the username so every
key derivation matches the hub's stored form.
Docs: docs/auth-confirm.md. Locale keys across all ten catalogues.
Tests: test_password_change, test_password_reset, test_recovery_email,
test_recovery_key, test_rewrap_fanout, test_bundle_store_recovery, plus
additions to test_admin_ops_mnp and test_webrtc_transport. Hub suite 492
passed; node suite 741 passed (the lone test_packaging_units failure is a
pre-existing RPM-spec flake, reproducible on main).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GGkxJW9br8Y9bhT8ywJ3oc
Diffstat (limited to 'packages/meshbay-hub/tests/test_password_change.py')
| -rw-r--r-- | packages/meshbay-hub/tests/test_password_change.py | 140 |
1 files changed, 140 insertions, 0 deletions
diff --git a/packages/meshbay-hub/tests/test_password_change.py b/packages/meshbay-hub/tests/test_password_change.py new file mode 100644 index 0000000..aba2d9a --- /dev/null +++ b/packages/meshbay-hub/tests/test_password_change.py @@ -0,0 +1,140 @@ +""" +Passphrase change — Flow A of docs/auth-confirm.md. + +The hub's part is small: re-prove the current passphrase, swap the auth_key +verifier, invalidate every other session, keep the caller's. The re-wrapping of +per-node identity bundles is the client's job and does not touch the hub, so it +is not exercised here. +""" + +import base64 +import hashlib + +import pytest +from sqlalchemy import select + +from meshbay_hub.db.models import IPLog, RefreshToken, User + + +def _auth_key(password: str, username: str) -> str: + salt = hashlib.sha256(f"meshbay:auth:v1:{username}".encode()).digest() + return base64.b64encode( + hashlib.pbkdf2_hmac("sha512", password.encode(), salt, 600_000, 32)).decode() + + +async def _register(client, username, password="the-first-passphrase"): + r = await client.post("/v1/users/register", json={ + "username": username, "email": f"{username}@example.com", + "auth_key": _auth_key(password, username), + }) + assert r.status_code in (200, 201), r.text + login = await client.post("/v1/users/login", json={ + "username": username, "auth_key": _auth_key(password, username)}) + assert login.status_code == 200, login.text + return login.json() + + +@pytest.mark.asyncio +async def test_change_then_sign_in_with_the_new_passphrase(client): + old, new = "the-first-passphrase", "a-second-passphrase-entirely" + session = await _register(client, "alice", old) + + r = await client.post("/v1/users/password", json={ + "old_auth_key": _auth_key(old, "alice"), + "new_auth_key": _auth_key(new, "alice"), + }, headers={"Authorization": f"Bearer {session['access_token']}"}) + assert r.status_code == 200, r.text + assert r.json()["status"] == "changed" + + assert (await client.post("/v1/users/login", json={ + "username": "alice", "auth_key": _auth_key(old, "alice")})).status_code == 401 + assert (await client.post("/v1/users/login", json={ + "username": "alice", "auth_key": _auth_key(new, "alice")})).status_code == 200 + + +@pytest.mark.asyncio +async def test_wrong_current_passphrase_is_refused_and_changes_nothing(client): + old = "the-first-passphrase" + session = await _register(client, "bob", old) + + r = await client.post("/v1/users/password", json={ + "old_auth_key": _auth_key("not the passphrase", "bob"), + "new_auth_key": _auth_key("some-new-passphrase", "bob"), + }, headers={"Authorization": f"Bearer {session['access_token']}"}) + assert r.status_code == 403 + + assert (await client.post("/v1/users/login", json={ + "username": "bob", "auth_key": _auth_key(old, "bob")})).status_code == 200 + + +@pytest.mark.asyncio +async def test_new_must_differ_from_old(client): + old = "the-first-passphrase" + session = await _register(client, "carol", old) + + r = await client.post("/v1/users/password", json={ + "old_auth_key": _auth_key(old, "carol"), + "new_auth_key": _auth_key(old, "carol"), + }, headers={"Authorization": f"Bearer {session['access_token']}"}) + assert r.status_code == 400 + + +@pytest.mark.asyncio +async def test_unauthenticated_call_is_rejected(client): + """A session is required — the current passphrase alone is not a credential.""" + await _register(client, "dave", "the-first-passphrase") + r = await client.post("/v1/users/password", json={ + "old_auth_key": _auth_key("the-first-passphrase", "dave"), + "new_auth_key": _auth_key("a-new-one", "dave"), + }) + assert r.status_code in (401, 403, 422) + + +@pytest.mark.asyncio +async def test_other_sessions_are_invalidated_and_the_caller_keeps_one( + client, db_session): + old, new = "the-first-passphrase", "a-second-passphrase-entirely" + first = await _register(client, "erin", old) + # A second browser signs in before the change. + second = (await client.post("/v1/users/login", json={ + "username": "erin", "auth_key": _auth_key(old, "erin")})).json() + + r = await client.post("/v1/users/password", json={ + "old_auth_key": _auth_key(old, "erin"), + "new_auth_key": _auth_key(new, "erin"), + }, headers={"Authorization": f"Bearer {first['access_token']}"}) + assert r.status_code == 200, r.text + + # The other browser's refresh token is dead. + stale = await client.post("/v1/users/token/refresh", json={ + "refresh_token": second["refresh_token"]}) + assert stale.status_code == 401 + + # The caller was handed a fresh pair that still works. + fresh = await client.post("/v1/users/token/refresh", json={ + "refresh_token": r.json()["refresh_token"]}) + assert fresh.status_code == 200, fresh.text + + uid = (await db_session.execute( + select(User.id).where(User.username == "erin"))).scalar_one() + live = (await db_session.execute( + select(RefreshToken).where(RefreshToken.user_id == uid, + RefreshToken.revoked.is_(False)))).scalars().all() + # Only the family issued to the caller (the refresh above rotated it once). + assert len(live) == 1 + + +@pytest.mark.asyncio +async def test_the_change_is_logged(client, db_session): + old, new = "the-first-passphrase", "a-second-passphrase-entirely" + session = await _register(client, "frank", old) + await client.post("/v1/users/password", json={ + "old_auth_key": _auth_key(old, "frank"), + "new_auth_key": _auth_key(new, "frank"), + }, headers={"Authorization": f"Bearer {session['access_token']}"}) + + uid = (await db_session.execute( + select(User.id).where(User.username == "frank"))).scalar_one() + events = {e.event for e in (await db_session.execute( + select(IPLog).where(IPLog.user_id == uid))).scalars().all()} + assert "password_change" in events |