integrate the session broker: one CLI, a module unit, and a VM check
M0 of the sessions design, wired into the flake and gated by a real check. What is here now: - `src/hhstreamd/` — the broker: session registry, lifecycle verbs, process-group teardown, app allowlist, audit log, idle reaper on CLOCK_BOOTTIME. - `src/hhstream_session/` — the CLI handlers, registered into the one front door. - `src/hhstream/cli.py` — `hhstream status|shot|run|record|session …`, so the frame verbs and the session namespace are one binary. - `nix/module.nix` — `sessions.*` options and the `hhstream-sessions.service` unit: the operator's own account (never a service account, because launched applications should see that account's home), the compositor's group as a supplementary group (without it a launched GUI client cannot open the Wayland socket), the generated app allowlist, and `--compositor-runtime-dir` so applications are handed the compositor's session rather than the broker's. - `checks/vm-sessions.nix` — 18 subtests on a real compositor in a VM. Two bugs found by driving it, both fixed: - BUG-01: launched applications could not reach the compositor at all — the broker spawned them with its own inherited environment, which names the login session. `hhstreamd/compositor.py` discovers the socket and builds the child environment; a directory with no usable socket is a startup refusal, not a warning. - BUG-02: `kill` refused to signal a live application and said nothing was wrong. The identity gate hashed `/proc/<pid>/cmdline`, which every `execve` replaces — and on NixOS applications are reached through wrapper scripts that do exactly that. The gate now rests on `starttime` (+ boot id, + session id where it is immutable) and records command-line drift as evidence of nothing. KillMode=process is set on the unit on purpose: the default control-group kill would take the applications down with the broker, which would make adoption and a broker restart pointless.
This commit is contained in:
1 parent
9dc9e0da9a
commit
30f456c07e
37 files changed
+9118
-1
No files matched your search
@@ -0,0 +1,306 @@
|
||||
"""The integration contract: ``register(subparsers)`` into someone else's CLI.
|
||||
|
||||
The registrant is assumed to know nothing about the daemon beyond the socket
|
||||
path, so these tests drive the handlers through a host parser they build
|
||||
themselves and stub out the transport.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
|
||||
import pytest
|
||||
|
||||
import hhstream_session
|
||||
from hhstream_session import register
|
||||
from hhstream_session.client import ClientError
|
||||
from hhstreamd.protocol import ExitCode
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def host_cli():
|
||||
"""A stand-in for the pre-existing ``hhstream`` CLI."""
|
||||
|
||||
parser = argparse.ArgumentParser(prog="hhstream")
|
||||
sub = parser.add_subparsers(dest="command")
|
||||
|
||||
existing = sub.add_parser("frame", help="an existing subcommand")
|
||||
existing.set_defaults(func=lambda args: 0)
|
||||
|
||||
register(sub)
|
||||
return parser
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sent(monkeypatch):
|
||||
"""Capture what the handlers would send, and reply with what the test wants."""
|
||||
|
||||
class Transport(list):
|
||||
"""The captured requests, plus the canned replies to hand back."""
|
||||
|
||||
replies = [
|
||||
{
|
||||
"ok": True,
|
||||
"id": "stub-aaaaaa",
|
||||
"session": {"id": "stub-aaaaaa", "state": "ready"},
|
||||
"sessions": [],
|
||||
"lines": [],
|
||||
}
|
||||
]
|
||||
|
||||
calls = Transport()
|
||||
|
||||
def fake_call(op, *, socket_path=None, timeout=None, **fields):
|
||||
# Mirror protocol.request(): unset fields are not put on the wire, so
|
||||
# the tests below can assert on what is actually sent.
|
||||
wire = {k: v for k, v in fields.items() if v is not None}
|
||||
calls.append({"op": op, "socket_path": socket_path, **wire})
|
||||
return calls.replies[min(len(calls) - 1, len(calls.replies) - 1)]
|
||||
|
||||
monkeypatch.setattr(hhstream_session, "call", fake_call)
|
||||
return calls
|
||||
|
||||
|
||||
def run(parser: argparse.ArgumentParser, argv: list[str]) -> tuple[int, str, str]:
|
||||
args = parser.parse_args(argv)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with redirect_stdout(out), redirect_stderr(err):
|
||||
code = hhstream_session.dispatch(args)
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# registration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_registration_adds_exactly_one_subcommand_and_leaves_the_host_alone(host_cli):
|
||||
args = host_cli.parse_args(["frame"])
|
||||
assert args.func(args) == 0 # the pre-existing subcommand still works
|
||||
|
||||
args = host_cli.parse_args(["session", "list"])
|
||||
assert callable(args.func)
|
||||
|
||||
|
||||
def test_the_handler_is_exposed_under_both_the_common_name_and_a_namespaced_one(host_cli):
|
||||
args = host_cli.parse_args(["session", "status", "foo-aaaaaa"])
|
||||
assert args.func is args.hhstream_session_handler
|
||||
|
||||
|
||||
def test_every_v1_verb_is_registered(host_cli):
|
||||
for verb in ["start", "list", "status", "touch", "kill", "gc", "adopt", "logs"]:
|
||||
argv = ["session", verb]
|
||||
if verb in ("status", "touch", "kill", "logs"):
|
||||
argv.append("foo-aaaaaa")
|
||||
if verb == "start":
|
||||
argv.append("foot")
|
||||
if verb == "adopt":
|
||||
argv += ["--pid", "1234"]
|
||||
args = host_cli.parse_args(argv)
|
||||
assert callable(args.func), verb
|
||||
|
||||
|
||||
def test_session_with_no_verb_lists(host_cli, sent):
|
||||
code, _, _ = run(host_cli, ["session"])
|
||||
assert code == ExitCode.OK
|
||||
assert sent[0]["op"] == "list"
|
||||
|
||||
|
||||
def test_the_socket_may_be_given_before_or_after_the_verb(host_cli, sent):
|
||||
run(host_cli, ["session", "--socket", "/a.sock", "list"])
|
||||
run(host_cli, ["session", "list", "--socket", "/b.sock"])
|
||||
assert sent[0]["socket_path"] == "/a.sock"
|
||||
assert sent[1]["socket_path"] == "/b.sock"
|
||||
|
||||
|
||||
def test_the_socket_falls_back_to_the_environment(host_cli, sent, monkeypatch):
|
||||
"""The registrant's only piece of daemon knowledge."""
|
||||
|
||||
monkeypatch.setenv("HHSTREAM_SOCKET", "/env.sock")
|
||||
run(host_cli, ["session", "list"])
|
||||
# The handler passes None through; the client resolves the default.
|
||||
assert sent[0]["socket_path"] is None
|
||||
from hhstream_session.client import default_socket_path
|
||||
|
||||
assert default_socket_path() == "/env.sock"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# request shapes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_start_sends_the_app_and_an_argv_list_never_a_command_string(host_cli, sent):
|
||||
run(host_cli, ["session", "start", "chromium", "--", "--new-window", "https://example.com"])
|
||||
assert sent[0]["op"] == "start"
|
||||
assert sent[0]["app"] == "chromium"
|
||||
assert sent[0]["argv"] == ["--new-window", "https://example.com"]
|
||||
|
||||
|
||||
def test_this_commands_own_flags_still_parse_after_the_app_name(host_cli, sent):
|
||||
"""The separator divides the two argvs; it does not divide the parsers."""
|
||||
|
||||
run(host_cli, ["session", "start", "chromium", "--idle-timeout", "5m", "--", "--new-window"])
|
||||
assert sent[0]["idle_timeout_s"] == 300.0
|
||||
assert sent[0]["argv"] == ["--new-window"]
|
||||
|
||||
|
||||
def test_an_application_flag_after_the_separator_is_never_read_as_ours(host_cli, sent):
|
||||
run(host_cli, ["session", "start", "chromium", "--", "--idle-timeout", "5m"])
|
||||
assert "idle_timeout_s" not in sent[0]
|
||||
assert sent[0]["argv"] == ["--idle-timeout", "5m"]
|
||||
|
||||
|
||||
def test_durations_are_parsed_on_the_way_in(host_cli, sent):
|
||||
run(host_cli, ["session", "start", "foot", "--idle-timeout", "3h"])
|
||||
assert sent[0]["idle_timeout_s"] == 10800.0
|
||||
run(host_cli, ["session", "kill", "foo-aaaaaa", "--grace", "30s"])
|
||||
assert sent[1]["grace_s"] == 30.0
|
||||
|
||||
|
||||
def test_a_bad_duration_is_rejected_by_argparse(host_cli):
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(["session", "start", "foot", "--idle-timeout", "soon"])
|
||||
|
||||
|
||||
def test_home_and_ephemeral_home_are_mutually_exclusive(host_cli):
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(["session", "start", "foot", "--home", "/x", "--ephemeral-home"])
|
||||
|
||||
|
||||
def test_ephemeral_home_is_opt_in_and_absent_by_default(host_cli, sent):
|
||||
run(host_cli, ["session", "start", "foot"])
|
||||
assert "ephemeral_home" not in sent[0]
|
||||
run(host_cli, ["session", "start", "foot", "--ephemeral-home"])
|
||||
assert sent[1]["ephemeral_home"] is True
|
||||
|
||||
|
||||
def test_list_all_is_only_sent_when_asked(host_cli, sent):
|
||||
run(host_cli, ["session", "list"])
|
||||
assert "all" not in sent[0]
|
||||
run(host_cli, ["session", "list", "--all"])
|
||||
assert sent[1]["all"] is True
|
||||
|
||||
|
||||
def test_request_ids_are_forwarded_on_mutating_verbs(host_cli, sent):
|
||||
run(host_cli, ["session", "start", "foot", "--request-id", "abc"])
|
||||
assert sent[0]["request_id"] == "abc"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# output and exit codes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_start_prints_the_bare_id_on_stdout_and_detail_on_stderr(host_cli, sent):
|
||||
sent.replies[:] = [
|
||||
{
|
||||
"ok": True,
|
||||
"id": "foot-k3f9qx",
|
||||
"session": {
|
||||
"id": "foot-k3f9qx",
|
||||
"app": "foot",
|
||||
"pid": 48812,
|
||||
"pgid": 48812,
|
||||
"sid": 48812,
|
||||
"state": "ready",
|
||||
"ready_signal": "spawned",
|
||||
"idle_timeout_s": 10800,
|
||||
},
|
||||
}
|
||||
]
|
||||
code, out, err = run(host_cli, ["session", "start", "foot"])
|
||||
assert code == ExitCode.OK
|
||||
assert out == "foot-k3f9qx\n" # exactly the id, so $(...) works
|
||||
assert "pid 48812" in err
|
||||
assert "touch foot-k3f9qx" in err # the keepalive is named where it is needed
|
||||
|
||||
|
||||
def test_start_json_puts_one_object_on_stdout_and_nothing_on_stderr(host_cli, sent):
|
||||
sent.replies[:] = [{"ok": True, "id": "foot-k3f9qx", "session": {"id": "foot-k3f9qx"}}]
|
||||
code, out, err = run(host_cli, ["session", "start", "--json", "foot"])
|
||||
assert code == ExitCode.OK
|
||||
assert json.loads(out) == {"id": "foot-k3f9qx"}
|
||||
assert err == ""
|
||||
|
||||
|
||||
def test_json_is_available_on_every_read_verb(host_cli, sent):
|
||||
sent.replies[:] = [{"ok": True, "sessions": []}]
|
||||
code, out, _ = run(host_cli, ["session", "list", "--json"])
|
||||
assert json.loads(out)["ok"] is True
|
||||
|
||||
sent.replies[:] = [{"ok": True, "session": {"id": "a"}, "id": "a"}]
|
||||
code, out, _ = run(host_cli, ["session", "status", "--json", "a"])
|
||||
assert json.loads(out)["session"] == {"id": "a"}
|
||||
|
||||
sent.replies[:] = [{"ok": True, "lines": ["hello"], "offset": 6, "eof": True}]
|
||||
code, out, _ = run(host_cli, ["session", "logs", "--json", "a"])
|
||||
assert json.loads(out)["lines"] == ["hello"]
|
||||
|
||||
|
||||
def test_errors_go_to_stderr_with_the_machine_field_in_json_mode(host_cli, sent):
|
||||
sent.replies[:] = [
|
||||
{"ok": False, "error": "not_allowlisted", "reason": "app 'sh' is not in the allowlist"}
|
||||
]
|
||||
code, out, err = run(host_cli, ["session", "start", "--json", "sh"])
|
||||
assert code == ExitCode.POLICY
|
||||
assert out == ""
|
||||
assert json.loads(err)["error"] == "not_allowlisted"
|
||||
|
||||
|
||||
def test_errors_are_human_readable_without_json(host_cli, sent):
|
||||
sent.replies[:] = [
|
||||
{"ok": False, "error": "no_such_session", "reason": "no session 'x'", "hint": "try list"}
|
||||
]
|
||||
code, out, err = run(host_cli, ["session", "status", "x"])
|
||||
assert code == ExitCode.NO_SUCH_SESSION
|
||||
assert "no session 'x'" in err and "try list" in err
|
||||
|
||||
|
||||
def test_a_transport_failure_becomes_exit_five_not_a_traceback(host_cli, monkeypatch):
|
||||
def boom(*args, **kwargs):
|
||||
raise ClientError("daemon_unreachable", "nothing is listening", hint="start it")
|
||||
|
||||
monkeypatch.setattr(hhstream_session, "call", boom)
|
||||
code, _, err = run(host_cli, ["session", "list"])
|
||||
assert code == ExitCode.DAEMON_UNREACHABLE
|
||||
assert "nothing is listening" in err and "start it" in err
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the activity contract, as documented to the user
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_help_text_says_touch_is_the_only_mark_of_activity(host_cli):
|
||||
out = io.StringIO()
|
||||
with redirect_stdout(out):
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(["session", "--help"])
|
||||
text = out.getvalue()
|
||||
assert "touch" in text
|
||||
assert "ONLY" in text
|
||||
for verb in ["list", "status", "logs", "gc"]:
|
||||
assert verb in text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("verb", ["list", "status", "logs", "gc"])
|
||||
def test_each_read_verbs_help_says_it_does_not_count(host_cli, verb):
|
||||
out = io.StringIO()
|
||||
with redirect_stdout(out):
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(["session", "--help"])
|
||||
line = [l for l in out.getvalue().splitlines() if l.strip().startswith(verb)]
|
||||
assert line, verb
|
||||
assert "does NOT count" in " ".join(out.getvalue().split())
|
||||
|
||||
|
||||
def test_touchs_help_calls_itself_the_only_mark_of_activity(host_cli):
|
||||
out = io.StringIO()
|
||||
with redirect_stdout(out):
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(["session", "touch", "--help"])
|
||||
assert "only verb that counts as activity" in " ".join(out.getvalue().split())
|
||||
@@ -0,0 +1,414 @@
|
||||
"""BUG-01: a launched application must be able to reach the compositor.
|
||||
|
||||
Every test here fails against the pre-fix daemon, which spawned children with
|
||||
its own inherited environment — on the target machine the *login* session, with
|
||||
no compositor listening in it — so every GUI application died within a second of
|
||||
``start`` and the only symptom was ``state exited`` one command later.
|
||||
|
||||
A note on the fixtures: a Wayland socket that is **bound but not listening**
|
||||
gives ``ECONNREFUSED`` on connect, which is exactly what a socket left behind by
|
||||
a crashed compositor looks like. A bound *and listening* socket is what a live
|
||||
one looks like. That is the whole difference between the two helpers below, and
|
||||
it is why the tests need no compositor.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from conftest import SUN_PATH_MAX
|
||||
from hhstreamd import compositor
|
||||
from hhstreamd.__main__ import (
|
||||
ENV_COMPOSITOR_RUNTIME_DIR,
|
||||
build_parser,
|
||||
main,
|
||||
resolve_compositor,
|
||||
)
|
||||
from hhstreamd.compositor import CompositorError, CompositorSession, CompositorTarget, discover
|
||||
from hhstreamd.launcher import Launcher
|
||||
|
||||
|
||||
def _bind(directory: Path, name: str, *, listening: bool) -> socket.socket:
|
||||
path = directory / name
|
||||
if len(str(path).encode()) > SUN_PATH_MAX:
|
||||
pytest.skip(f"socket path too long for AF_UNIX: {path}")
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.bind(str(path))
|
||||
if listening:
|
||||
sock.listen(4)
|
||||
return sock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sockets():
|
||||
"""Open sockets closed at teardown, so no test leaks a listener."""
|
||||
|
||||
opened: list[socket.socket] = []
|
||||
|
||||
def make(directory: Path, name: str, *, listening: bool = True) -> Path:
|
||||
sock = _bind(directory, name, listening=listening)
|
||||
opened.append(sock)
|
||||
return directory / name
|
||||
|
||||
try:
|
||||
yield make
|
||||
finally:
|
||||
for sock in opened:
|
||||
sock.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# discovery: the socket's name is found, never assumed
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_discovers_wayland_1_not_wayland_0(short_tmpdir, sockets):
|
||||
"""The target machine's compositor is on ``wayland-1``. Nothing may assume ``-0``."""
|
||||
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
session = discover(short_tmpdir)
|
||||
assert session.wayland_display == "wayland-1"
|
||||
assert session.runtime_dir == short_tmpdir.resolve()
|
||||
assert session.socket_path == short_tmpdir.resolve() / "wayland-1"
|
||||
|
||||
|
||||
def test_ignores_lock_files_and_other_non_sockets(short_tmpdir, sockets):
|
||||
"""``wayland-1.lock`` is a regular file libwayland writes beside the socket."""
|
||||
|
||||
(short_tmpdir / "wayland-1.lock").write_text("")
|
||||
(short_tmpdir / "wayland-0").write_text("not a socket") # a leftover regular file
|
||||
(short_tmpdir / "wayland-9").mkdir() # and a directory named like one
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
assert discover(short_tmpdir).wayland_display == "wayland-1"
|
||||
|
||||
|
||||
def test_candidates_lists_only_sockets(short_tmpdir, sockets):
|
||||
sockets(short_tmpdir, "wayland-0")
|
||||
(short_tmpdir / "wayland-0.lock").write_text("")
|
||||
(short_tmpdir / "bus").write_text("")
|
||||
assert compositor.candidates(short_tmpdir.resolve()) == ["wayland-0"]
|
||||
|
||||
|
||||
def test_a_live_socket_beats_a_crashed_compositors_leftover(short_tmpdir, sockets):
|
||||
"""Both are sockets; only one has anything behind it."""
|
||||
|
||||
sockets(short_tmpdir, "wayland-1", listening=False) # refuses connections
|
||||
sockets(short_tmpdir, "wayland-0", listening=True)
|
||||
assert discover(short_tmpdir).wayland_display == "wayland-0"
|
||||
|
||||
|
||||
def test_among_live_sockets_the_later_name_wins(short_tmpdir, sockets):
|
||||
"""A compositor takes the first free name, so the survivor of a restart is later."""
|
||||
|
||||
sockets(short_tmpdir, "wayland-0")
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
assert discover(short_tmpdir).wayland_display == "wayland-1"
|
||||
|
||||
|
||||
def test_non_numeric_suffix_is_usable_but_ranks_last(short_tmpdir, sockets):
|
||||
sockets(short_tmpdir, "wayland-hyprland")
|
||||
assert discover(short_tmpdir).wayland_display == "wayland-hyprland"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# fail loudly, early, and correctly
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_empty_runtime_dir_is_refused_and_named(short_tmpdir):
|
||||
with pytest.raises(CompositorError) as exc:
|
||||
discover(short_tmpdir)
|
||||
message = str(exc.value)
|
||||
assert str(short_tmpdir.resolve()) in message
|
||||
assert "no Wayland socket" in message
|
||||
# It must not be mistaken for the daemon's own --runtime-dir.
|
||||
assert "--runtime-dir" in message
|
||||
|
||||
|
||||
def test_missing_runtime_dir_is_refused_and_named(short_tmpdir):
|
||||
missing = short_tmpdir / "nope"
|
||||
with pytest.raises(CompositorError) as exc:
|
||||
discover(missing)
|
||||
assert str(missing) in str(exc.value)
|
||||
|
||||
|
||||
def test_a_file_in_place_of_the_runtime_dir_is_refused(short_tmpdir):
|
||||
path = short_tmpdir / "file"
|
||||
path.write_text("")
|
||||
with pytest.raises(CompositorError) as exc:
|
||||
discover(path)
|
||||
assert str(path) in str(exc.value)
|
||||
|
||||
|
||||
def test_only_stale_sockets_is_refused(short_tmpdir, sockets):
|
||||
"""Accepting work here would kill every application that arrived."""
|
||||
|
||||
sockets(short_tmpdir, "wayland-0", listening=False)
|
||||
sockets(short_tmpdir, "wayland-1", listening=False)
|
||||
with pytest.raises(CompositorError) as exc:
|
||||
discover(short_tmpdir)
|
||||
message = str(exc.value)
|
||||
assert str(short_tmpdir.resolve()) in message
|
||||
assert "no usable Wayland socket" in message
|
||||
assert "wayland-0" in message and "wayland-1" in message
|
||||
|
||||
|
||||
def test_an_unconnectable_but_not_refused_socket_is_used_with_a_warning(
|
||||
short_tmpdir, sockets, caplog, monkeypatch
|
||||
):
|
||||
"""An ambiguous probe (EACCES, a timeout) is a warning, not an outage."""
|
||||
|
||||
sockets(short_tmpdir, "wayland-1", listening=False)
|
||||
|
||||
def refuse_with_eacces(path):
|
||||
return compositor._Candidate(Path(path).name, False, False, "PermissionError: denied")
|
||||
|
||||
monkeypatch.setattr(compositor, "_probe", refuse_with_eacces)
|
||||
with caplog.at_level(logging.WARNING, logger="hhstreamd.compositor"):
|
||||
assert discover(short_tmpdir).wayland_display == "wayland-1"
|
||||
assert "did not accept a probe connection" in caplog.text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the environment a child is given
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_session_env_is_the_three_variables():
|
||||
session = CompositorSession(runtime_dir=Path("/run/user/1001"), wayland_display="wayland-1")
|
||||
assert session.env() == {
|
||||
"XDG_RUNTIME_DIR": "/run/user/1001",
|
||||
"WAYLAND_DISPLAY": "wayland-1",
|
||||
"XDG_SESSION_TYPE": "wayland",
|
||||
}
|
||||
|
||||
|
||||
def test_child_env_is_built_from_the_compositor_runtime_dir(short_tmpdir, sockets, tmp_path):
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
launcher = Launcher(
|
||||
tmp_path / "runtime",
|
||||
tmp_path / "state",
|
||||
compositor=CompositorTarget.from_runtime_dir(short_tmpdir),
|
||||
)
|
||||
env = launcher.build_env("chromium-uynn6w", tmp_path / "home")
|
||||
|
||||
assert env["XDG_RUNTIME_DIR"] == str(short_tmpdir.resolve())
|
||||
assert env["WAYLAND_DISPLAY"] == "wayland-1"
|
||||
assert env["XDG_SESSION_TYPE"] == "wayland"
|
||||
# Not the daemon's own runtime dir, and not the session's private one.
|
||||
assert env["XDG_RUNTIME_DIR"] != str(launcher.session_runtime_dir("chromium-uynn6w"))
|
||||
# The private directory is still created: the daemon owns and cleans it up.
|
||||
assert launcher.session_runtime_dir("chromium-uynn6w").is_dir()
|
||||
|
||||
|
||||
def test_child_env_keeps_the_inherited_environment_underneath(
|
||||
short_tmpdir, sockets, tmp_path, monkeypatch
|
||||
):
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
monkeypatch.setenv("PATH", "/usr/bin")
|
||||
monkeypatch.setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus")
|
||||
launcher = Launcher(
|
||||
tmp_path / "runtime",
|
||||
tmp_path / "state",
|
||||
compositor=CompositorTarget.from_runtime_dir(short_tmpdir),
|
||||
)
|
||||
env = launcher.build_env("s", tmp_path / "home")
|
||||
assert env["PATH"] == "/usr/bin"
|
||||
assert env["DBUS_SESSION_BUS_ADDRESS"] == "unix:path=/run/user/1000/bus"
|
||||
assert env["HOME"] == str(tmp_path / "home")
|
||||
assert env["HHSTREAM_SESSION_ID"] == "s"
|
||||
|
||||
|
||||
def test_the_daemons_own_configuration_never_leaks_to_a_child(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv(ENV_COMPOSITOR_RUNTIME_DIR, "/run/user/1001")
|
||||
env = Launcher(tmp_path / "runtime", tmp_path / "state").build_env("s", tmp_path)
|
||||
assert ENV_COMPOSITOR_RUNTIME_DIR not in env
|
||||
|
||||
|
||||
def test_without_a_compositor_the_inherited_environment_still_stands(tmp_path, monkeypatch):
|
||||
"""Point 4 of the brief: the old behaviour is kept, not broken."""
|
||||
|
||||
monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-7")
|
||||
monkeypatch.delenv("XDG_SESSION_TYPE", raising=False)
|
||||
launcher = Launcher(tmp_path / "runtime", tmp_path / "state")
|
||||
env = launcher.build_env("s", tmp_path / "home")
|
||||
assert env["XDG_RUNTIME_DIR"] == str(launcher.session_runtime_dir("s"))
|
||||
assert env["WAYLAND_DISPLAY"] == "wayland-7" # passed through, not invented
|
||||
assert "XDG_SESSION_TYPE" not in env
|
||||
|
||||
|
||||
def test_the_recorded_runtime_dir_stays_the_one_the_daemon_may_delete(
|
||||
short_tmpdir, sockets, tmp_path
|
||||
):
|
||||
"""``discard_runtime_dir`` must never be pointed at another user's directory."""
|
||||
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
launcher = Launcher(
|
||||
tmp_path / "runtime",
|
||||
tmp_path / "state",
|
||||
compositor=CompositorTarget.from_runtime_dir(short_tmpdir),
|
||||
)
|
||||
spawned = launcher.spawn("s", [sys.executable, "-c", "pass"])
|
||||
spawned.process.wait(timeout=10)
|
||||
assert spawned.runtime_dir == str(launcher.session_runtime_dir("s"))
|
||||
assert spawned.runtime_dir != str(short_tmpdir.resolve())
|
||||
|
||||
|
||||
def test_a_real_child_sees_the_compositor_environment(short_tmpdir, sockets, tmp_path):
|
||||
"""The end of the chain: what the process actually gets after exec."""
|
||||
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
launcher = Launcher(
|
||||
tmp_path / "runtime",
|
||||
tmp_path / "state",
|
||||
compositor=CompositorTarget.from_runtime_dir(short_tmpdir),
|
||||
)
|
||||
code = (
|
||||
"import json, os, sys; "
|
||||
"sys.stdout.write(json.dumps({k: os.environ.get(k) for k in "
|
||||
"('XDG_RUNTIME_DIR', 'WAYLAND_DISPLAY', 'XDG_SESSION_TYPE')}))"
|
||||
)
|
||||
spawned = launcher.spawn("s", [sys.executable, "-c", code])
|
||||
assert spawned.process.wait(timeout=30) == 0
|
||||
seen = json.loads(Path(spawned.log_path).read_text())
|
||||
assert seen == {
|
||||
"XDG_RUNTIME_DIR": str(short_tmpdir.resolve()),
|
||||
"WAYLAND_DISPLAY": "wayland-1",
|
||||
"XDG_SESSION_TYPE": "wayland",
|
||||
}
|
||||
# And the socket it was pointed at is really there.
|
||||
assert stat.S_ISSOCK(os.stat(short_tmpdir / seen["WAYLAND_DISPLAY"]).st_mode)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# re-resolution: the compositor can restart under a running daemon
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_target_follows_a_compositor_that_came_back_on_another_socket(short_tmpdir, sockets):
|
||||
first = sockets(short_tmpdir, "wayland-0")
|
||||
target = CompositorTarget.from_runtime_dir(short_tmpdir)
|
||||
assert target.session.wayland_display == "wayland-0"
|
||||
|
||||
sockets(short_tmpdir, "wayland-1") # restarted compositor, new name
|
||||
first.unlink() # the old socket file went with the old compositor
|
||||
|
||||
assert target.env()["WAYLAND_DISPLAY"] == "wayland-1"
|
||||
assert target.session.wayland_display == "wayland-1"
|
||||
|
||||
|
||||
def test_target_keeps_the_last_known_good_when_re_resolution_fails(short_tmpdir, sockets, caplog):
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
target = CompositorTarget.from_runtime_dir(short_tmpdir)
|
||||
(short_tmpdir / "wayland-1").unlink() # compositor gone, mid-flight
|
||||
|
||||
with caplog.at_level(logging.WARNING, logger="hhstreamd.compositor"):
|
||||
env = target.env()
|
||||
assert env["WAYLAND_DISPLAY"] == "wayland-1"
|
||||
assert "re-resolving the compositor socket failed" in caplog.text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the daemon's startup contract
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _args(argv: list[str]):
|
||||
return build_parser().parse_args(argv)
|
||||
|
||||
|
||||
def test_the_option_and_the_environment_variable_are_both_accepted(monkeypatch):
|
||||
monkeypatch.setenv(ENV_COMPOSITOR_RUNTIME_DIR, "/from/env")
|
||||
assert _args([]).compositor_runtime_dir == "/from/env"
|
||||
assert _args(["--compositor-runtime-dir", "/from/flag"]).compositor_runtime_dir == "/from/flag"
|
||||
|
||||
|
||||
def test_no_option_means_no_compositor_and_a_startup_warning(monkeypatch, caplog):
|
||||
monkeypatch.delenv(ENV_COMPOSITOR_RUNTIME_DIR, raising=False)
|
||||
with caplog.at_level(logging.WARNING, logger="hhstreamd"):
|
||||
assert resolve_compositor(_args([])) is None
|
||||
assert "may not be able to reach a compositor" in caplog.text
|
||||
assert "--compositor-runtime-dir" in caplog.text
|
||||
|
||||
|
||||
def test_resolve_compositor_returns_a_target_when_the_socket_is_there(short_tmpdir, sockets):
|
||||
sockets(short_tmpdir, "wayland-1")
|
||||
target = resolve_compositor(_args(["--compositor-runtime-dir", str(short_tmpdir)]))
|
||||
assert target is not None
|
||||
assert target.session.wayland_display == "wayland-1"
|
||||
|
||||
|
||||
def test_daemon_refuses_to_start_on_an_unusable_compositor_dir(short_tmpdir, capsys, monkeypatch):
|
||||
"""Exit before listening, with the directory in the message."""
|
||||
|
||||
monkeypatch.delenv(ENV_COMPOSITOR_RUNTIME_DIR, raising=False)
|
||||
code = main(
|
||||
[
|
||||
"--check",
|
||||
"--socket",
|
||||
str(short_tmpdir / "c.sock"),
|
||||
"--state-dir",
|
||||
str(short_tmpdir / "state"),
|
||||
"--runtime-dir",
|
||||
str(short_tmpdir / "runtime"),
|
||||
"--config",
|
||||
str(short_tmpdir / "missing.toml"),
|
||||
"--compositor-runtime-dir",
|
||||
str(short_tmpdir),
|
||||
]
|
||||
)
|
||||
assert code == 2
|
||||
err = capsys.readouterr().err
|
||||
assert str(short_tmpdir.resolve()) in err
|
||||
assert "no Wayland socket" in err
|
||||
|
||||
|
||||
def test_check_reports_the_discovered_compositor(short_tmpdir, sockets, capsys, monkeypatch):
|
||||
monkeypatch.delenv(ENV_COMPOSITOR_RUNTIME_DIR, raising=False)
|
||||
runtime = short_tmpdir / "comp"
|
||||
runtime.mkdir()
|
||||
sockets(runtime, "wayland-1")
|
||||
code = main(
|
||||
[
|
||||
"--check",
|
||||
"--state-dir",
|
||||
str(short_tmpdir / "state"),
|
||||
"--runtime-dir",
|
||||
str(short_tmpdir / "runtime"),
|
||||
"--config",
|
||||
str(short_tmpdir / "missing.toml"),
|
||||
"--compositor-runtime-dir",
|
||||
str(runtime),
|
||||
]
|
||||
)
|
||||
assert code == 0
|
||||
out = capsys.readouterr().out
|
||||
assert f"compositor: {runtime.resolve()}" in out
|
||||
assert "WAYLAND_DISPLAY=wayland-1" in out
|
||||
|
||||
|
||||
def test_check_says_so_when_no_compositor_is_configured(short_tmpdir, capsys, monkeypatch):
|
||||
monkeypatch.delenv(ENV_COMPOSITOR_RUNTIME_DIR, raising=False)
|
||||
code = main(
|
||||
[
|
||||
"--check",
|
||||
"--state-dir",
|
||||
str(short_tmpdir / "state"),
|
||||
"--runtime-dir",
|
||||
str(short_tmpdir / "runtime"),
|
||||
"--config",
|
||||
str(short_tmpdir / "missing.toml"),
|
||||
]
|
||||
)
|
||||
assert code == 0
|
||||
assert "compositor: none configured" in capsys.readouterr().out
|
||||
@@ -0,0 +1,104 @@
|
||||
"""The exit-code table of DESIGN.md §1.6.
|
||||
|
||||
These are frozen: agents branch on them. The test states the table in full so
|
||||
a change to it is a change to this file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstream_session.client import ClientError, reply_exit_code
|
||||
from hhstreamd.protocol import EXIT_CODE_FOR_ERROR, ExitCode, exit_code_for
|
||||
|
||||
|
||||
def test_the_frozen_numbers():
|
||||
assert ExitCode.OK == 0
|
||||
assert ExitCode.USAGE == 2
|
||||
assert ExitCode.NO_SUCH_SESSION == 3
|
||||
assert ExitCode.BAD_STATE == 4
|
||||
assert ExitCode.DAEMON_UNREACHABLE == 5
|
||||
assert ExitCode.POLICY == 6
|
||||
assert ExitCode.TIMEOUT == 7
|
||||
assert ExitCode.BUSY == 8
|
||||
# 1 is deliberately absent: it is the shell's "something went wrong", and
|
||||
# reusing it would make an unhandled crash indistinguishable from a
|
||||
# documented outcome.
|
||||
assert 1 not in set(ExitCode)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error,code",
|
||||
[
|
||||
# 2 — usage
|
||||
("bad_request", 2),
|
||||
("unknown_op", 2),
|
||||
("unsupported_version", 2),
|
||||
("message_too_large", 2),
|
||||
("invalid_argument", 2),
|
||||
# 3 — no such session
|
||||
("no_such_session", 3),
|
||||
("no_such_process", 3),
|
||||
# 4 — not in a usable state
|
||||
("session_exited", 4),
|
||||
("session_killed", 4),
|
||||
("session_reaped", 4),
|
||||
("session_starting", 4),
|
||||
("compositor_lost", 4),
|
||||
("bad_state", 4),
|
||||
("pid_reuse_detected", 4),
|
||||
("identity_unknown", 4),
|
||||
# 5 — daemon unreachable
|
||||
("daemon_unreachable", 5),
|
||||
# 6 — refused by policy
|
||||
("not_allowlisted", 6),
|
||||
("argument_refused", 6),
|
||||
("session_cap_reached", 6),
|
||||
("refused", 6),
|
||||
# 7 — timed out
|
||||
("timeout", 7),
|
||||
("readiness_timeout", 7),
|
||||
# 8 — busy
|
||||
("busy", 8),
|
||||
("already_managed", 8),
|
||||
],
|
||||
)
|
||||
def test_every_error_name_maps_to_its_documented_code(error, code):
|
||||
assert exit_code_for(error) == code
|
||||
|
||||
|
||||
def test_the_table_has_no_entries_this_test_does_not_know_about():
|
||||
"""Adding an error name must mean adding it to the test above."""
|
||||
|
||||
documented = {
|
||||
"bad_request", "unknown_op", "unsupported_version", "message_too_large",
|
||||
"invalid_argument", "no_such_session", "no_such_process", "session_exited",
|
||||
"session_killed", "session_reaped", "session_starting", "compositor_lost",
|
||||
"bad_state", "pid_reuse_detected", "identity_unknown",
|
||||
"daemon_unreachable", "not_allowlisted",
|
||||
"argument_refused", "session_cap_reached", "refused", "timeout",
|
||||
"readiness_timeout", "busy", "already_managed",
|
||||
}
|
||||
assert set(EXIT_CODE_FOR_ERROR) == documented
|
||||
|
||||
|
||||
def test_success_is_zero():
|
||||
assert exit_code_for(None) == 0
|
||||
assert exit_code_for("") == 0
|
||||
|
||||
|
||||
def test_an_unknown_error_degrades_to_not_usable_rather_than_to_success():
|
||||
"""A caller that does not recognise the failure must still not see a 0."""
|
||||
|
||||
assert exit_code_for("something_invented_next_year") == ExitCode.BAD_STATE
|
||||
|
||||
|
||||
def test_reply_exit_code_reads_a_decoded_reply():
|
||||
assert reply_exit_code({"ok": True, "id": "a"}) == 0
|
||||
assert reply_exit_code({"ok": False, "error": "no_such_session"}) == 3
|
||||
assert reply_exit_code({"ok": False}) == ExitCode.BAD_STATE
|
||||
|
||||
|
||||
def test_client_errors_carry_their_own_code():
|
||||
assert ClientError("daemon_unreachable", "no socket").exit_code == 5
|
||||
assert ClientError("timeout", "no reply").exit_code == 7
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Allowlist and input-bound tests (DESIGN.md §8 item 1).
|
||||
|
||||
The allowlist is the main control: without it, `start /bin/sh` makes every
|
||||
other control decorative.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd.policy import (
|
||||
MAX_ARG_BYTES,
|
||||
MAX_ARGV_BYTES,
|
||||
MAX_ARGV_ITEMS,
|
||||
Policy,
|
||||
PolicyError,
|
||||
check_app_name,
|
||||
check_argv,
|
||||
load_policy,
|
||||
policy_from_dict,
|
||||
)
|
||||
|
||||
CONFIG = """
|
||||
[defaults]
|
||||
max_sessions = 2
|
||||
idle_timeout_s = 10800
|
||||
max_idle_timeout_s = 86400
|
||||
|
||||
[apps.chromium]
|
||||
exec = "/run/current-system/sw/bin/chromium"
|
||||
args_allow = ["--new-window", "--app=*", "--user-data-dir=*"]
|
||||
|
||||
[apps.foot]
|
||||
exec = "/usr/bin/foot"
|
||||
|
||||
[apps.blender]
|
||||
exec = "/usr/bin/blender"
|
||||
args = ["--background"]
|
||||
args_allow = ["*.blend"]
|
||||
idle_timeout_s = 60
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def policy() -> Policy:
|
||||
return policy_from_dict(tomllib.loads(CONFIG), source="test-config")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the allowlist itself
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_an_allowlisted_app_resolves_to_its_absolute_path(policy: Policy):
|
||||
rule, argv = policy.resolve("chromium", ["--new-window"])
|
||||
assert rule.name == "chromium"
|
||||
assert argv == ["/run/current-system/sw/bin/chromium", "--new-window"]
|
||||
|
||||
|
||||
def test_an_app_that_is_not_in_the_allowlist_is_refused_with_a_policy_error(policy: Policy):
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
policy.resolve("sh", [])
|
||||
assert exc.value.error == "not_allowlisted"
|
||||
assert "sh" in exc.value.reason
|
||||
assert "blender, chromium, foot" in exc.value.hint
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["/bin/sh", "./sh", "../../bin/sh", "sh;rm -rf /", "a b"])
|
||||
def test_a_path_or_a_shell_fragment_is_not_even_a_valid_app_name(policy: Policy, name: str):
|
||||
"""The caller names an app; it never names a binary."""
|
||||
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
policy.resolve(name, [])
|
||||
assert exc.value.error == "invalid_argument"
|
||||
|
||||
|
||||
def test_an_empty_allowlist_refuses_everything_and_says_so():
|
||||
empty = Policy(source="/etc/hhstream/config.toml")
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
empty.resolve("foot", [])
|
||||
assert exc.value.error == "not_allowlisted"
|
||||
assert "the allowlist is empty" in exc.value.hint
|
||||
|
||||
|
||||
def test_fixed_args_from_the_config_precede_the_callers(policy: Policy):
|
||||
_, argv = policy.resolve("blender", ["scene.blend"])
|
||||
assert argv == ["/usr/bin/blender", "--background", "scene.blend"]
|
||||
|
||||
|
||||
def test_an_app_rule_may_set_its_own_default_idle_timeout(policy: Policy):
|
||||
assert policy.apps["blender"].idle_timeout_s == 60
|
||||
assert policy.apps["foot"].idle_timeout_s is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# argument allowlisting
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_arguments_are_matched_against_patterns(policy: Policy):
|
||||
policy.resolve("chromium", ["--app=https://example.com", "--user-data-dir=/tmp/x"])
|
||||
|
||||
|
||||
def test_an_argument_that_matches_no_pattern_is_refused(policy: Policy):
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
policy.resolve("chromium", ["--no-sandbox"])
|
||||
assert exc.value.error == "argument_refused"
|
||||
assert "--no-sandbox" in exc.value.reason
|
||||
|
||||
|
||||
def test_an_app_with_no_args_allow_accepts_no_caller_arguments(policy: Policy):
|
||||
policy.resolve("foot", []) # fine
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
policy.resolve("foot", ["-e", "sh"])
|
||||
assert exc.value.error == "argument_refused"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# config validation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_relative_exec_path_is_rejected_at_load_time():
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
policy_from_dict({"apps": {"foot": {"exec": "foot"}}})
|
||||
assert "absolute path" in exc.value.reason
|
||||
|
||||
|
||||
def test_an_app_with_no_exec_is_rejected():
|
||||
with pytest.raises(PolicyError):
|
||||
policy_from_dict({"apps": {"foot": {}}})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["args", "args_allow"])
|
||||
def test_args_fields_must_be_lists_of_strings(field):
|
||||
with pytest.raises(PolicyError):
|
||||
policy_from_dict({"apps": {"foot": {"exec": "/usr/bin/foot", field: "oops"}}})
|
||||
|
||||
|
||||
def test_a_missing_config_file_yields_an_empty_allowlist_rather_than_a_crash(tmp_path: Path):
|
||||
"""A misconfigured deployment must not look like a daemon crash."""
|
||||
|
||||
policy = load_policy(tmp_path / "absent.toml")
|
||||
assert policy.apps == {}
|
||||
assert policy.source.endswith("absent.toml")
|
||||
|
||||
|
||||
def test_a_config_file_is_read_from_disk(tmp_path: Path):
|
||||
path = tmp_path / "config.toml"
|
||||
path.write_text(CONFIG)
|
||||
policy = load_policy(path)
|
||||
assert set(policy.apps) == {"chromium", "foot", "blender"}
|
||||
assert policy.max_sessions == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# input bounds on `start`
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_argv_must_be_a_list_not_a_string():
|
||||
"""A string here would be the beginning of a shell command line."""
|
||||
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
check_argv("--new-window https://example.com")
|
||||
assert exc.value.error == "invalid_argument"
|
||||
|
||||
|
||||
def test_argv_items_must_be_strings():
|
||||
with pytest.raises(PolicyError):
|
||||
check_argv(["--a", 7])
|
||||
|
||||
|
||||
def test_argv_length_is_bounded():
|
||||
check_argv(["x"] * MAX_ARGV_ITEMS)
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
check_argv(["x"] * (MAX_ARGV_ITEMS + 1))
|
||||
assert "more than" in exc.value.reason
|
||||
|
||||
|
||||
def test_a_single_argument_is_bounded():
|
||||
with pytest.raises(PolicyError):
|
||||
check_argv(["x" * (MAX_ARG_BYTES + 1)])
|
||||
|
||||
|
||||
def test_the_total_argv_size_is_bounded():
|
||||
item = "x" * (MAX_ARG_BYTES - 1)
|
||||
count = MAX_ARGV_BYTES // len(item) + 2
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
check_argv([item] * count)
|
||||
assert "in total" in exc.value.reason
|
||||
|
||||
|
||||
def test_a_nul_byte_in_an_argument_is_refused():
|
||||
"""execve would truncate at the NUL; refusing is the honest answer."""
|
||||
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
check_argv(["--url=http://x\0--no-sandbox"])
|
||||
assert "NUL" in exc.value.reason
|
||||
|
||||
|
||||
def test_app_names_are_bounded_and_charset_checked():
|
||||
check_app_name("chromium")
|
||||
check_app_name("my-app_2.0+x")
|
||||
with pytest.raises(PolicyError):
|
||||
check_app_name("")
|
||||
with pytest.raises(PolicyError):
|
||||
check_app_name("a" * 65)
|
||||
with pytest.raises(PolicyError):
|
||||
check_app_name(None)
|
||||
|
||||
|
||||
def test_an_idle_timeout_above_the_configured_maximum_is_refused(policy: Policy):
|
||||
assert policy.check_idle_timeout(None) == 10800.0
|
||||
assert policy.check_idle_timeout(60) == 60.0
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
policy.check_idle_timeout(86401)
|
||||
assert exc.value.error == "refused"
|
||||
|
||||
|
||||
def test_a_negative_or_non_numeric_idle_timeout_is_refused(policy: Policy):
|
||||
with pytest.raises(PolicyError):
|
||||
policy.check_idle_timeout(-1)
|
||||
with pytest.raises(PolicyError):
|
||||
policy.check_idle_timeout("soon")
|
||||
|
||||
|
||||
def test_a_zero_idle_timeout_is_accepted_and_means_never_expire(policy: Policy):
|
||||
assert policy.check_idle_timeout(0) == 0.0
|
||||
|
||||
|
||||
def test_the_session_cap_is_enforced(policy: Policy):
|
||||
policy.check_capacity(1)
|
||||
with pytest.raises(PolicyError) as exc:
|
||||
policy.check_capacity(2)
|
||||
assert exc.value.error == "session_cap_reached"
|
||||
assert "max_sessions is 2" in exc.value.reason
|
||||
@@ -0,0 +1,383 @@
|
||||
"""`/proc` parsing and the safety guards on signalling.
|
||||
|
||||
The identity check is what makes it safe to signal a pid the daemon did not
|
||||
spawn, so it gets tests against a synthetic `/proc` as well as the real one.
|
||||
|
||||
BUG-02 removed one of its three conditions, so these tests have two jobs rather
|
||||
than one: they pin down that an `exec`ing wrapper no longer trips the gate, and
|
||||
they pin down — in the same file, from the same synthetic `/proc` — that a
|
||||
genuinely recycled pid is still refused. Dropping a condition without the
|
||||
second half would leave a check that cannot fail, which is worse than the bug.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd import procmon
|
||||
|
||||
|
||||
def fake_proc(root: Path, pid: int, *, comm: str, sid: int, pgid: int, starttime: int, cmdline: bytes):
|
||||
"""Write a plausible `/proc/<pid>` for the parser to read."""
|
||||
|
||||
directory = root / str(pid)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
fields = ["0"] * 50
|
||||
fields[0] = "S" # field 3: state
|
||||
fields[1] = "1" # field 4: ppid
|
||||
fields[2] = str(pgid) # field 5
|
||||
fields[3] = str(sid) # field 6
|
||||
fields[19] = str(starttime) # field 22
|
||||
(directory / "stat").write_text(f"{pid} ({comm}) " + " ".join(fields) + "\n")
|
||||
(directory / "cmdline").write_bytes(cmdline)
|
||||
return directory
|
||||
|
||||
|
||||
def test_stat_parsing_survives_a_comm_containing_spaces_and_parentheses(tmp_path: Path):
|
||||
"""`comm` is attacker-adjacent: a process can rename itself to ") 1 2 3 (".
|
||||
|
||||
Splitting the whole line on whitespace would read the wrong fields and the
|
||||
daemon would then signal the wrong process group.
|
||||
"""
|
||||
|
||||
fake_proc(
|
||||
tmp_path,
|
||||
42,
|
||||
comm="evil (name) with ) spaces",
|
||||
sid=7,
|
||||
pgid=9,
|
||||
starttime=12345,
|
||||
cmdline=b"/bin/x\0",
|
||||
)
|
||||
stat = procmon.read_stat(42, proc=str(tmp_path))
|
||||
assert stat.comm == "evil (name) with ) spaces"
|
||||
assert stat.pgid == 9
|
||||
assert stat.sid == 7
|
||||
assert stat.starttime == 12345
|
||||
|
||||
|
||||
def test_a_missing_process_reads_as_none(tmp_path: Path):
|
||||
assert procmon.read_stat(999, proc=str(tmp_path)) is None
|
||||
assert procmon.read_cmdline(999, proc=str(tmp_path)) is None
|
||||
assert procmon.identity(999, proc=str(tmp_path)) is None
|
||||
assert procmon.is_alive(999, proc=str(tmp_path)) is False
|
||||
|
||||
|
||||
def test_a_truncated_stat_line_is_rejected_rather_than_misparsed(tmp_path: Path):
|
||||
directory = tmp_path / "7"
|
||||
directory.mkdir()
|
||||
(directory / "stat").write_text("7 (short) S 1 2\n")
|
||||
assert procmon.read_stat(7, proc=str(tmp_path)) is None
|
||||
|
||||
|
||||
def test_cmdline_is_split_on_nul_without_a_trailing_empty_item(tmp_path: Path):
|
||||
fake_proc(tmp_path, 8, comm="x", sid=8, pgid=8, starttime=1, cmdline=b"/bin/x\0-a\0-b\0")
|
||||
assert procmon.cmdline_argv(8, proc=str(tmp_path)) == ["/bin/x", "-a", "-b"]
|
||||
|
||||
|
||||
def test_the_cmdline_hash_is_of_the_raw_bytes(tmp_path: Path):
|
||||
raw = b"/bin/x\0-a\0"
|
||||
fake_proc(tmp_path, 9, comm="x", sid=9, pgid=9, starttime=1, cmdline=raw)
|
||||
assert procmon.cmdline_hash(9, proc=str(tmp_path)) == hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the identity check (BUG-02)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def leader(root: Path, pid: int, *, starttime: int, cmdline: bytes, comm: str = "x"):
|
||||
"""A session leader, as `start_new_session=True` produces: sid == pgid == pid."""
|
||||
|
||||
return fake_proc(
|
||||
root, pid, comm=comm, sid=pid, pgid=pid, starttime=starttime, cmdline=cmdline
|
||||
)
|
||||
|
||||
|
||||
def test_the_gate_is_starttime_corroborated_by_a_leaders_sid_and_pgid(tmp_path: Path):
|
||||
"""What is checked is stated explicitly, so weakening it cannot be silent."""
|
||||
|
||||
raw = b"/bin/x\0"
|
||||
leader(tmp_path, 10, starttime=999, cmdline=raw)
|
||||
verdict = procmon.check(
|
||||
10,
|
||||
proc=str(tmp_path),
|
||||
starttime=999,
|
||||
sid=10,
|
||||
pgid=10,
|
||||
cmdline_sha256=hashlib.sha256(raw).hexdigest(),
|
||||
)
|
||||
assert verdict.ok is True
|
||||
assert verdict.reason is None
|
||||
assert verdict.checked == ("starttime", "sid", "pgid")
|
||||
assert verdict.mismatched == ()
|
||||
assert verdict.cmdline_drifted is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"live,mismatched",
|
||||
[
|
||||
# A different process was created on this pid: it cannot share the
|
||||
# creation instant of the one that is recorded.
|
||||
(dict(sid=10, pgid=10, starttime=1000), "starttime"),
|
||||
# ...and if the clocks did collide, it is not in our session either.
|
||||
(dict(sid=77, pgid=77, starttime=999), "sid"),
|
||||
(dict(sid=10, pgid=77, starttime=999), "pgid"),
|
||||
],
|
||||
)
|
||||
def test_a_recycled_pid_is_still_refused(tmp_path: Path, live: dict, mismatched: str):
|
||||
"""The protection BUG-02 had to keep: a pid that is not ours is not signalled.
|
||||
|
||||
The brief's construction: a pid cannot be forced to be recycled on demand,
|
||||
so the record is held fixed — a session leader on pid 10, created at tick
|
||||
999 — and `/proc` is made to describe a process that **cannot** be that one
|
||||
while it is alive. Each surviving condition is shown to refuse on its own.
|
||||
"""
|
||||
|
||||
fake_proc(tmp_path, 10, comm="stranger", cmdline=b"/bin/other\0", **live)
|
||||
verdict = procmon.check(10, proc=str(tmp_path), starttime=999, sid=10, pgid=10)
|
||||
assert verdict.ok is False, "a pid that is not ours must never be signalled"
|
||||
assert verdict.reason == "pid_reuse_detected"
|
||||
assert verdict.unresolved is True
|
||||
assert mismatched in verdict.mismatched
|
||||
|
||||
|
||||
def test_the_gate_cannot_be_satisfied_by_the_cmdline_alone(tmp_path: Path):
|
||||
"""A recycled pid is refused *even when the command line matches exactly*.
|
||||
|
||||
The converse of dropping the condition: it was never what made the check
|
||||
safe, and removing it takes nothing away.
|
||||
"""
|
||||
|
||||
raw = b"/bin/x\0"
|
||||
fake_proc(tmp_path, 10, comm="x", sid=10, pgid=10, starttime=1000, cmdline=raw)
|
||||
verdict = procmon.check(
|
||||
10, proc=str(tmp_path), starttime=999, sid=10, pgid=10,
|
||||
cmdline_sha256=hashlib.sha256(raw).hexdigest(),
|
||||
)
|
||||
assert verdict.ok is False
|
||||
assert verdict.reason == "pid_reuse_detected"
|
||||
assert verdict.cmdline_drifted is False, "identical argv, and still refused"
|
||||
|
||||
|
||||
def test_a_wrapper_script_exec_does_not_look_like_pid_reuse(tmp_path: Path):
|
||||
"""BUG-02 itself, at the level of the check.
|
||||
|
||||
The recorded argv is the wrapper's, the live argv is the real binary's, and
|
||||
everything the kernel owns is unchanged. This is a healthy process.
|
||||
"""
|
||||
|
||||
launched = b"/run/current-system/sw/bin/chromium\0--ozone-platform=wayland\0"
|
||||
live = b"/nix/store/abc-chromium-unwrapped/libexec/chromium/chromium\0"
|
||||
leader(tmp_path, 2661433, starttime=15780209, cmdline=live, comm="chromium")
|
||||
|
||||
verdict = procmon.check(
|
||||
2661433,
|
||||
proc=str(tmp_path),
|
||||
starttime=15780209,
|
||||
sid=2661433,
|
||||
pgid=2661433,
|
||||
cmdline_sha256=hashlib.sha256(launched).hexdigest(),
|
||||
)
|
||||
assert verdict.ok is True, "an exec'ing wrapper is not evidence of pid reuse"
|
||||
assert verdict.cmdline_drifted is True, "the drift is still reported, just not acted on"
|
||||
|
||||
|
||||
def test_the_cmdline_can_never_refuse_on_its_own(tmp_path: Path):
|
||||
"""The condition that was dropped is dropped: no value of it refuses."""
|
||||
|
||||
raw = b"/bin/real\0"
|
||||
leader(tmp_path, 10, starttime=999, cmdline=raw)
|
||||
for recorded_hash in ["0" * 64, hashlib.sha256(b"/bin/wrapper\0").hexdigest(), ""]:
|
||||
verdict = procmon.check(
|
||||
10, proc=str(tmp_path), starttime=999, sid=10, pgid=10,
|
||||
cmdline_sha256=recorded_hash,
|
||||
)
|
||||
assert verdict.ok is True
|
||||
assert "cmdline_sha256" not in verdict.checked
|
||||
|
||||
|
||||
def test_sid_and_pgid_are_only_checked_for_a_leader(tmp_path: Path):
|
||||
"""An adopted non-leader may lawfully `setsid()`; that is not pid reuse.
|
||||
|
||||
`setsid()` and `setpgid()` both fail with EPERM for a session/group leader,
|
||||
so the recorded values are immutable exactly when they equal the recorded
|
||||
pid — and are checked exactly then.
|
||||
"""
|
||||
|
||||
# Recorded as a member of someone else's session, then it calls setsid().
|
||||
fake_proc(tmp_path, 10, comm="x", sid=5, pgid=5, starttime=999, cmdline=b"/bin/x\0")
|
||||
verdict = procmon.check(10, proc=str(tmp_path), starttime=999, sid=5, pgid=5)
|
||||
assert verdict.ok is True
|
||||
assert verdict.checked == ("starttime",), "a non-leader's sid/pgid are not evidence"
|
||||
|
||||
|
||||
def test_a_record_with_no_starttime_is_refused_rather_than_waved_through(tmp_path: Path):
|
||||
"""BUG-02 item 5: no evidence means refuse loudly, never "probably fine"."""
|
||||
|
||||
leader(tmp_path, 10, starttime=999, cmdline=b"/bin/x\0")
|
||||
for missing in (None, 0, -1):
|
||||
verdict = procmon.check(10, proc=str(tmp_path), starttime=missing, sid=10, pgid=10)
|
||||
assert verdict.ok is False
|
||||
assert verdict.reason == "identity_unknown"
|
||||
assert verdict.unresolved is True
|
||||
|
||||
|
||||
def test_a_vanished_process_reports_gone_not_pid_reuse(tmp_path: Path):
|
||||
"""The difference matters: one is routine, the other is alarming."""
|
||||
|
||||
verdict = procmon.check(404, proc=str(tmp_path), starttime=1, sid=404, pgid=404)
|
||||
assert (verdict.ok, verdict.reason) == (False, "gone")
|
||||
assert verdict.unresolved is False, "an exit is not something to shout about"
|
||||
|
||||
|
||||
def test_a_zombie_is_gone_not_alive(tmp_path: Path):
|
||||
"""A zombie holds its pid but can never be signalled into doing anything."""
|
||||
|
||||
directory = leader(tmp_path, 10, starttime=999, cmdline=b"/bin/x\0")
|
||||
stat = (directory / "stat").read_text().replace(") S ", ") Z ", 1)
|
||||
(directory / "stat").write_text(stat)
|
||||
verdict = procmon.check(10, proc=str(tmp_path), starttime=999, sid=10, pgid=10)
|
||||
assert (verdict.ok, verdict.reason) == (False, "gone")
|
||||
|
||||
|
||||
def test_verify_still_answers_ok_and_reason_for_callers_that_want_no_detail(tmp_path: Path):
|
||||
leader(tmp_path, 10, starttime=999, cmdline=b"/bin/x\0")
|
||||
assert procmon.verify(10, proc=str(tmp_path), starttime=999, sid=10, pgid=10) == (True, None)
|
||||
assert procmon.verify(10, proc=str(tmp_path), starttime=998, sid=10, pgid=10) == (
|
||||
False,
|
||||
"pid_reuse_detected",
|
||||
)
|
||||
|
||||
|
||||
def test_the_real_process_verifies_against_itself():
|
||||
me = os.getpid()
|
||||
identity = procmon.identity(me)
|
||||
assert identity is not None
|
||||
assert identity.sid == os.getsid(me)
|
||||
assert identity.pgid == os.getpgid(me)
|
||||
verdict = procmon.check(
|
||||
me,
|
||||
starttime=identity.starttime,
|
||||
sid=identity.sid,
|
||||
pgid=identity.pgid,
|
||||
cmdline_sha256=identity.cmdline_sha256,
|
||||
)
|
||||
assert verdict.ok is True
|
||||
assert "starttime" in verdict.checked
|
||||
|
||||
|
||||
def test_a_real_exec_does_not_change_starttime_but_does_change_the_cmdline():
|
||||
"""The claim the whole fix rests on, measured on a real process.
|
||||
|
||||
A process that `exec`s something else keeps its pid, its session id, its
|
||||
process group and its `starttime`; only its command line is replaced. The
|
||||
handshake over stdin is what makes it deterministic — the child is blocked
|
||||
in `readline()` while the "before" identity is taken, so there is no race
|
||||
with the `exec` and no sleep sized by guesswork. If this ever stops being
|
||||
true, the gate is unsound and this test says so.
|
||||
"""
|
||||
|
||||
child = (
|
||||
"import os, sys\n"
|
||||
"sys.stdout.write(str(os.getpid()) + chr(10)); sys.stdout.flush()\n"
|
||||
"sys.stdin.readline()\n" # held here while the parent looks at us
|
||||
"os.execv(sys.executable, [sys.executable, '-c', 'import time; time.sleep(30)'])\n"
|
||||
)
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-c", child],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
start_new_session=True,
|
||||
)
|
||||
try:
|
||||
pid = int(process.stdout.readline())
|
||||
before = procmon.identity(pid)
|
||||
assert before is not None
|
||||
assert before.sid == before.pgid == pid, "start_new_session gives a leader"
|
||||
|
||||
process.stdin.write(b"go\n")
|
||||
process.stdin.flush()
|
||||
|
||||
deadline = time.monotonic() + 10.0
|
||||
while True:
|
||||
after = procmon.identity(pid)
|
||||
assert after is not None, "the process exec'd into nothing"
|
||||
if after.cmdline_sha256 != before.cmdline_sha256:
|
||||
break
|
||||
assert time.monotonic() < deadline, "the exec never happened"
|
||||
time.sleep(0.01)
|
||||
|
||||
assert after.starttime == before.starttime, "starttime must survive exec"
|
||||
assert after.sid == before.sid == pid, "the session id must survive exec"
|
||||
assert after.pgid == before.pgid == pid, "the process group must survive exec"
|
||||
|
||||
# And the gate agrees: the identity recorded before the exec still
|
||||
# verifies afterwards, with the drift reported but not acted on.
|
||||
verdict = procmon.check(
|
||||
pid,
|
||||
starttime=before.starttime,
|
||||
sid=before.sid,
|
||||
pgid=before.pgid,
|
||||
cmdline_sha256=before.cmdline_sha256,
|
||||
)
|
||||
assert verdict.ok is True
|
||||
assert verdict.cmdline_drifted is True
|
||||
finally:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# signalling guards
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sid", [0, 1, -1, None])
|
||||
def test_the_sweep_refuses_session_ids_that_would_select_the_machine(sid):
|
||||
"""sid 0 or 1 would match init and most of everything else."""
|
||||
|
||||
assert procmon.session_members(sid) == []
|
||||
assert procmon.sweep_session(sid) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pgid", [0, 1, -1, None])
|
||||
def test_killpg_refuses_the_dangerous_process_groups(pgid):
|
||||
"""killpg(0) means "every process in my own group" — including the daemon."""
|
||||
|
||||
assert procmon.killpg(pgid, signal.SIGTERM) is False
|
||||
|
||||
|
||||
def test_the_sweep_finds_processes_by_session_id(tmp_path: Path):
|
||||
for pid, sid in [(100, 55), (101, 55), (102, 66)]:
|
||||
fake_proc(tmp_path, pid, comm="x", sid=sid, pgid=pid, starttime=1, cmdline=b"/bin/x\0")
|
||||
assert procmon.session_members(55, proc=str(tmp_path)) == [100, 101]
|
||||
assert procmon.session_members(66, proc=str(tmp_path)) == [102]
|
||||
assert procmon.session_members(55, proc=str(tmp_path), exclude={100}) == [101]
|
||||
|
||||
|
||||
def test_signalling_a_dead_pid_is_not_an_error():
|
||||
assert procmon.kill_pid(2**22 - 1, signal.SIGKILL) in (False, True)
|
||||
|
||||
|
||||
def test_pidfd_open_yields_none_rather_than_raising_when_it_cannot_be_used():
|
||||
"""The caller falls back to a /proc poll on None, so it must never raise.
|
||||
|
||||
This covers both reasons for None: the kernel lacking the syscall, and the
|
||||
process being gone between the liveness check and the open.
|
||||
"""
|
||||
|
||||
assert procmon.pidfd_open(2**22 - 1) is None
|
||||
fd = procmon.pidfd_open(os.getpid())
|
||||
if fd is None:
|
||||
assert not procmon.HAVE_PIDFD
|
||||
else:
|
||||
os.close(fd)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Protocol framing tests (DESIGN.md §3.4)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd import protocol
|
||||
from hhstreamd.protocol import MAX_LINE_BYTES, PROTOCOL_VERSION, ProtocolError
|
||||
|
||||
|
||||
def test_a_message_is_exactly_one_newline_terminated_line():
|
||||
frame = protocol.encode({"ok": True, "id": "foot-aaaaaa"})
|
||||
assert frame.endswith(b"\n")
|
||||
assert frame.count(b"\n") == 1
|
||||
assert json.loads(frame) == {"ok": True, "id": "foot-aaaaaa"}
|
||||
|
||||
|
||||
def test_round_trip():
|
||||
message = {"v": 1, "op": "start", "app": "foot", "argv": ["--a", "--b"]}
|
||||
assert protocol.decode(protocol.encode(message)) == message
|
||||
|
||||
|
||||
def test_embedded_newlines_cannot_break_the_framing():
|
||||
"""A session id or an argv element must never be able to split a frame."""
|
||||
|
||||
message = {"ok": False, "reason": "line one\nline two\r\nline three"}
|
||||
frame = protocol.encode(message)
|
||||
assert frame.count(b"\n") == 1
|
||||
assert protocol.decode(frame) == message
|
||||
|
||||
|
||||
def test_non_ascii_is_escaped_so_the_frame_stays_ascii():
|
||||
frame = protocol.encode({"reason": "café — ✓"})
|
||||
frame.decode("ascii") # must not raise
|
||||
assert protocol.decode(frame)["reason"] == "café — ✓"
|
||||
|
||||
|
||||
def test_decode_tolerates_a_missing_trailing_newline():
|
||||
assert protocol.decode(b'{"ok":true}') == {"ok": True}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("line", [b"", b"\n", b" \n"])
|
||||
def test_an_empty_frame_is_a_bad_request(line):
|
||||
with pytest.raises(ProtocolError) as exc:
|
||||
protocol.decode(line)
|
||||
assert exc.value.error == "bad_request"
|
||||
|
||||
|
||||
def test_malformed_json_is_a_bad_request():
|
||||
with pytest.raises(ProtocolError) as exc:
|
||||
protocol.decode(b"{not json\n")
|
||||
assert exc.value.error == "bad_request"
|
||||
assert "malformed JSON" in exc.value.reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [b"[1,2,3]", b'"a string"', b"42", b"null"])
|
||||
def test_a_frame_that_is_not_an_object_is_rejected(payload):
|
||||
with pytest.raises(ProtocolError) as exc:
|
||||
protocol.decode(payload)
|
||||
assert exc.value.error == "bad_request"
|
||||
|
||||
|
||||
def test_an_oversized_frame_is_refused_on_both_sides():
|
||||
with pytest.raises(ProtocolError) as exc:
|
||||
protocol.decode(b"x" * (MAX_LINE_BYTES + 1))
|
||||
assert exc.value.error == "message_too_large"
|
||||
|
||||
with pytest.raises(ProtocolError) as exc:
|
||||
protocol.encode({"argv": ["x" * MAX_LINE_BYTES]})
|
||||
assert exc.value.error == "message_too_large"
|
||||
|
||||
|
||||
def test_decode_request_requires_an_op():
|
||||
with pytest.raises(ProtocolError) as exc:
|
||||
protocol.decode_request(b'{"v":1}')
|
||||
assert exc.value.error == "bad_request"
|
||||
assert "no 'op'" in exc.value.reason
|
||||
|
||||
|
||||
def test_decode_request_rejects_an_unknown_protocol_version():
|
||||
with pytest.raises(ProtocolError) as exc:
|
||||
protocol.decode_request(b'{"v":99,"op":"list"}')
|
||||
assert exc.value.error == "unsupported_version"
|
||||
|
||||
|
||||
def test_a_request_without_a_version_is_assumed_to_be_current():
|
||||
assert protocol.decode_request(b'{"op":"list"}')["op"] == "list"
|
||||
|
||||
|
||||
def test_request_attaches_the_version_and_drops_unset_fields():
|
||||
message = protocol.request("start", app="foot", argv=None, idle_timeout_s=30.0)
|
||||
assert message == {"v": PROTOCOL_VERSION, "op": "start", "app": "foot", "idle_timeout_s": 30.0}
|
||||
|
||||
|
||||
def test_error_replies_carry_both_a_machine_field_and_a_human_field():
|
||||
reply = protocol.error(
|
||||
"not_allowlisted", "app 'sh' is not in the allowlist", hint="see the config"
|
||||
)
|
||||
assert reply == {
|
||||
"ok": False,
|
||||
"error": "not_allowlisted",
|
||||
"reason": "app 'sh' is not in the allowlist",
|
||||
"hint": "see the config",
|
||||
}
|
||||
|
||||
|
||||
def test_ok_replies_are_flagged():
|
||||
assert protocol.ok(id="a")["ok"] is True
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Reaper unit tests — injected clock, no processes, no sleeping.
|
||||
|
||||
DESIGN.md §6.5 layer 1: "tests pass a fake clock and assert which session is
|
||||
selected and when". This is where nearly all of the reaping logic is covered.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
|
||||
from hhstreamd.clock import ManualClock
|
||||
from hhstreamd.reaper import Reaper, deadlines, next_deadline, select_expired, sleep_for
|
||||
from hhstreamd.registry import State
|
||||
|
||||
|
||||
class FakeSession:
|
||||
"""The minimum the reaper needs: an id, liveness and a deadline."""
|
||||
|
||||
def __init__(self, sid: str, last_activity: float, timeout: float, state: str = State.READY):
|
||||
self.id = sid
|
||||
self.last_activity_boottime = last_activity
|
||||
self.idle_timeout_s = timeout
|
||||
self.state = state
|
||||
|
||||
@property
|
||||
def live(self) -> bool:
|
||||
return self.state not in {State.EXITED, State.KILLED, State.REAPED}
|
||||
|
||||
def deadline(self):
|
||||
if not self.live or not self.idle_timeout_s:
|
||||
return None
|
||||
return self.last_activity_boottime + self.idle_timeout_s
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# selection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_empty_set_has_no_deadline_and_sleeps_indefinitely():
|
||||
assert deadlines([]) == {}
|
||||
assert next_deadline([]) is None
|
||||
assert select_expired([], now=10_000.0) == []
|
||||
# None means "sleep until woken" — zero wakeups on a quiet server.
|
||||
assert sleep_for([], now=10_000.0) is None
|
||||
|
||||
|
||||
def test_next_deadline_is_the_earliest_across_sessions():
|
||||
sessions = [
|
||||
FakeSession("a", last_activity=1000.0, timeout=10800.0), # 11800
|
||||
FakeSession("b", last_activity=5000.0, timeout=60.0), # 5060 <- earliest
|
||||
FakeSession("c", last_activity=2000.0, timeout=3600.0), # 5600
|
||||
]
|
||||
assert next_deadline(sessions) == 5060.0
|
||||
assert sleep_for(sessions, now=5000.0) == 60.0
|
||||
|
||||
|
||||
def test_select_expired_returns_only_the_passed_deadlines_oldest_first():
|
||||
sessions = [
|
||||
FakeSession("late", last_activity=100.0, timeout=10.0), # 110
|
||||
FakeSession("later", last_activity=100.0, timeout=5.0), # 105
|
||||
FakeSession("future", last_activity=100.0, timeout=1000.0), # 1100
|
||||
]
|
||||
assert select_expired(sessions, now=120.0) == ["later", "late"]
|
||||
assert select_expired(sessions, now=104.0) == []
|
||||
|
||||
|
||||
def test_deadline_is_inclusive_so_an_exactly_due_session_is_reaped():
|
||||
session = FakeSession("a", last_activity=100.0, timeout=10.0)
|
||||
assert select_expired([session], now=110.0) == ["a"]
|
||||
assert sleep_for([session], now=110.0) == 0.0
|
||||
|
||||
|
||||
def test_a_terminal_session_has_no_deadline():
|
||||
for state in (State.EXITED, State.KILLED, State.REAPED):
|
||||
session = FakeSession("a", last_activity=0.0, timeout=1.0, state=state)
|
||||
assert session.deadline() is None
|
||||
assert select_expired([session], now=1e9) == []
|
||||
|
||||
|
||||
def test_a_zero_timeout_disables_expiry_rather_than_expiring_immediately():
|
||||
session = FakeSession("a", last_activity=0.0, timeout=0.0)
|
||||
assert next_deadline([session]) is None
|
||||
assert select_expired([session], now=1e9) == []
|
||||
|
||||
|
||||
def test_sleep_for_never_goes_negative():
|
||||
session = FakeSession("a", last_activity=0.0, timeout=10.0)
|
||||
assert sleep_for([session], now=1_000_000.0) == 0.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the Reaper object, with the clock injected at construction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def make_reaper(clock: ManualClock, sessions: list[FakeSession]):
|
||||
reaped: list[str] = []
|
||||
|
||||
async def on_expire(session_id: str) -> None:
|
||||
reaped.append(session_id)
|
||||
for session in sessions:
|
||||
if session.id == session_id:
|
||||
session.state = State.REAPED
|
||||
|
||||
return Reaper(now=clock.boottime, sessions=lambda: sessions, on_expire=on_expire), reaped
|
||||
|
||||
|
||||
def test_clock_is_injected_and_nothing_expires_until_it_moves():
|
||||
clock = ManualClock(boottime=1000.0)
|
||||
sessions = [FakeSession("a", last_activity=1000.0, timeout=10800.0)]
|
||||
reaper, reaped = make_reaper(clock, sessions)
|
||||
|
||||
assert reaper.next_deadline() == 11800.0
|
||||
assert reaper.sleep_for() == 10800.0
|
||||
assert reaper.expired() == []
|
||||
|
||||
clock.advance(10799.0)
|
||||
assert reaper.expired() == []
|
||||
clock.advance(1.0) # exactly three hours of idleness
|
||||
assert reaper.expired() == ["a"]
|
||||
assert reaped == [] # selection alone does not tear anything down
|
||||
|
||||
|
||||
def test_tick_reaps_the_expired_and_leaves_the_rest():
|
||||
clock = ManualClock(boottime=0.0)
|
||||
sessions = [
|
||||
FakeSession("doomed", last_activity=0.0, timeout=60.0),
|
||||
FakeSession("safe", last_activity=0.0, timeout=3600.0),
|
||||
]
|
||||
reaper, reaped = make_reaper(clock, sessions)
|
||||
clock.advance(61.0)
|
||||
|
||||
assert asyncio.run(reaper.tick()) == ["doomed"]
|
||||
assert reaped == ["doomed"]
|
||||
assert sessions[1].state == State.READY
|
||||
# The reaped session now has no deadline, so the next one is the survivor's.
|
||||
assert reaper.next_deadline() == 3600.0
|
||||
|
||||
|
||||
def test_adopt_with_an_already_expired_deadline_is_reaped_on_the_first_pass():
|
||||
"""DESIGN.md §2.4 item 6: the arithmetic survives a daemon restart.
|
||||
|
||||
A record adopted at boottime 50000 whose last activity was at 1000 with a
|
||||
one-hour timeout is already 13 hours overdue. It must be selected
|
||||
immediately, not scheduled another hour out.
|
||||
"""
|
||||
|
||||
clock = ManualClock(boottime=50_000.0)
|
||||
sessions = [FakeSession("adopted", last_activity=1000.0, timeout=3600.0)]
|
||||
reaper, reaped = make_reaper(clock, sessions)
|
||||
|
||||
assert reaper.sleep_for() == 0.0
|
||||
assert asyncio.run(reaper.tick()) == ["adopted"]
|
||||
assert reaped == ["adopted"]
|
||||
|
||||
|
||||
def test_a_touch_pushes_the_deadline_out():
|
||||
clock = ManualClock(boottime=0.0)
|
||||
session = FakeSession("a", last_activity=0.0, timeout=100.0)
|
||||
reaper, _ = make_reaper(clock, [session])
|
||||
|
||||
clock.advance(99.0)
|
||||
assert reaper.expired() == []
|
||||
session.last_activity_boottime = clock.boottime() # what `touch` does
|
||||
clock.advance(99.0)
|
||||
assert reaper.expired() == []
|
||||
clock.advance(2.0)
|
||||
assert reaper.expired() == ["a"]
|
||||
|
||||
|
||||
def test_run_reaps_when_the_deadline_arrives_and_then_sleeps_indefinitely():
|
||||
"""Exercise the real asyncio task without waiting for a real timeout."""
|
||||
|
||||
async def scenario():
|
||||
clock = ManualClock(boottime=0.0)
|
||||
sessions = [FakeSession("a", last_activity=0.0, timeout=10_000.0)]
|
||||
reaper, reaped = make_reaper(clock, sessions)
|
||||
task = reaper.start()
|
||||
await asyncio.sleep(0) # let the first pass run
|
||||
assert reaped == []
|
||||
|
||||
clock.advance(10_001.0) # three hours pass in a nanosecond
|
||||
reaper.wake()
|
||||
for _ in range(20):
|
||||
await asyncio.sleep(0)
|
||||
if reaped:
|
||||
break
|
||||
assert reaped == ["a"]
|
||||
# Nothing left to expire: the task is parked, not spinning.
|
||||
assert reaper.sleep_for() is None
|
||||
await reaper.stop()
|
||||
assert task.done()
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_a_failing_teardown_does_not_kill_the_reaper_task():
|
||||
async def scenario():
|
||||
clock = ManualClock(boottime=0.0)
|
||||
sessions = [FakeSession("a", last_activity=0.0, timeout=1.0)]
|
||||
calls = []
|
||||
|
||||
async def on_expire(session_id: str) -> None:
|
||||
calls.append(session_id)
|
||||
raise RuntimeError("teardown exploded")
|
||||
|
||||
reaper = Reaper(now=clock.boottime, sessions=lambda: sessions, on_expire=on_expire)
|
||||
clock.advance(2.0)
|
||||
assert await reaper.tick() == [] # the failure is swallowed and logged
|
||||
assert calls == ["a"]
|
||||
assert reaper.expired() == ["a"] # still expired; it will be retried
|
||||
|
||||
asyncio.run(scenario())
|
||||
@@ -0,0 +1,270 @@
|
||||
"""Registry unit tests: atomic persistence, adoption, tombstones."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstreamd.clock import ManualClock
|
||||
from hhstreamd.registry import (
|
||||
Registry,
|
||||
Session,
|
||||
State,
|
||||
atomic_write_json,
|
||||
mint_id,
|
||||
)
|
||||
|
||||
|
||||
def make_session(sid: str = "foot-aaaaaa", **overrides) -> Session:
|
||||
base = dict(
|
||||
id=sid,
|
||||
app="foot",
|
||||
argv=["/usr/bin/foot"],
|
||||
pid=4242,
|
||||
pgid=4242,
|
||||
sid=4242,
|
||||
pid_starttime=918342,
|
||||
cmdline_sha256="9f2c",
|
||||
home="/home/someone",
|
||||
runtime_dir="/run/hhstream/sessions/" + sid,
|
||||
created_at="2026-10-01T09:14:02Z",
|
||||
created_boottime=1000.0,
|
||||
last_activity_at="2026-10-01T09:14:02Z",
|
||||
last_activity_boottime=1000.0,
|
||||
idle_timeout_s=10800.0,
|
||||
state=State.READY,
|
||||
)
|
||||
base.update(overrides)
|
||||
return Session(**base)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def registry(tmp_path: Path) -> Registry:
|
||||
reg = Registry(tmp_path, ManualClock(boottime=1000.0))
|
||||
reg.ensure_dirs()
|
||||
return reg
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# atomic persistence
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_atomic_write_leaves_no_temporary_files_behind(tmp_path: Path):
|
||||
target = tmp_path / "rec.json"
|
||||
atomic_write_json(target, {"hello": "world"})
|
||||
assert json.loads(target.read_text()) == {"hello": "world"}
|
||||
assert [p.name for p in tmp_path.iterdir()] == ["rec.json"]
|
||||
|
||||
|
||||
def test_a_failed_write_leaves_the_previous_record_intact(tmp_path: Path, monkeypatch):
|
||||
"""The point of tmp + os.replace: a reader never sees a half-written record."""
|
||||
|
||||
target = tmp_path / "rec.json"
|
||||
atomic_write_json(target, {"generation": 1})
|
||||
|
||||
def explode(*args, **kwargs):
|
||||
raise OSError("disk full")
|
||||
|
||||
monkeypatch.setattr(json, "dump", explode)
|
||||
with pytest.raises(OSError):
|
||||
atomic_write_json(target, {"generation": 2})
|
||||
|
||||
assert json.loads(target.read_text()) == {"generation": 1}
|
||||
assert [p.name for p in tmp_path.iterdir()] == ["rec.json"] # temp cleaned up
|
||||
|
||||
|
||||
def test_the_temp_file_is_written_in_the_target_directory(tmp_path: Path, monkeypatch):
|
||||
"""os.replace is only atomic within one filesystem, so the temp must be adjacent."""
|
||||
|
||||
seen: list[str] = []
|
||||
real_replace = os.replace
|
||||
|
||||
def spy(src, dst, *args, **kwargs):
|
||||
seen.append(str(src))
|
||||
return real_replace(src, dst, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(os, "replace", spy)
|
||||
target = tmp_path / "deep" / "rec.json"
|
||||
atomic_write_json(target, {"a": 1})
|
||||
assert Path(seen[0]).parent == target.parent
|
||||
|
||||
|
||||
def test_persist_writes_the_record_and_it_round_trips(registry: Registry):
|
||||
session = registry.add(make_session())
|
||||
path = registry.record_path(session.id)
|
||||
assert path.exists()
|
||||
restored = Session.from_dict(json.loads(path.read_text()))
|
||||
assert restored == session
|
||||
|
||||
|
||||
def test_a_mirror_write_failure_never_fails_the_command(registry: Registry, monkeypatch, caplog):
|
||||
session = registry.add(make_session())
|
||||
monkeypatch.setattr(
|
||||
"hhstreamd.registry.atomic_write_json",
|
||||
lambda *a, **k: (_ for _ in ()).throw(OSError("read-only filesystem")),
|
||||
)
|
||||
registry.touch(session, force_flush=True) # must not raise
|
||||
assert session.command_count == 1
|
||||
assert "mirror write failed" in caplog.text
|
||||
|
||||
|
||||
def test_activity_flushes_are_rate_limited_but_transitions_are_not(registry: Registry):
|
||||
clock: ManualClock = registry.clock # type: ignore[assignment]
|
||||
session = registry.add(make_session())
|
||||
|
||||
registry.touch(session) # within the 15 s window: memory only
|
||||
on_disk = Session.from_dict(json.loads(registry.record_path(session.id).read_text()))
|
||||
assert session.command_count == 1
|
||||
assert on_disk.command_count == 0
|
||||
|
||||
clock.advance(16.0)
|
||||
registry.touch(session)
|
||||
on_disk = Session.from_dict(json.loads(registry.record_path(session.id).read_text()))
|
||||
assert on_disk.command_count == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# handles
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_colliding_draw_is_discarded_and_another_taken():
|
||||
"""Handles are never reused: a draw already in the set is refused."""
|
||||
|
||||
class TwoDraws:
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
|
||||
def token_bytes(self, n):
|
||||
self.calls += 1
|
||||
return b"\x00" * n if self.calls == 1 else b"\xff" * n
|
||||
|
||||
rng = TwoDraws()
|
||||
collision = f"foot-{base64.b32encode(b'\x00' * 5).decode().rstrip('=').lower()[:6]}"
|
||||
minted = mint_id("foot", {collision}, rng=rng)
|
||||
assert rng.calls == 2
|
||||
assert minted != collision
|
||||
assert minted.startswith("foot-")
|
||||
|
||||
|
||||
def test_a_tombstoned_id_still_blocks_reuse(registry: Registry):
|
||||
session = registry.add(make_session())
|
||||
registry.terminate(session, State.KILLED)
|
||||
assert session.id in registry.taken_ids()
|
||||
assert registry.new_id("foot") != session.id
|
||||
|
||||
|
||||
def test_the_slug_is_sanitised_but_never_parsed():
|
||||
assert mint_id("Chromium", set()).startswith("chromium-")
|
||||
assert mint_id("/bin/odd name", set()).startswith("bin-odd-name-")
|
||||
assert mint_id("!!!", set()).startswith("app-")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# tombstones
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_terminate_writes_a_tombstone_with_an_expiry(registry: Registry):
|
||||
clock: ManualClock = registry.clock # type: ignore[assignment]
|
||||
session = registry.add(make_session())
|
||||
registry.terminate(session, State.EXITED, exit_code=0, exit_detected_by="sigchld")
|
||||
|
||||
assert not session.live
|
||||
assert session.exit_code == 0
|
||||
assert session.tombstoned_boottime == clock.boottime()
|
||||
assert session.tombstone_expires() == clock.boottime() + 3600.0
|
||||
assert session.deadline() is None # a tombstone can never be idle-reaped
|
||||
assert registry.tombstones() == [session]
|
||||
assert registry.live() == []
|
||||
|
||||
|
||||
def test_an_adopted_exit_records_no_exit_code_rather_than_inventing_a_zero(registry: Registry):
|
||||
session = registry.add(make_session(adopted=True))
|
||||
registry.terminate(session, State.EXITED, exit_detected_by="pidfd")
|
||||
assert session.exit_code is None
|
||||
assert session.exit_detected_by == "pidfd"
|
||||
|
||||
|
||||
def test_drop_removes_the_record_and_its_mirror(registry: Registry):
|
||||
session = registry.add(make_session())
|
||||
path = registry.record_path(session.id)
|
||||
registry.drop(session.id)
|
||||
assert not path.exists()
|
||||
assert registry.get(session.id) is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# loading / adoption
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_load_records_reads_back_what_was_persisted(tmp_path: Path):
|
||||
writer = Registry(tmp_path, ManualClock())
|
||||
writer.ensure_dirs()
|
||||
writer.add(make_session("foot-aaaaaa"))
|
||||
writer.add(make_session("foot-bbbbbb", pid=99))
|
||||
|
||||
reader = Registry(tmp_path, ManualClock())
|
||||
records, quarantined = reader.load_records()
|
||||
assert quarantined == []
|
||||
assert sorted(r.id for r in records) == ["foot-aaaaaa", "foot-bbbbbb"]
|
||||
|
||||
|
||||
def test_a_corrupt_record_is_quarantined_not_deleted_and_not_acted_on(tmp_path: Path, caplog):
|
||||
registry = Registry(tmp_path, ManualClock())
|
||||
registry.ensure_dirs()
|
||||
bad = registry.sessions_dir / "foot-broken.json"
|
||||
bad.write_text("{this is not json")
|
||||
|
||||
records, quarantined = registry.load_records()
|
||||
assert records == []
|
||||
assert len(quarantined) == 1
|
||||
assert not bad.exists()
|
||||
moved = list(registry.quarantine_dir.iterdir())
|
||||
assert len(moved) == 1
|
||||
assert moved[0].read_text() == "{this is not json"
|
||||
assert "quarantining unreadable record" in caplog.text
|
||||
|
||||
|
||||
def test_a_record_that_is_not_an_object_is_quarantined(tmp_path: Path):
|
||||
registry = Registry(tmp_path, ManualClock())
|
||||
registry.ensure_dirs()
|
||||
(registry.sessions_dir / "x.json").write_text("[1, 2, 3]")
|
||||
records, quarantined = registry.load_records()
|
||||
assert records == [] and len(quarantined) == 1
|
||||
|
||||
|
||||
def test_unknown_fields_from_a_newer_schema_are_dropped_not_fatal(caplog):
|
||||
data = make_session().to_dict()
|
||||
data["invented_by_a_later_version"] = True
|
||||
session = Session.from_dict(data)
|
||||
assert session.id == "foot-aaaaaa"
|
||||
assert "dropping unknown record fields" in caplog.text
|
||||
|
||||
|
||||
def test_a_record_from_a_previous_boot_is_recognised_as_stale(tmp_path: Path):
|
||||
"""Pids restart from zero at boot, so /proc cannot be trusted about them."""
|
||||
|
||||
registry = Registry(tmp_path, ManualClock())
|
||||
this_boot = make_session("foot-aaaaaa")
|
||||
this_boot.boot_id = registry._boot_id
|
||||
previous_boot = make_session("foot-bbbbbb")
|
||||
previous_boot.boot_id = "00000000-0000-0000-0000-000000000000"
|
||||
|
||||
assert registry.stale_boot(this_boot) is False
|
||||
assert registry.stale_boot(previous_boot) is True
|
||||
|
||||
|
||||
def test_derived_fields_reported_to_callers(registry: Registry):
|
||||
session = registry.add(make_session())
|
||||
public = session.public(now=1000.0 + 600.0)
|
||||
assert public["idle_s"] == 600.0
|
||||
assert public["expires_in_s"] == 10800.0 - 600.0
|
||||
assert public["live"] is True
|
||||
assert public["schema"] == 2
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Bounded tail reads.
|
||||
|
||||
Both the audit log and an application's captured output are unbounded in M0, and
|
||||
both are read by verbs that must stay cheap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from hhstreamd.textio import tail_lines
|
||||
|
||||
|
||||
def test_the_last_n_lines_are_returned(tmp_path: Path):
|
||||
path = tmp_path / "f.log"
|
||||
path.write_text("".join(f"line {i}\n" for i in range(100)))
|
||||
lines, truncated, size = tail_lines(path, 3)
|
||||
assert lines == ["line 97", "line 98", "line 99"]
|
||||
assert truncated is True # there was more above the window
|
||||
assert size == path.stat().st_size
|
||||
|
||||
|
||||
def test_a_short_file_is_returned_whole_and_not_marked_truncated(tmp_path: Path):
|
||||
path = tmp_path / "f.log"
|
||||
path.write_text("a\nb\n")
|
||||
assert tail_lines(path, 10) == (["a", "b"], False, 4)
|
||||
|
||||
|
||||
def test_a_large_file_is_never_read_whole(tmp_path: Path):
|
||||
"""A gigabyte of Chromium stderr must not become a daemon-sized allocation."""
|
||||
|
||||
path = tmp_path / "big.log"
|
||||
path.write_text("".join(f"{i:07d} padding padding padding\n" for i in range(40_000)))
|
||||
assert path.stat().st_size > 1_000_000
|
||||
|
||||
lines, truncated, size = tail_lines(path, 5, max_bytes=4096)
|
||||
assert len(lines) == 5
|
||||
assert lines[-1] == "0039999 padding padding padding"
|
||||
assert truncated is True
|
||||
assert size == path.stat().st_size
|
||||
|
||||
|
||||
def test_a_partial_first_line_in_the_window_is_dropped_not_reported_as_whole(tmp_path: Path):
|
||||
path = tmp_path / "f.log"
|
||||
path.write_text("aaaaaaaaaaaaaaaaaaaa\nbbbb\ncccc\n")
|
||||
lines, truncated, _ = tail_lines(path, 10, max_bytes=12)
|
||||
assert "aaaa" not in "".join(lines)
|
||||
assert lines == ["cccc"] or lines == ["bbbb", "cccc"]
|
||||
assert truncated is True
|
||||
|
||||
|
||||
def test_a_missing_file_is_empty_rather_than_an_error(tmp_path: Path):
|
||||
assert tail_lines(tmp_path / "absent.log", 10) == ([], False, 0)
|
||||
|
||||
|
||||
def test_asking_for_no_lines_still_reports_the_size(tmp_path: Path):
|
||||
path = tmp_path / "f.log"
|
||||
path.write_text("hello\n")
|
||||
assert tail_lines(path, 0) == ([], False, 6)
|
||||
|
||||
|
||||
def test_invalid_utf8_is_replaced_not_fatal(tmp_path: Path):
|
||||
path = tmp_path / "f.log"
|
||||
path.write_bytes(b"ok\n\xff\xfe bad\n")
|
||||
lines, _, _ = tail_lines(path, 10)
|
||||
assert lines[0] == "ok"
|
||||
assert "bad" in lines[1]
|
||||
Reference in new issue
Block a user