summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/tests/test_spa_ordering.py
blob: 1329b748828650e5a19a09cea063b770762cc9da (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""
Ordering guards for the SPA's connect() flow.

These are source-level checks, which is not how one would normally test
behaviour. They exist because a specific class of bug shipped to a live browser
twice and no other test could see it: `connect()` is a long sequence in which
later steps read values earlier steps set, and the Python end-to-end client in
QE/deploy/ cannot catch a mistake there — it is a different implementation,
written in the right order by construction, so it passes while the browser fails.

Concretely: join_request signs a transcript over the node key and the node nonce,
and runs *before* the GEK proof, because a first-time member has no GEK to prove.
Both values were being read further down, next to the proof that also uses them,
so every invited member hit "Handshake incomplete — reconnect and retry".

If you restructure connect(), these will fail. Check the invariant still holds —
that nothing reads a value assigned later — and then move the markers.
"""

from pathlib import Path

import pytest

STATIC = (Path(__file__).resolve().parents[1]
          / "src" / "meshbay_hub" / "static")
TRANSPORT = STATIC / "transport.js"

pytestmark = pytest.mark.skipif(
    not TRANSPORT.exists(), reason="SPA sources not present")


def _positions(*needles: str) -> list[int]:
    source = TRANSPORT.read_text()
    out = []
    for needle in needles:
        idx = source.find(needle)
        assert idx != -1, f"{needle!r} is gone from transport.js — update this test"
        out.append(idx)
    return out


def test_challenge_values_are_captured_before_joining():
    """
    joinGroup() signs over node_pk and nonce_node, so both must be recorded when
    the challenge arrives — not later, beside the proof.
    """
    # Deliberately loose markers: what matters is where the assignment happens,
    # not how it is spelled, so a reordering fails on the ordering assertion
    # below rather than on a missing string.
    node_pk, nonce_node, join_call = _positions(
        "this.nodePk = reply.node_pk",
        "this._nonceNode = ",
        "await this.joinGroup(",
    )
    assert node_pk < join_call, (
        "node_pk is read from the challenge after joinGroup() runs — the join "
        "would sign a transcript naming nothing")
    assert nonce_node < join_call, (
        "nonce_node is captured after joinGroup() runs — the join would not be "
        "bound to this connection")


def test_join_happens_before_the_gek_proof():
    """
    The whole point of joining in the pre-proof window: someone who has never
    held the group key cannot produce a proof, so the key has to arrive first.
    """
    join_call, proof = _positions(
        "await this.joinGroup(",
        "await C.handshakeProof(",
    )
    assert join_call < proof, (
        "the join must happen before the GEK proof — a first-time member has no "
        "key to prove with")


def test_keys_are_recovered_before_the_join_is_attempted():
    """
    A second browser holds nothing but a password. It recovers its identity keys
    from the node's encrypted keypair bundle, and only then can it sign a join —
    so the recovery has to come first. Getting this order wrong is invisible on
    the browser that registered, and breaks every other one.
    """
    recover, join_call = _positions(
        "type: 'keypair_bundle_fetch'",
        "await this.joinGroup(",
    )
    assert recover < join_call, (
        "the keypair bundle must be fetched before joinGroup() — otherwise a "
        "browser that did not register has no key to sign the join with")


def test_the_ack_still_verifies_the_announced_node_key():
    """
    Taking node_pk from the challenge is only safe because the ack proves it and
    the client compares the two. Losing that check would leave the announcement
    trusted on its own.
    """
    source = TRANSPORT.read_text()
    assert "Node identity changed during the handshake" in source, (
        "the challenge's node_pk must be checked against the ack's")
    assert "verifyNodeSignature" in source, (
        "the ack's signature over the handshake transcript must still be verified")


# ── Component boundaries ────────────────────────────────────────────────────
#
# A second class of bug this file exists for. Moving a block between components
# is a plain cut and paste, and nothing checks that the paste landed somewhere
# the names it uses exist: the invite form and the member list were cut out of
# MembersPanel and pasted into AdminPage, which left a standard member seeing an
# empty Members tab, the group owner seeing only a pairing form, and the hub's
# Users tab referencing `doInvite`, `members` and `adminId` — none of which are
# defined there.

APP = STATIC / "app.js"


def _component(name: str) -> str:
    """The source of one top-level `function Name(...)`, up to the next one."""
    source = APP.read_text()
    start = source.find(f"\nfunction {name}(")
    assert start != -1, f"{name} is gone from app.js — update this test"
    end = source.find("\nfunction ", start + 1)
    return source[start:end if end != -1 else len(source)]


def test_members_panel_renders_what_it_owns():
    panel = _component("MembersPanel")
    assert "members.map(" in panel, "the member list is not rendered"
    assert "onSubmit=${doInvite}" in panel, "the invite form is not rendered"
    assert "onSubmit=${doPair}" in panel, "the pairing form is not rendered"


def test_the_invite_form_comes_before_the_list():
    panel = _component("MembersPanel")
    assert panel.index("onSubmit=${doInvite}") < panel.index("members.map("), \
        "the invite form belongs above the member list"


def test_admin_page_does_not_borrow_the_members_panel_state():
    admin = _component("AdminPage")
    for name in ("doInvite", "adminId", "inviteCode", "setInviteUser"):
        assert name not in admin, \
            f"AdminPage references {name}, which only exists in MembersPanel"


# ── Upload pipelining ───────────────────────────────────────────────────────
#
# The upload loop waited for the node to acknowledge each 48 KB chunk before
# reading the next one, which caps throughput at one chunk per round trip no
# matter how much bandwidth there is — and keeps SCTP's congestion window shut,
# so the transport never speeds up either. Measured over a 100 ms path: 0.16 MB/s
# waiting for every ack, 3.47 MB/s with 32 chunks in flight.

def test_the_uploader_keeps_several_chunks_in_flight():
    src = TRANSPORT.read_text()
    body = src[src.index("async uploadFile("):]
    body = body[:body.index("\n  async ", 1)]
    assert "UPLOAD_WINDOW" in body, "the send window is gone — uploads are serial again"
    assert "bufferedAmount" in body, (
        "without backpressure the file lands in the send buffer in seconds and "
        "the progress bar becomes fiction")


def test_no_caller_waits_for_one_chunk_at_a_time():
    app = APP.read_text()
    assert "uploadChunk(" not in app, (
        "a per-chunk await is back in the SPA; use transport.uploadFile()")