aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/tests
diff options
context:
space:
mode:
Diffstat (limited to 'packages/meshbay-hub/tests')
-rw-r--r--packages/meshbay-hub/tests/test_bundle_key.py48
-rw-r--r--packages/meshbay-hub/tests/test_csv_cell.py32
-rw-r--r--packages/meshbay-hub/tests/test_desktop_keyring.py34
-rw-r--r--packages/meshbay-hub/tests/test_desktop_shell.py23
-rw-r--r--packages/meshbay-hub/tests/test_group_name_checked.py33
-rw-r--r--packages/meshbay-hub/tests/test_hub_work_is_bounded.py51
-rw-r--r--packages/meshbay-hub/tests/test_known_browser.py98
-rw-r--r--packages/meshbay-hub/tests/test_login_lockout.py20
-rw-r--r--packages/meshbay-hub/tests/test_username_case.py24
9 files changed, 357 insertions, 6 deletions
diff --git a/packages/meshbay-hub/tests/test_bundle_key.py b/packages/meshbay-hub/tests/test_bundle_key.py
index 333f8f8..f6c99f8 100644
--- a/packages/meshbay-hub/tests/test_bundle_key.py
+++ b/packages/meshbay-hub/tests/test_bundle_key.py
@@ -156,7 +156,7 @@ def test_an_earlier_format_is_refused_by_name(tmp_path):
}
console.log(JSON.stringify(results));
""")
- assert out == [["retired", "bundle_format_retired"], ["retired", "bundle_format_retired"]]
+ assert out == [["legacy", "bundle_format_retired"], ["retired", "bundle_format_retired"]]
def test_two_devices_of_one_account_derive_the_same_playlist_key(tmp_path):
@@ -181,3 +181,49 @@ def test_the_playlist_key_is_no_node_key(tmp_path):
}));
""")
assert out["distinct"]
+
+
+def test_an_mbk2_bundle_is_opened_once_and_sealed_again_as_mbk3(tmp_path):
+ """
+ TRANSITIONAL. Nodes still hold bundles sealed under the passphrase's Argon2
+ key alone. The same Argon2 run that makes `M` makes that key, so the session
+ keeps it — decrypt only — and the identity is moved to MBK3 on the account's
+ next visit instead of the member being re-invited.
+ """
+ out = _run(tmp_path, """
+ argonCalls = 0;
+ const sk = await K().deriveBundleSessionKey('p', 'someone', 'uid-1', PEPPER, 1);
+ const calls = argonCalls;
+ // An MBK2 bundle as 0.16 wrote it: "MBK2" ‖ nonce ‖ AES-GCM(A), no AAD.
+ const a = await crypto.subtle.importKey('raw', await _bundleKeyBytes('p', 'someone'),
+ { name: 'AES-GCM' }, false, ['encrypt']);
+ const nonce = new Uint8Array(12).fill(3);
+ const plain = new TextEncoder().encode(JSON.stringify({ skEd: btoa('ED'), skX: btoa('XX') }));
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, a, plain));
+ const raw = new Uint8Array(4 + 12 + ct.length);
+ raw.set(new TextEncoder().encode('MBK2')); raw.set(nonce, 4); raw.set(ct, 16);
+ const mbk2 = btoa(String.fromCharCode(...raw));
+
+ const keys = await K().decryptLegacyBundle(mbk2, sk.legacy);
+ const resealed = await K().resealLegacyIdentity(keys, sk, null, { userId: 'uid-1', nodePk: 'NODE' });
+ const back = await K().decryptBundle(resealed.bundleEnc, await K().nodeBundleKey(sk, 'NODE'),
+ { userId: 'uid-1', nodePk: 'NODE' });
+ let otherPassphrase = 'opened';
+ const sk2 = await K().deriveBundleSessionKey('another', 'someone', 'uid-1', PEPPER, 1);
+ try { await K().decryptLegacyBundle(mbk2, sk2.legacy); } catch { otherPassphrase = 'refused'; }
+ let sealsUnderLegacy = 'yes';
+ try { await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, sk.legacy, plain); }
+ catch { sealsUnderLegacy = 'no'; }
+ console.log(JSON.stringify({
+ calls, format: K().bundleFormat(mbk2), keys, newFormat: K().bundleFormat(resealed.bundleEnc),
+ back, otherPassphrase, sealsUnderLegacy, extractable: sk.legacy.extractable,
+ }));
+ """)
+ assert out["calls"] == 1, "keeping the legacy key must not cost a second Argon2 run"
+ assert out["format"] == "legacy"
+ assert out["keys"] == {"skEd": "RUQ=", "skX": "WFg="}
+ assert out["newFormat"] == "current"
+ assert out["back"] == out["keys"]
+ assert out["otherPassphrase"] == "refused"
+ assert out["sealsUnderLegacy"] == "no", "the legacy key opens; it never seals"
+ assert out["extractable"] is False
diff --git a/packages/meshbay-hub/tests/test_csv_cell.py b/packages/meshbay-hub/tests/test_csv_cell.py
new file mode 100644
index 0000000..ca38805
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_csv_cell.py
@@ -0,0 +1,32 @@
+"""
+The audit export never hands a spreadsheet a formula.
+
+It carries text a member chose — a refused blob's kind, a file name. A cell that
+starts with `=`, `+`, `-` or `@` runs as a formula when the operator opens the
+file, so it is given a leading apostrophe, which spreadsheets read as text.
+"""
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+CSV = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static" / "csv.js"
+
+pytestmark = pytest.mark.skipif(shutil.which("node") is None, reason="node unavailable")
+
+CASES = ['=HYPERLINK("http://x","y")', "+1+1", "-2+3", "@SUM(A1)", "\t=1", "plain",
+ 'with "quotes"', "a,b", "", None, 12]
+
+
+def test_a_cell_is_text_and_quoted_where_it_must_be(tmp_path):
+ script = tmp_path / "case.mjs"
+ script.write_text(
+ f"import {{ csvCell }} from '{CSV.as_uri()}';\n"
+ f"console.log(JSON.stringify({json.dumps(CASES)}.map(csvCell)));\n")
+ out = json.loads(subprocess.run(["node", str(script)], capture_output=True,
+ text=True, check=True).stdout)
+ assert out == ['"\'=HYPERLINK(""http://x"",""y"")"', "'+1+1", "'-2+3", "'@SUM(A1)",
+ "'\t=1", "plain", '"with ""quotes"""', '"a,b"', "", "", "12"]
diff --git a/packages/meshbay-hub/tests/test_desktop_keyring.py b/packages/meshbay-hub/tests/test_desktop_keyring.py
index 963ee55..e55e6d0 100644
--- a/packages/meshbay-hub/tests/test_desktop_keyring.py
+++ b/packages/meshbay-hub/tests/test_desktop_keyring.py
@@ -119,10 +119,33 @@ const v = JSON.parse(fs.readFileSync(input, 'utf8'));
await K.nodeBundleKey(sk, 'NODE-P'), { userId: v.userId, nodePk: 'NODE-P' });
out.sealed_here_opens_in_page = back.skX === pageId.skXB64;
+ // 3b. TRANSITIONAL: an MBK2 bundle, sealed under the Argon2 key alone as
+ // 0.16 wrote it, is opened with the legacy key kept beside M.
+ {
+ const nc = require('crypto');
+ const salt = nc.createHash('sha256').update(`meshbay:bundle:v2:${v.user}`).digest().subarray(0, 16);
+ const a = await argon2(v.password, salt,
+ { memory: 131072, passes: 3, parallelism: 1, tagLength: 32 });
+ const ed = nc.generateKeyPairSync('ed25519').privateKey.export({ format: 'der', type: 'pkcs8' });
+ const x = nc.generateKeyPairSync('x25519').privateKey.export({ format: 'der', type: 'pkcs8' });
+ const nonce = nc.randomBytes(12);
+ const c = nc.createCipheriv('aes-256-gcm', Buffer.from(a), nonce);
+ const body = Buffer.concat([c.update(JSON.stringify({ skEd: ed.toString('base64'),
+ skX: x.toString('base64') })), c.final()]);
+ const mbk2 = Buffer.concat([Buffer.from('MBK2'), nonce, body, c.getAuthTag()]).toString('base64');
+ out.legacy_open = ring.openBundle(v.userId, 'NODE-L', { bundleEnc: mbk2 });
+ out.legacy_kept = ring.identity(v.userId, 'NODE-L');
+ const keptLegacy = store.masters[v.userId].legacy;
+ delete store.masters[v.userId].legacy;
+ try { ring.openBundle(v.userId, 'NODE-M', { bundleEnc: mbk2 }); out.legacy_missing = 'opened'; }
+ catch (e) { out.legacy_missing = e.message; }
+ store.masters[v.userId].legacy = keptLegacy;
+ }
+
// 4. nothing but public keys come out of the keyring's answers.
out.identity_answer = ring.identity(v.userId, v.node);
out.retired = (() => { try { ring.openBundle(v.userId, 'NODE-R',
- { bundleEnc: Buffer.from('MBK2' + 'x'.repeat(40)).toString('base64') }); }
+ { bundleEnc: Buffer.from('y'.repeat(44)).toString('base64') }); }
catch (e) { return e.code; } })();
out.access_default = ring.browserAccess('someone-else');
ring.setBrowserAccess(v.userId, false);
@@ -284,3 +307,12 @@ def test_the_application_never_asks_its_own_crypto_for_argon2():
source = (KEYRING.parent / name).read_text(encoding="utf-8")
assert "crypto.argon2" not in source, name
assert "wasmArgon2(" in (KEYRING.parent / "main.js").read_text(encoding="utf-8")
+
+
+def test_an_mbk2_bundle_is_opened_with_the_kept_legacy_key(out):
+ """TRANSITIONAL. Kept unsealed, so the next settle replaces the node's copy
+ with MBK3 or withdraws it; without the legacy key the passphrase is asked
+ for, rather than the identity being given up."""
+ assert set(out["legacy_open"]) == {"pkEdB64", "pkXB64"}
+ assert out["legacy_kept"]["sealedWith"] is None
+ assert out["legacy_missing"] == "no_legacy_key"
diff --git a/packages/meshbay-hub/tests/test_desktop_shell.py b/packages/meshbay-hub/tests/test_desktop_shell.py
index 4426dd7..60aa32f 100644
--- a/packages/meshbay-hub/tests/test_desktop_shell.py
+++ b/packages/meshbay-hub/tests/test_desktop_shell.py
@@ -701,3 +701,26 @@ def test_an_account_made_in_the_application_starts_without_browser_access():
assert "platform.keys.createdHere(reg.userId)" in register
assert "userId" in (STATIC / "keyderive.js").read_text(encoding="utf-8").split(
"async function registerUser", 1)[1].split("\n}\n", 1)[0]
+
+
+def _handler(name: str) -> str:
+ source = _main()
+ start = source.index(f"handle('{name}'")
+ return source[start:source.index("\n });", start)]
+
+
+def test_a_finished_download_carries_the_mark_of_the_web():
+ """What a browser leaves on every download, so Windows applies SmartScreen
+ and Protected View. Only checkable here by reading: the stream exists on
+ NTFS alone, and this suite does not run on Windows."""
+ assert "markFromInternet(sink.path)" in _handler("save:end")
+ source = _main()
+ mark = source[source.index("function markFromInternet"):]
+ mark = mark[:mark.index("\n }\n")]
+ assert "Zone.Identifier" in mark and "ZoneId=3" in mark
+ assert "process.platform !== 'win32'" in mark
+
+
+def test_a_saved_name_cannot_hide_its_extension():
+ begin = _handler("save:begin")
+ assert "\\u202a-\\u202e" in begin and "\\u2066-\\u2069" in begin
diff --git a/packages/meshbay-hub/tests/test_group_name_checked.py b/packages/meshbay-hub/tests/test_group_name_checked.py
new file mode 100644
index 0000000..fbc8277
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_group_name_checked.py
@@ -0,0 +1,33 @@
+"""
+A group name is checked where it is created.
+
+The column is 128 characters wide: a longer name was a database error on
+PostgreSQL and a silent truncation on SQLite. And the name is shown to other
+people — in their group list, in the invitation mail — so it carries no line
+breaks or other control characters, and no bidirectional override that makes it
+display as something other than what it is.
+"""
+
+import pytest
+from test_bundle_pepper import _login, _register
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("name,ok", [
+ ("Photos de famille", True),
+ ("x" * 128, True),
+ ("👨‍👩‍👧 Family", True), # a ZWJ sequence is a name, not a trick
+ ("x" * 129, False),
+ ("Films\nClick here", False),
+ ("tab\there", False),
+ ("evil‮gpj.exe", False),
+ (" ", False),
+])
+async def test_a_group_name(client, name, ok):
+ await _register(client, "group_namer")
+ token = (await _login(client, "group_namer"))["access_token"]
+ r = await client.post("/v1/groups", json={"name": name},
+ headers={"Authorization": f"Bearer {token}"})
+ assert (r.status_code < 300) is ok, (name, r.status_code, r.text)
+ if not ok:
+ assert r.status_code == 422
diff --git a/packages/meshbay-hub/tests/test_hub_work_is_bounded.py b/packages/meshbay-hub/tests/test_hub_work_is_bounded.py
new file mode 100644
index 0000000..40ea81d
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_hub_work_is_bounded.py
@@ -0,0 +1,51 @@
+"""
+What an authenticated caller can make the hub do, bounded where it was not.
+
+An offer wrote an IP-log row — kept a year — before any check, for whatever
+string the caller named as a node, and carried an ICE list of any length to the
+node. A node could send `update_groups` as fast as it liked, each one a
+database read, with a list of any length.
+"""
+
+import pytest
+from meshbay_hub.db.models import IPLog
+from sqlalchemy import func, select
+from test_availability_between_members import _make_user
+
+
+def _offer(client, user, node_id, candidates):
+ return client.post(f"/v1/nodes/{node_id}/webrtc/offer",
+ json={"sdp": "v=0\r\n", "ice_candidates": candidates},
+ headers={"Authorization": f"Bearer {user['token']}"})
+
+
+@pytest.mark.asyncio
+async def test_an_offer_that_goes_nowhere_writes_no_log_row(client, db_session):
+ user = await _make_user(client, "offer_nowhere")
+ for i in range(5):
+ r = await _offer(client, user, f"not-a-node-{i}", [])
+ assert r.status_code == 404
+ rows = await db_session.scalar(
+ select(func.count()).select_from(IPLog).where(IPLog.event == "webrtc_offer"))
+ assert rows == 0
+
+
+@pytest.mark.asyncio
+async def test_the_ice_list_is_bounded(client):
+ from meshbay_hub.api.signaling import MAX_ICE_CANDIDATES
+ user = await _make_user(client, "offer_ice")
+ one = {"candidate": "candidate:1 1 udp 2122260223 192.0.2.1 50000 typ host",
+ "sdpMid": "0", "sdpMLineIndex": 0}
+ assert (await _offer(client, user, "nowhere", [one] * MAX_ICE_CANDIDATES)).status_code == 404
+ too_many = [one] * (MAX_ICE_CANDIDATES + 1)
+ assert (await _offer(client, user, "nowhere", too_many)).status_code == 422
+ big = {"candidate": "x" * 40_000}
+ assert (await _offer(client, user, "nowhere", [big])).status_code == 422
+
+
+def test_a_node_reloading_is_budgeted():
+ from meshbay_hub.api.revocation import UPDATE_GROUPS_BURST, _update_budget, _update_window
+ _update_window.clear()
+ assert all(_update_budget("node-a") for _ in range(UPDATE_GROUPS_BURST))
+ assert not _update_budget("node-a")
+ assert _update_budget("node-b"), "one node's budget is not another's"
diff --git a/packages/meshbay-hub/tests/test_known_browser.py b/packages/meshbay-hub/tests/test_known_browser.py
new file mode 100644
index 0000000..260f08e
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_known_browser.py
@@ -0,0 +1,98 @@
+"""
+A stranger who knows your name locks only the browsers you never used.
+
+The sign-in lockout counts wrong passphrases per username: four an hour from
+anyone kept the owner out of every browser for as long as they cared to keep
+going. A browser that signed in to the account before presents a token and has
+a counter of its own, which nobody else can spend. The token is not a
+credential — the passphrase is still asked — and a passphrase re-checked inside
+an open session is not the sign-in counter's business at all.
+"""
+
+import pytest
+from meshbay_hub.db.models import KnownBrowser, User
+from sqlalchemy import func, select
+from test_bundle_pepper import KEY, _register
+
+WRONG = "w" * 44
+
+
+async def _sign_in(client, username, key=KEY, known=None):
+ body = {"username": username, "auth_key": key}
+ if known:
+ body["known_browser"] = known
+ return await client.post("/v1/users/login", json=body)
+
+
+async def _lock(client, username):
+ for _ in range(4):
+ await _sign_in(client, username, WRONG)
+ assert (await _sign_in(client, username)).status_code == 429
+
+
+@pytest.mark.asyncio
+async def test_a_known_browser_signs_in_through_a_strangers_lockout(client):
+ await _register(client, "known_owner")
+ token = (await _sign_in(client, "known_owner")).json()["known_browser"]
+
+ await _lock(client, "known_owner") # the stranger, without a token
+ r = await _sign_in(client, "known_owner", known=token)
+ assert r.status_code == 200, r.text
+ assert "known_browser" not in r.json(), "a known browser is not given a second token"
+
+
+@pytest.mark.asyncio
+async def test_another_accounts_token_is_no_way_round(client):
+ await _register(client, "known_alice")
+ await _register(client, "known_bobby")
+ alices = (await _sign_in(client, "known_alice")).json()["known_browser"]
+
+ await _lock(client, "known_bobby")
+ assert (await _sign_in(client, "known_bobby", known=alices)).status_code == 429
+
+
+@pytest.mark.asyncio
+async def test_a_known_browser_is_locked_by_its_own_failures(client):
+ """Whoever holds the token still guesses at the same rate."""
+ await _register(client, "known_guess")
+ token = (await _sign_in(client, "known_guess")).json()["known_browser"]
+ for _ in range(4):
+ assert (await _sign_in(client, "known_guess", WRONG, token)).status_code == 401
+ assert (await _sign_in(client, "known_guess", known=token)).status_code == 429
+ # ...and that spent nothing of a browser that has no token.
+ assert (await _sign_in(client, "known_guess")).status_code == 200
+
+
+@pytest.mark.asyncio
+async def test_a_locked_name_does_not_stop_its_owner_inside_a_session(client):
+ await _register(client, "known_inside")
+ session = (await _sign_in(client, "known_inside")).json()["access_token"]
+ await _lock(client, "known_inside")
+
+ r = await client.post("/v1/users/me/bundle-pepper", json={"auth_key": KEY},
+ headers={"Authorization": f"Bearer {session}"})
+ assert r.status_code == 200, r.text
+
+
+@pytest.mark.asyncio
+async def test_only_a_hash_is_kept_and_only_twenty(client, db_session):
+ await _register(client, "known_many")
+ tokens = [(await _sign_in(client, "known_many")).json()["known_browser"]
+ for _ in range(25)]
+ uid = (await db_session.execute(
+ select(User.id).where(User.username == "known_many"))).scalar_one()
+ rows = (await db_session.execute(
+ select(KnownBrowser).where(KnownBrowser.user_id == uid))).scalars().all()
+ assert len(rows) == 20
+ assert not any(t in {r.token_hash for r in rows} for t in tokens)
+
+
+@pytest.mark.asyncio
+async def test_erasing_the_account_forgets_its_browsers(client, db_session):
+ await _register(client, "known_gone")
+ login = (await _sign_in(client, "known_gone")).json()
+ r = await client.request("DELETE", "/v1/users/me", json={"auth_key": KEY},
+ headers={"Authorization": f"Bearer {login['access_token']}"})
+ assert r.status_code == 200, r.text
+ left = await db_session.scalar(select(func.count()).select_from(KnownBrowser))
+ assert left == 0
diff --git a/packages/meshbay-hub/tests/test_login_lockout.py b/packages/meshbay-hub/tests/test_login_lockout.py
index 601edbd..8f06d2d 100644
--- a/packages/meshbay-hub/tests/test_login_lockout.py
+++ b/packages/meshbay-hub/tests/test_login_lockout.py
@@ -131,8 +131,13 @@ async def test_a_burst_of_concurrent_guesses_gets_no_more_than_the_limit(client)
@pytest.mark.asyncio
-async def test_change_password_counts_on_the_same_row(client):
- """It checks the same passphrase, so it is the same oracle."""
+async def test_change_password_counts_on_the_sessions_own_row(client):
+ """
+ It checks the passphrase, so it is counted and locked like a sign-in — on a
+ row of the session's own. A stranger failing at sign-in must not stop the
+ owner changing their passphrase from a session they hold, and failures here
+ must not lock the owner's other browsers out of signing in.
+ """
await _register(client, "grace_test")
token = (await _login(client, "grace_test", RIGHT)).json()["access_token"]
auth = {"Authorization": f"Bearer {token}"}
@@ -145,7 +150,7 @@ async def test_change_password_counts_on_the_same_row(client):
r = await client.post("/v1/users/password", headers=auth, json={
"old_auth_key": RIGHT, "new_auth_key": "n" * 44})
assert r.status_code == 429, r.text
- assert (await _login(client, "grace_test", RIGHT)).status_code == 429
+ assert (await _login(client, "grace_test", RIGHT)).status_code == 200
@pytest.mark.asyncio
@@ -157,10 +162,17 @@ async def test_a_signed_in_session_is_told_its_own_lockout(client):
auth = {"Authorization": f"Bearer {token}"}
assert (await client.get("/v1/users/me", headers=auth)).json()["passphrase_locked_for"] == 0
- await _fail(client, "olivia_test", 4)
+ for _ in range(4):
+ await client.post("/v1/users/password", headers=auth, json={
+ "old_auth_key": WRONG, "new_auth_key": "n" * 44})
left = (await client.get("/v1/users/me", headers=auth)).json()["passphrase_locked_for"]
assert 3500 <= left <= 3600
+ # A stranger failing at sign-in is not this session's lockout.
+ await _fail(client, "olivia_test", 4)
+ other = (await _login(client, "olivia_test", RIGHT))
+ assert other.status_code == 429
+
@pytest.mark.asyncio
async def test_an_attempt_that_checks_no_passphrase_is_not_counted(client, db_session):
diff --git a/packages/meshbay-hub/tests/test_username_case.py b/packages/meshbay-hub/tests/test_username_case.py
new file mode 100644
index 0000000..42f4815
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_username_case.py
@@ -0,0 +1,24 @@
+"""
+A username is unique whatever its case.
+
+Invitations and member management name people by username, so "Alice" beside
+"alice" is one person to whoever reads the list — and a second account under
+the other spelling is the way to be mistaken for them.
+"""
+
+import pytest
+from test_bundle_pepper import KEY
+
+
+async def _register(client, username, email):
+ return await client.post("/v1/users/register", json={
+ "username": username, "auth_key": KEY, "email": email})
+
+
+@pytest.mark.asyncio
+async def test_a_name_differing_only_by_case_is_taken(client):
+ assert (await _register(client, "alice_case", "a1@example.invalid")).status_code == 201
+ for other in ("Alice_case", "ALICE_CASE", "alice_CASE"):
+ r = await _register(client, other, "a2@example.invalid")
+ assert r.status_code == 409, (other, r.text)
+