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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
|
"""
Every CLI verb reaches its own code without falling over on a name.
`meshbay-node reload` shipped with `subprocess` unimported and crashed with a
NameError the first time it was typed. Python compiles that file happily —
`node --check validates syntax, not names` is already in CLAUDE.md about the
SPA, and it is the same class here: nothing in the module is wrong until the
branch runs.
So this walks every documented verb with the daemon stubbed out, and asserts
that the branch executes. It is deliberately shallow — what each command *does*
is tested in `test_ops.py` and `test_roster_pairing.py`. What this catches is a
branch nobody ever ran.
"""
import sys
from pathlib import Path
import pytest
from meshbay_node import daemon as daemon_mod
# Each verb, with the arguments that reach its branch. `--yes` where the command
# would otherwise stop for a confirmation nobody can type in a test.
VERBS = [
["status"],
["group", "list"],
["group", "add"], # missing --dir: usage, then exit
["group", "add", "g", "--dir", "/tmp/media", "--no-writable"],
["root", "list"],
["root", "add"], # missing path: usage, then exit
["root", "add", "/tmp/media", "--writable", "--removable"],
["root", "remove", "media", "--yes"],
["root", "set", "media", "--no-writable"],
["root", "set", "media"], # nothing to change: usage, then exit
["root", "eject", "media"],
["root", "plug", "media"],
["gek", "init"],
["gek", "rotate", "--yes"],
["gek-init"],
["member", "list"],
["member", "invite", "bob"],
["member", "revoke", "bob"],
["member", "unpin", "bob"],
# Removed, and it has to say so rather than offering a username for a verb
# that no longer takes one.
["member", "upload"],
["operator", "pair"],
["transfers"], # defaults to show
["transfers", "show"],
["transfers", "set", "4", "2"],
["transfers", "set", "4"], # only one number: usage, then exit
["transfers", "set", "0", "2"], # zero is not "unlimited": refused
["transfers", "per-member", "4", "2"],
["transfers", "per-member", "4"], # only one number: usage, then exit
["transfers", "per-member", "0", "2"], # zero is refused here too
["file", "list"],
["file", "rm", "abc", "--yes"],
["video", "rematch", "--yes"],
["chat", "status"],
["chat", "rotate"],
["chat", "encrypt-history", "--yes"],
["chat", "prune", "30"],
["chat", "prune"], # missing days: usage, then exit
["denylist", "show"],
["denylist", "clear", "--yes"],
["stun", "list"],
["reload"],
["restart-daemon"],
["autostart", "status"],
["service", "status"],
]
@pytest.fixture
def stub_daemon(monkeypatch, tmp_path):
"""
Answer every loopback call with an empty-ish payload.
The point is to reach the branch, not to exercise the daemon: a command that
only crashes when the node is running is still a command that crashes.
"""
calls: list[tuple] = []
def fake_api(cfg, path, method="GET", timeout=30, body=None):
calls.append((method, path))
return {
"groups": [], "files": [], "identities": [], "members": [],
"invites": [], "users": [], "jtis": [], "count": 0, "removed": 0,
"subject": "all", "code": "TEST-CODE", "expires_at": "",
"user_id": "u", "authorized_members": 0, "errors": [],
"name": "g", "group_id": "g", "shared_dir": str(tmp_path),
"config": str(tmp_path / "node.toml"),
# Chat encryption: the switch's answer, the epoch a rotation
# opened, and what a history re-encryption reports.
"enabled": False, "epoch": 1, "converted": 0,
"backup": str(tmp_path / "chat.db.bak"),
"encrypted": False, "plaintext_messages": 0,
"encrypted_messages": 0, "max_age_days": 30,
}
monkeypatch.setattr(daemon_mod, "_daemon_api", fake_api)
monkeypatch.setattr(daemon_mod, "_resolve_group", lambda cfg, g: "g" * 32)
conf = tmp_path / "node.toml"
conf.write_text('[hub]\nurl = "https://example.invalid"\n')
monkeypatch.setattr(daemon_mod, "DEFAULT_CONFIG_PATH", conf)
# No interactive prompt left to hang on.
monkeypatch.setattr("builtins.input", lambda *a: "n")
import getpass
monkeypatch.setattr(getpass, "getpass", lambda *a, **kw: "test-password")
# `reload` and `restart-daemon` shell out to `systemctl --user`. Without
# this the test would run that against whatever session bus is actually
# available — a test must not reach outside itself, which is exactly what
# the pgrep/os.kill version of this fixture existed to prevent before
# those commands were rewritten to delegate to systemd.
import subprocess
systemctl_calls: list[list[str]] = []
def fake_run(argv, **kw):
systemctl_calls.append(argv)
return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
monkeypatch.setattr(subprocess, "run", fake_run)
calls.append(("_systemctl_calls", systemctl_calls))
return calls
@pytest.mark.parametrize("argv", VERBS, ids=lambda a: "-".join(a))
def test_every_verb_reaches_its_branch(argv, stub_daemon, monkeypatch, capsys):
monkeypatch.setattr(sys, "argv", ["meshbay-node", *argv])
try:
daemon_mod.main()
except SystemExit:
# A usage message and exit(1) is a branch that ran, which is what this
# asserts. A NameError or AttributeError is not.
pass
except (NameError, AttributeError) as e: # pragma: no cover
pytest.fail(f"{' '.join(argv)} crashed on a name: {e}")
out = capsys.readouterr()
assert out.out or out.err, f"{' '.join(argv)} printed nothing at all"
def test_the_verb_list_here_matches_the_parser():
"""
A verb added to the parser and not to this file would go untested, which is
exactly how `reload` shipped broken.
"""
import argparse
import inspect
source = inspect.getsource(daemon_mod.main)
start = source.index('choices=[') + len('choices=[')
end = source.index(']', start)
declared = {c.strip().strip('"\'') for c in source[start:end].split(',')
if c.strip()}
exercised = {argv[0] for argv in VERBS}
# `init` writes a config file and `calibrate-argon2` burns CPU for seconds;
# both are excluded on purpose rather than by omission.
untested = declared - exercised - {"init", "reset", "calibrate-argon2"}
assert not untested, (
f"CLI verbs with no dispatch test: {sorted(untested)} — add them to "
f"VERBS above")
# The server-rendered admin UI (and its `ui` verb) were removed in
# docs/MESHBAY_DESIGN.md §6.7. The control API stays; the browser
# page does not.
assert "ui" not in declared, "the `ui` verb came back"
@pytest.mark.skipif(sys.platform == "win32",
reason="systemd lifecycle; Windows uses the loopback API / "
"Startup-folder launcher, covered by test_platform.py")
@pytest.mark.parametrize("argv,verb", [
(["reload"], "reload"),
(["restart-daemon"], "restart"),
])
def test_lifecycle_commands_delegate_to_systemctl_user(
argv, verb, stub_daemon, monkeypatch, capsys):
"""
`reload` and `restart-daemon` must ask systemd to do it, not hunt a PID
with pgrep and signal it directly — that pattern-matched a developer's own
running node by accident once, which is why it was replaced.
They must also reload the user manager's view of unit files first: a
package upgrade only reloads the *system* manager (it runs as root and
cannot reach a signed-in user's own), so the user manager can still be
holding a stale unit when one of these runs.
"""
monkeypatch.setattr(sys, "argv", ["meshbay-node", *argv])
daemon_mod.main()
systemctl_calls = dict(stub_daemon)["_systemctl_calls"]
assert systemctl_calls == [
["systemctl", "--user", "daemon-reload"],
["systemctl", "--user", verb, "meshbay-node"],
]
assert not capsys.readouterr().err
@pytest.mark.skipif(sys.platform == "win32",
reason="systemd lifecycle; Windows uses the loopback API / "
"Startup-folder launcher, covered by test_platform.py")
@pytest.mark.parametrize("argv", [["reload"], ["restart-daemon"]])
def test_lifecycle_commands_report_systemctl_failure(
argv, stub_daemon, monkeypatch, capsys):
"""A unit that refuses (not installed, not running) must exit non-zero."""
import subprocess
monkeypatch.setattr(
subprocess, "run",
lambda a, **k: subprocess.CompletedProcess(
a, 1, stdout="", stderr="Unit meshbay-node.service not loaded.\n"))
monkeypatch.setattr(sys, "argv", ["meshbay-node", *argv])
with pytest.raises(SystemExit) as exc:
daemon_mod.main()
assert exc.value.code == 1
assert "not loaded" in capsys.readouterr().out
def test_a_bare_invocation_with_no_config_yet_exits_cleanly(monkeypatch, tmp_path, capsys):
"""
A bare `meshbay-node` — no subcommand, nothing dispatches, falls through to
"start the daemon" at the bottom of main() — is exactly what the Windows W3
Startup .vbs and the service-mode Scheduled Task both run unattended. On a
fresh install neither has ever provisioned anything, so this is the first
thing that runs on the very first boot, quite possibly before the user has
ever opened the client.
This must fail closed, fast, and without a trace: no exception (nothing
catches one — the .vbs and the Scheduled Task are both headless, so an
uncaught crash is invisible and, run on every boot, an inert but permanent
fixture in the Task Scheduler history and Windows' own Application log).
Confirmed by hand first: measured under a second and zero bytes written
to disk against a real, empty %LOCALAPPDATA%.
load_config() already returns an empty Config when the path does not
exist rather than raising — this pins that main() then notices the empty
hub.username and exits before ever reaching NodeDaemon()/asyncio.run(),
so nothing here has to mock the daemon startup at all.
"""
missing_config = tmp_path / "does-not-exist" / "node.toml"
monkeypatch.setattr(daemon_mod, "DEFAULT_CONFIG_PATH", missing_config)
monkeypatch.setattr(sys, "argv", ["meshbay-node"])
with pytest.raises(SystemExit) as exc:
daemon_mod.main()
assert exc.value.code == 1
assert "meshbay-node init" in capsys.readouterr().out
assert not missing_config.parent.exists(), (
"a fresh, unprovisioned start must not create anything on disk")
def test_a_removed_verb_says_what_replaced_it():
"""
`member upload` used to set a group-wide switch that no longer exists. It
reached the usage line for the *other* member verbs — "usage: meshbay-node
member upload <username>" — which advertises a removed feature and sends
the operator looking for a username it would then reject.
Naming it costs three lines and is the difference between an operator
finding `root set --writable` and concluding the CLI is broken.
"""
import inspect
source = inspect.getsource(daemon_mod.main)
start = source.index('if args.command == "member":')
block = source[start:source.index('if args.command == "group":', start)]
assert 'sub == "upload"' in block, (
"`member upload` falls through to the generic usage line")
guidance = block[block.index('sub == "upload"'):]
guidance = guidance[:guidance.index("sys.exit")]
assert "root set" in guidance and "--writable" in guidance, (
"the message does not name what replaced it")
def test_there_is_no_way_to_create_a_group_in_the_old_shape():
"""
`--upload-dir` is gone, and documenting it as deprecated was the wrong
answer — which is what it got at first.
It wrote `upload_dir` into a brand-new `[[groups]]` block, and
`GroupConfig.__post_init__` reads that by forcing *every other root
read-only* and appending that path as the one writable one. So
`group add --dir X --writable --upload-dir Y` silently made X read-only:
two mechanisms deciding which directories accept uploads, one of them
invisible, in a group created after the model that replaced it.
Reading it stays — an existing node.toml must keep working, and that is the
only legitimate use. Writing it does not.
"""
import inspect
source = inspect.getsource(daemon_mod.main)
assert "--upload-dir" not in source, (
"the CLI can still create a group in the pre-RO/RW shape")
from meshbay_node import ops
params = inspect.signature(ops.attach_group).parameters
assert "upload_dir" not in params, (
"attach_group still writes the legacy key")
# The read path is deliberately untouched.
from meshbay_node.config import GroupConfig
assert "upload_dir" in inspect.getsource(GroupConfig), (
"an existing node.toml using upload_dir would stop working")
|