diff --git a/checks/unit.nix b/checks/unit.nix index 0d96c9d..7b5a63b 100644 --- a/checks/unit.nix +++ b/checks/unit.nix @@ -32,11 +32,20 @@ let # `mcp.types.Tool` objects is where a malformed schema or a name the spec # refuses would show up, and a file that skipped when the SDK was absent # would be green in exactly the build where that mattered. + # `starlette` and `httpx` beside `mcp`, and for the same reason the comment + # above gives: `tests/unit/test_mcp_http.py` drives the HTTP transport + # through `starlette.testclient`, which needs `httpx`. Both arrive through + # the SDK today -- measured -- and relying on that is the trap. An SDK + # release that moved its HTTP transport behind an optional extra would make + # 43 tests vanish from this gate, and a gate that loses tests silently is + # worse than one that fails. pytestEnv = python3.withPackages (ps: [ ps.pytest ps.pywayland ps.xkbcommon ps.mcp + ps.starlette + ps.httpx ]); # Only the suite itself, so an editor's droppings or a local .pytest_cache @@ -84,6 +93,10 @@ runCommand "hhstream-unit" # so here, as for `hhstream`, the import comes from what Nix installed, and a # packaging mistake is distinguishable from a test failure. python3 -c 'import hhstream_mcp.tools as t; print("mcp tool table:", len(t.TOOLS), "tools")' + # The HTTP transport's stack, proved present here rather than discovered as a + # skip in the report: `test_mcp_http.py` imports `starlette.testclient` at + # module scope and is not allowed to skip. + python3 -c 'import starlette.testclient, hhstream_mcp.http; print("http transport imports")' set +e pytest suite \ diff --git a/nix/mcp.nix b/nix/mcp.nix index fd7f6e6..0b8dd37 100644 --- a/nix/mcp.nix +++ b/nix/mcp.nix @@ -41,6 +41,11 @@ python3.pkgs.buildPythonApplication { dependencies = [ python3.pkgs.mcp python3.pkgs.anyio + # The HTTP transport's own two, declared for the reason `anyio` is: the SDK + # propagates both today, and `hhstream_mcp.http` imports them by name. See + # the note in src/hhstream_mcp/pyproject.toml. + python3.pkgs.starlette + python3.pkgs.uvicorn # An application is not importable by a dependent until this converts it, # and `hhstream_mcp.invoke` imports `hhstream.cli` directly. (python3.pkgs.toPythonModule hhstream) diff --git a/nix/module.nix b/nix/module.nix index 91d92dc..4ea9395 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -1697,7 +1697,18 @@ in { SupplementaryGroups = [cfg.sessions.group]; WorkingDirectory = cfg.mcp.stateDir; - UMask = "0077"; + # The CLI's own umask and not a tighter one, deliberately. This unit's + # tools write files an operator then reads: `shot --output` and + # `record` produce exactly the files the same verbs produce from a + # shell, and a unit that made them 0600 would be a surprising + # difference between the CLI and the tool that wraps it -- the sort + # that ends with a web server unable to read a capture and nothing + # saying why. + # + # The authorization table is not protected by this. It is `0600` by an + # explicit chmod, inside a `0700` directory declared by the tmpfiles + # entry above, which is what actually guards it. + UMask = "0022"; Restart = "on-failure"; RestartSec = 5; diff --git a/src/hhstream_mcp/http.py b/src/hhstream_mcp/http.py index 6f0303f..52e1a2f 100644 --- a/src/hhstream_mcp/http.py +++ b/src/hhstream_mcp/http.py @@ -51,11 +51,27 @@ The deliberate choices in the request path :class:`~hhstream_live.server.RateLimiter` rather than growing a second one. 256-bit tokens make guessing hopeless already; this is so an attacker cannot even try at line speed and so the attempt is visible in one place. + +One operational property worth knowing before enabling this +--------------------------------------------------------- + +**Tool calls are serialised across every caller, not per session.** +:class:`hhstream_mcp.invoke.Runner` holds a process-wide lock because the CLI +it calls prints to a stdout this process shares, and that was invisible while +each client had a process of its own. It is visible here: two agents on two +tokens queue behind each other, and a slow call (a long ``record``, a ``grim`` +wedged on a compositor that has stopped answering) delays everyone's next call +rather than only its own caller's. + +The event loop stays responsive throughout -- a ``ping`` is answered, a +resource read is still off the loop in its own thread -- so this is latency and +never a hang. It is the same limit +``docs/TODO/mcp-in-process-has-no-call-deadline.md`` already describes, with +one more consequence now that the transport is shared. """ from __future__ import annotations -import contextlib import logging from collections.abc import Callable, Sequence from typing import Any @@ -176,26 +192,31 @@ class BearerAuth: async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None: # `lifespan` is the server talking to itself; only `http` carries a - # caller. A `websocket` scope would reach here if a route grew one, - # and falls into the same refusal as an unauthenticated request. + # caller. if scope["type"] == "lifespan": await self.app(scope, receive, send) return if scope["type"] != "http": - await self._refuse(scope, receive, send) + # Nothing here mounts a websocket, so this is unreachable today -- + # but it is refused in that protocol's own terms rather than with + # an `http.response.start` a websocket client cannot read. An + # unreachable branch that would send the wrong frame is a trap for + # whoever makes it reachable. + log.warning("refusing a %r scope: this server is http only", scope["type"]) + await send({"type": "websocket.close", "code": 1008}) return client = (scope.get("client") or ("unknown", 0))[0] header = _header(scope, b"authorization") token = bearer_token(header) if header else None if token is None: - await self._refuse(scope, receive, send, client=client, reason="no bearer token") + await self._refuse(send, client=client, reason="no bearer token") return # A file read, so off the event loop: small, but the discipline is the # one the rest of this package keeps about blocking work. grant = await anyio.to_thread.run_sync(lambda: self.store.verify(token)) if grant is None: - await self._refuse(scope, receive, send, client=client, reason="token refused") + await self._refuse(send, client=client, reason="token refused") return scope[SCOPE_KEY] = grant log.debug("request authorized by token %s", grant.id) @@ -203,8 +224,6 @@ class BearerAuth: async def _refuse( self, - scope: dict[str, Any], - receive: Any, send: Any, *, client: str = "unknown", @@ -219,17 +238,13 @@ class BearerAuth: allowed = self.limiter.allow(client) status = 401 if allowed else 429 log.warning("%s from %s: %s", status, client, reason if allowed else "rate limited") - headers = [ - (b"content-length", b"0"), - (b"cache-control", b"no-store"), - (b"x-content-type-options", b"nosniff"), - ] + headers: list[tuple[bytes, bytes]] = [] if status == 401: # RFC 9110's challenge. A realm and nothing else: there is no - # `as_uri` to point at, because there is no authorization server. + # metadata document to point at, because there is no authorization + # server -- see `docs/TODO/mcp-http-auth-is-not-oauth.md`. headers.append((b"www-authenticate", f'Bearer realm="{SERVER_NAME}"'.encode())) - await send({"type": "http.response.start", "status": status, "headers": headers}) - await send({"type": "http.response.body", "body": b""}) + await _empty(send, status, headers) def _header(scope: dict[str, Any], name: bytes) -> str: @@ -297,6 +312,85 @@ def offered_for(server: Any, base: tuple[tools.Tool, ...]) -> Callable[[], tuple return chooser +class Endpoint: + """The ASGI app under :class:`BearerAuth`: one path, and the lifespan. + + Hand-rolled rather than ``Starlette(routes=[Mount(path, app=…)])``, and + the reason is a 307 that costs real clients their request. A Starlette + ``Mount`` at ``/mcp`` serves ``/mcp/`` and answers ``/mcp`` with a redirect + (or a 404 with ``redirect_slashes`` off) -- measured, both ways. Every MCP + client configuration spells the URL without the trailing slash, and a + redirected **POST** has to be re-sent with its body, which ``urllib`` will + not do at all and some clients get wrong. So the path is matched here, + exactly, with and without the slash, and nothing redirects. + + It also means the only routing in this server is three lines long and in + one place, which is the whole of what a single-endpoint server needs. + """ + + def __init__(self, manager: StreamableHTTPSessionManager, path: str) -> None: + self.manager = manager + # Both spellings are the endpoint; neither is a redirect to the other. + self.paths = {path, path.rstrip("/") + "/"} if path != "/" else {"/"} + + async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None: + if scope["type"] == "lifespan": + await self._lifespan(receive, send) + return + if scope.get("path") in self.paths: + await self.manager.handle_request(scope, receive, send) + return + await _empty(send, 404) + + async def _lifespan(self, receive: Any, send: Any) -> None: + """The startup/shutdown protocol, by hand. + + ``manager.run()`` has to stay open for the life of the process: it owns + the task group the per-session server tasks live in. Entered on + ``startup`` and exited on ``shutdown``, both of which arrive in this + one coroutine -- which matters, because an anyio task group must be + exited by the task that entered it. + """ + + running: Any = None + while True: + message = await receive() + kind = message["type"] + if kind == "lifespan.startup": + try: + running = self.manager.run() + await running.__aenter__() + except BaseException as exc: # noqa: BLE001 -- reported, not swallowed + log.exception("http transport failed to start") + await send({"type": "lifespan.startup.failed", "message": repr(exc)}) + return + log.info("http transport ready on %s", ", ".join(sorted(self.paths))) + await send({"type": "lifespan.startup.complete"}) + elif kind == "lifespan.shutdown": + if running is not None: + await running.__aexit__(None, None, None) + await send({"type": "lifespan.shutdown.complete"}) + return + + +async def _empty(send: Any, status: int, headers: list[tuple[bytes, bytes]] | None = None) -> None: + """A response with no body, which is every response this layer writes itself.""" + + await send( + { + "type": "http.response.start", + "status": status, + "headers": [ + (b"content-length", b"0"), + (b"cache-control", b"no-store"), + (b"x-content-type-options", b"nosniff"), + *(headers or ()), + ], + } + ) + await send({"type": "http.response.body", "body": b""}) + + def build_app( runner: Runner, store: Store, @@ -308,7 +402,7 @@ def build_app( stateless: bool = False, json_response: bool = False, ) -> Any: - """The ASGI application: one route, behind :class:`BearerAuth`. + """The ASGI application: one endpoint, behind :class:`BearerAuth`. ``allowed_hosts`` must already be resolved -- :func:`default_allowed_hosts` is the caller's to apply, because the empty list has to stay meaningful @@ -322,12 +416,6 @@ def build_app( only honest answer. """ - # Imported here and not at module scope: `build_app` is the only thing in - # this file that needs Starlette, and an import error should name the - # feature being started rather than fire on `import hhstream_mcp.http`. - from starlette.applications import Starlette - from starlette.routing import Mount - from .server import build security = TransportSecuritySettings( @@ -356,28 +444,11 @@ def build_app( json_response=json_response, security_settings=security, ) - - async def handle(scope: Any, receive: Any, send: Any) -> None: - await manager.handle_request(scope, receive, send) - - @contextlib.asynccontextmanager - async def lifespan(_app: Any) -> Any: - # The manager's task group has to be open for the whole life of the - # process: it owns the per-session server tasks. - async with manager.run(): - log.info("http transport ready on %s", path) - yield - - app = Starlette( - debug=False, - routes=[Mount(path, app=handle)], - lifespan=lifespan, - ) - # The token check wraps the *whole* app and not just the route, so a + # The token check wraps the *whole* app and not just the endpoint, so a # request to any other path is a 401 rather than a 404. An unauthenticated # caller learns nothing about what this server has mounted, including # whether it is an hhstream server at all. - return BearerAuth(app, store) + return BearerAuth(Endpoint(manager, path), store) def serve( @@ -435,6 +506,7 @@ __all__ = [ "DEFAULT_PORT", "SCOPE_KEY", "BearerAuth", + "Endpoint", "bearer_token", "build_app", "current_grant", diff --git a/src/hhstream_mcp/pyproject.toml b/src/hhstream_mcp/pyproject.toml index 6642c88..0e6af41 100644 --- a/src/hhstream_mcp/pyproject.toml +++ b/src/hhstream_mcp/pyproject.toml @@ -29,13 +29,23 @@ requires-python = ">=3.11" # SDK: `server.py` calls `anyio.run` and `anyio.to_thread` directly, and a # dependency used by name belongs in the metadata. # +# `starlette` and `uvicorn` are declared for exactly that reason and no other. +# The SDK pulls both in today -- its streamable-HTTP transport needs them -- so +# leaving them out would work, which is the trap: `http.py` imports +# `uvicorn` and the SDK's `TransportSecuritySettings` sits on Starlette's +# `Request`, and an SDK release that moved either behind an optional extra +# would break `serve --http` with an ImportError naming someone else's package. +# They are only needed by the HTTP transport, which is why they are imported +# inside the functions that use them rather than at module scope: the stdio +# path must neither pay for them nor fail on them. +# # `hhstream` is NOT listed, and it is not optional either: this package imports # `hhstream.cli`, `hhstreamd.protocol` and `hhstream_session` and does not work # without them. It is absent because `hhstream` is not a wheel anyone installs # from an index -- it is this repository's other derivation, and `nix/mcp.nix` # is where the two are joined. A dependency naming a version nobody can # resolve would be worse than the comment you are reading. -dependencies = ["mcp>=1.9", "anyio>=4"] +dependencies = ["mcp>=1.9", "anyio>=4", "starlette>=0.40", "uvicorn>=0.30"] [project.scripts] # Stdio only. One process per client, spawned by the client; no port, no daemon. diff --git a/tests/unit/test_mcp_authorizations.py b/tests/unit/test_mcp_authorizations.py new file mode 100644 index 0000000..1c95ae3 --- /dev/null +++ b/tests/unit/test_mcp_authorizations.py @@ -0,0 +1,483 @@ +"""The token store, and the token verbs on top of it. + +Standard library only, like the module under test: no SDK, no socket, no +Starlette. The HTTP transport that consumes these tokens is +``test_mcp_http.py``. + +Two properties get most of the attention here, because both are the kind that +a refactor breaks silently: + +* **the file never holds a token.** A store that quietly started writing the + secret would pass every functional test in this file, so there is an explicit + one that reads the bytes on disk and looks for it. +* **a lost update is impossible.** Two processes write this file, and the + atomic replace alone does not prevent one from overwriting a table the other + just added to. The concurrency test does the interleaving by hand. +""" + +from __future__ import annotations + +import json +import os +import threading +from pathlib import Path + +import pytest +from hhstreamd.clock import ManualClock + +from hhstream_mcp import authorizations as auth +from hhstream_mcp import server, tokencli + + +@pytest.fixture +def store(tmp_path): + return auth.Store.at(tmp_path / "state") + + +# ── the token itself ─────────────────────────────────────────────────────── + + +def test_mint_token_is_prefixed_and_long(): + token = auth.mint_token() + assert token.startswith(auth.TOKEN_PREFIX) + # The prefix is for recognising a leak on sight; the rest carries the + # entropy. 32 bytes base64url is 43 characters. + assert len(token) - len(auth.TOKEN_PREFIX) >= 43 + + +def test_mint_token_never_repeats(): + assert len({auth.mint_token() for _ in range(200)}) == 200 + + +def test_hash_is_stable_and_not_the_token(): + token = auth.mint_token() + digest = auth.hash_token(token) + assert digest == auth.hash_token(token) + assert len(digest) == 64 + assert token not in digest + + +# ── the table ────────────────────────────────────────────────────────────── + + +def test_missing_file_is_an_empty_table(store): + assert store.load() == [] + assert not store.path.exists() + + +def test_mint_then_load_round_trips_every_field(store): + grant, token = store.mint(label="laptop", ttl=3600, toolsets=["frames", "pointer"]) + (loaded,) = store.load() + assert loaded.id == grant.id + assert loaded.label == "laptop" + assert loaded.toolsets == ("frames", "pointer") + assert loaded.expires_at == pytest.approx(grant.expires_at) + assert loaded.hash == auth.hash_token(token) + + +def test_the_file_does_not_contain_the_token(store): + _, token = store.mint(label="secret-bearing") + raw = store.path.read_bytes() + assert token.encode() not in raw + # Nor any usable prefix of it: a truncated write would be just as bad. + assert token[len(auth.TOKEN_PREFIX) : len(auth.TOKEN_PREFIX) + 20].encode() not in raw + + +def test_the_file_is_private_and_so_is_its_directory(store): + store.mint() + assert os.stat(store.path).st_mode & 0o777 == 0o600 + assert os.stat(store.state_dir).st_mode & 0o777 == 0o700 + + +def test_the_file_is_json_with_a_version(store): + store.mint() + data = json.loads(store.path.read_text()) + assert data["version"] == auth.FORMAT_VERSION + assert len(data["grants"]) == 1 + + +def test_ids_are_unique_across_many_mints(store): + for _ in range(50): + store.mint() + ids = [g.id for g in store.load()] + assert len(set(ids)) == 50 + + +# ── verify ───────────────────────────────────────────────────────────────── + + +def test_verify_accepts_the_minted_token(store): + grant, token = store.mint(label="good") + found = store.verify(token) + assert found is not None + assert found.id == grant.id + + +@pytest.mark.parametrize( + "bad", + [ + "", + "hhsmcp_not-a-real-token", + "completely wrong", + auth.TOKEN_PREFIX, + ], +) +def test_verify_refuses_anything_else(store, bad): + store.mint() + assert store.verify(bad) is None + + +def test_verify_refuses_a_revoked_token(store): + grant, token = store.mint() + store.revoke(grant.id) + assert store.verify(token) is None + + +def test_verify_refuses_an_expired_token(store): + clock = ManualClock() + store.clock = clock + _, token = store.mint(ttl=60) + assert store.verify(token) is not None + clock.advance(61) + assert store.verify(token) is None + + +def test_verify_refuses_everything_when_the_table_is_corrupt(store): + _, token = store.mint() + store.path.write_text("{ not json") + # Deny, never allow: a store that cannot be read is not a store that lets + # everyone in. + assert store.verify(token) is None + + +def test_verify_refuses_a_table_from_a_future_version(store): + _, token = store.mint() + data = json.loads(store.path.read_text()) + data["version"] = auth.FORMAT_VERSION + 1 + store.path.write_text(json.dumps(data)) + assert store.verify(token) is None + with pytest.raises(auth.StoreError, match="format version"): + store.load() + + +def test_one_token_does_not_verify_as_another(store): + _, first = store.mint(label="a") + second_grant, second = store.mint(label="b") + assert store.verify(first).id != second_grant.id + assert store.verify(second).id == second_grant.id + + +# ── last_used ────────────────────────────────────────────────────────────── + + +def test_verify_stamps_last_used(store): + grant, token = store.mint() + assert grant.last_used is None + store.verify(token) + (loaded,) = store.load() + assert loaded.last_used is not None + + +def test_the_stamp_is_throttled(store): + clock = ManualClock() + store.clock = clock + _, token = store.mint() + store.verify(token) + first = store.load()[0].last_used + clock.advance(auth.LAST_USED_FLUSH_S / 2) + store.verify(token) + assert store.load()[0].last_used == first + clock.advance(auth.LAST_USED_FLUSH_S) + store.verify(token) + assert store.load()[0].last_used != first + + +def test_stamp_does_not_resurrect_a_token_revoked_underneath_it(store): + grant, token = store.mint() + # The grant object the caller is holding, after it has been removed: this + # is the real interleaving, where a `verify` and a `revoke` race. + store.revoke(grant.id) + store._stamp(grant, store.clock.wall()) + assert store.load() == [] + + +def test_verify_can_be_asked_not_to_stamp(store): + _, token = store.mint() + assert store.verify(token, stamp=False) is not None + assert store.load()[0].last_used is None + + +# ── revoke and prune ─────────────────────────────────────────────────────── + + +def test_revoke_removes_only_the_named_grant(store): + first, _ = store.mint(label="a") + second, _ = store.mint(label="b") + store.revoke(first.id) + assert [g.id for g in store.load()] == [second.id] + + +def test_revoke_an_unknown_id_raises(store): + store.mint() + with pytest.raises(auth.NoSuchGrant, match="no token with id"): + store.revoke("zzzzzz") + assert len(store.load()) == 1 + + +def test_revoke_all_empties_the_table(store): + for _ in range(3): + store.mint() + gone = store.revoke_all() + assert len(gone) == 3 + assert store.load() == [] + + +def test_prune_drops_only_what_expired(store): + clock = ManualClock() + store.clock = clock + store.mint(label="short", ttl=10) + keeper, _ = store.mint(label="forever") + clock.advance(11) + dropped = store.prune() + assert [g.label for g in dropped] == ["short"] + assert [g.id for g in store.load()] == [keeper.id] + + +def test_prune_is_housekeeping_not_enforcement(store): + """An expired token is refused whether or not `prune` has run.""" + + clock = ManualClock() + store.clock = clock + _, token = store.mint(ttl=10) + clock.advance(11) + assert store.verify(token) is None + assert len(store.load()) == 1 # still on disk, and still refused + + +# ── the lock ─────────────────────────────────────────────────────────────── + + +def test_a_concurrent_mint_is_not_lost(tmp_path): + """Thirty threads minting into one table; every token must survive. + + The atomic replace stops a reader seeing half a file. It does **not** stop + two writers from each loading the same table and the second replacing the + first's addition -- which is why the store takes a flock, and why this test + would fail without it. + """ + + store = auth.Store.at(tmp_path / "state") + tokens: list[str] = [] + lock = threading.Lock() + errors: list[BaseException] = [] + + def mint() -> None: + try: + _, token = store.mint() + with lock: + tokens.append(token) + except BaseException as exc: # recorded, asserted below + with lock: + errors.append(exc) + + threads = [threading.Thread(target=mint) for _ in range(30)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(30) + + assert errors == [] + assert len(store.load()) == 30 + # And every one of them still works, which is the property that matters. + for token in tokens: + assert store.verify(token, stamp=False) is not None + + +def test_separate_store_objects_see_each_others_writes(tmp_path): + """Two `Store` instances on one path, as a unit and a shell would be.""" + + root = tmp_path / "state" + unit = auth.Store.at(root) + operator = auth.Store.at(root) + _, token = operator.mint(label="minted by the operator") + assert unit.verify(token) is not None + + +# ── where the store lives ────────────────────────────────────────────────── + + +def test_the_default_is_not_the_brokers_state_dir(): + """The broker's state dir is 0700 and holds its audit trail; stay out.""" + + assert auth.DEFAULT_STATE_DIR == "/var/lib/hhstream-mcp" + assert not auth.DEFAULT_STATE_DIR.startswith("/var/lib/hhstream/") + + +def test_the_environment_names_the_state_dir(tmp_path, monkeypatch): + monkeypatch.setenv(auth.ENV_STATE_DIR, str(tmp_path / "from-env")) + assert auth.Store.at().state_dir == tmp_path / "from-env" + + +def test_an_explicit_dir_beats_the_environment(tmp_path, monkeypatch): + monkeypatch.setenv(auth.ENV_STATE_DIR, str(tmp_path / "from-env")) + assert auth.Store.at(tmp_path / "explicit").state_dir == tmp_path / "explicit" + + +# ── the CLI verbs ────────────────────────────────────────────────────────── + + +@pytest.fixture +def state_dir(tmp_path, monkeypatch): + root = tmp_path / "state" + monkeypatch.setenv(auth.ENV_STATE_DIR, str(root)) + return root + + +def test_mint_prints_the_token_on_stdout_and_nothing_else(state_dir, capsys): + assert server.main(["token", "mint"]) == tokencli.EXIT_OK + captured = capsys.readouterr() + token = captured.out.strip() + # Exactly the token on stdout, so `token mint | ...` is usable. + assert token.startswith(auth.TOKEN_PREFIX) + assert "\n" not in token + # And the prose for the human is on stderr, beside it. + assert "only time the token is shown" in captured.err + assert auth.Store.at(state_dir).verify(token) is not None + + +def test_mint_accepts_a_label_an_expiry_and_toolsets(state_dir, capsys): + rc = server.main( + ["token", "mint", "--label", "laptop", "--expires-in", "30d", + "--toolsets", "frames,pointer"] + ) + assert rc == tokencli.EXIT_OK + capsys.readouterr() + (grant,) = auth.Store.at(state_dir).load() + assert grant.label == "laptop" + assert grant.toolsets == ("frames", "pointer") + assert grant.expires_at is not None + + +@pytest.mark.parametrize( + "argv", + [ + ["token", "mint", "--expires-in", "not-a-duration"], + ["token", "mint", "--expires-in", "0"], + ["token", "mint", "--toolsets", "nonesuch"], + ["token", "mint", "--toolsets", ","], + ], +) +def test_mint_refuses_a_bad_argument(state_dir, argv): + with pytest.raises(SystemExit) as exit_info: + server.main(argv) + assert exit_info.value.code == tokencli.EXIT_USAGE + assert auth.Store.at(state_dir).load() == [] + + +def test_list_shows_the_ids_but_never_a_token(state_dir, capsys): + server.main(["token", "mint", "--label", "one"]) + token = capsys.readouterr().out.strip() + assert server.main(["token", "list"]) == tokencli.EXIT_OK + out = capsys.readouterr().out + assert "one" in out + assert auth.Store.at(state_dir).load()[0].id in out + assert token not in out + + +def test_list_json_is_the_records(state_dir, capsys): + server.main(["token", "mint", "--label", "one"]) + capsys.readouterr() + assert server.main(["token", "list", "--json"]) == tokencli.EXIT_OK + records = json.loads(capsys.readouterr().out) + assert [r["label"] for r in records] == ["one"] + assert "hash" in records[0] + + +def test_list_on_an_empty_table_says_so_and_succeeds(state_dir, capsys): + assert server.main(["token", "list"]) == tokencli.EXIT_OK + assert "no tokens" in capsys.readouterr().err + + +def test_revoke_by_id(state_dir, capsys): + server.main(["token", "mint"]) + capsys.readouterr() + grant_id = auth.Store.at(state_dir).load()[0].id + assert server.main(["token", "revoke", grant_id]) == tokencli.EXIT_OK + assert auth.Store.at(state_dir).load() == [] + + +def test_revoke_an_unknown_id_is_exit_3(state_dir, capsys): + assert server.main(["token", "revoke", "zzzzzz"]) == tokencli.EXIT_NO_SUCH_TOKEN + assert "no token with id" in capsys.readouterr().err + + +def test_revoke_all(state_dir, capsys): + for _ in range(3): + server.main(["token", "mint"]) + capsys.readouterr() + assert server.main(["token", "revoke", "--all"]) == tokencli.EXIT_OK + assert auth.Store.at(state_dir).load() == [] + + +def test_revoke_needs_an_id_or_all(state_dir): + with pytest.raises(SystemExit) as exit_info: + server.main(["token", "revoke"]) + assert exit_info.value.code == tokencli.EXIT_USAGE + + +def test_revoke_refuses_an_id_and_all_together(state_dir): + with pytest.raises(SystemExit) as exit_info: + server.main(["token", "revoke", "abc123", "--all"]) + assert exit_info.value.code == tokencli.EXIT_USAGE + + +def test_prune_through_the_cli(state_dir, capsys): + assert server.main(["token", "prune"]) == tokencli.EXIT_OK + assert "nothing expired" in capsys.readouterr().err + + +def test_token_with_no_verb_prints_help(state_dir, capsys): + assert server.main(["token"]) == tokencli.EXIT_USAGE + assert "mint" in capsys.readouterr().out + + +def test_an_unreadable_table_is_exit_4(state_dir, capsys): + state_dir.mkdir(parents=True) + (state_dir / auth.STORE_NAME).write_text("{ not json") + assert server.main(["token", "list"]) == tokencli.EXIT_STORE + assert "not valid JSON" in capsys.readouterr().err + + +def test_state_dir_flag_overrides_the_environment(state_dir, tmp_path, capsys): + elsewhere = tmp_path / "elsewhere" + assert server.main(["token", "--state-dir", str(elsewhere), "mint"]) == 0 + capsys.readouterr() + assert len(auth.Store.at(elsewhere).load()) == 1 + assert auth.Store.at(state_dir).load() == [] + + +def test_the_token_verbs_never_claim_the_transport(state_dir, monkeypatch, capsys): + """`mint` prints a secret on stdout, which on stdio *is* the transport. + + So the verb has to return before anything moves file descriptor 1. A fake + `claim_transport` that fails the test if it is called is the only way to + assert that from here. + """ + + def forbidden(): + raise AssertionError("a token verb claimed the stdio transport") + + monkeypatch.setattr(server, "claim_transport", forbidden) + assert server.main(["token", "mint"]) == tokencli.EXIT_OK + assert server.main(["token", "list"]) == tokencli.EXIT_OK + capsys.readouterr() + + +def test_row_for_renders_the_honest_gaps(): + grant = auth.Grant(id="abc123", hash="x" * 64) + row = tokencli.row_for(grant) + assert row[0] == "abc123" + assert row[3] == "never" # expires + assert row[4] == "never" # last used + assert row[5] == "all" # toolsets + assert len(row) == len(tokencli.HEADERS) diff --git a/tests/unit/test_mcp_http.py b/tests/unit/test_mcp_http.py new file mode 100644 index 0000000..c549ab6 --- /dev/null +++ b/tests/unit/test_mcp_http.py @@ -0,0 +1,473 @@ +"""The HTTP transport: every way a request is refused, and the one way it is not. + +This file imports Starlette as well as the SDK, **unconditionally**, for the +reason ``test_mcp_server.py`` imports the SDK that way: the thing under test is +the wiring, only a real ASGI stack can judge it, and a file that skipped when +its dependency was missing would be green in precisely the build where that +mattered. The store itself is +standard library and tested without any of this +(``test_mcp_authorizations.py``). + +The app is driven through ``starlette.testclient``, which speaks to it over +ASGI with no socket. That is enough for everything here -- a status code, a +header, an empty body, which tools a session is shown -- and it is +deliberately *not* enough for "the unit comes up and answers on a port", which +is ``checks/vm-mcp.nix``' job. + +``Host: testserver`` is what the test client sends, so every app built here +names it in ``allowed_hosts``. That is not a workaround: DNS-rebinding +protection is on by default and an app that did not name its clients' host +would 421 them, which is the behaviour ``test_rebinding_protection_*`` asserts. +""" + +from __future__ import annotations + +import json + +import pytest + +from hhstream_mcp import authorizations as auth +from hhstream_mcp import http as http_transport +from hhstream_mcp import resources, tools +from hhstream_mcp.invoke import Runner + +# Imported unconditionally, and not through `importorskip`, for the reason +# `test_mcp_server.py` imports the SDK unconditionally: a file that skipped +# when its dependency was absent would be green in exactly the build where +# that mattered. `checks/unit.nix` declares `starlette` and `httpx` so this +# cannot become a skip, and proves them importable before pytest runs. +from starlette.testclient import TestClient + +#: The test client's Host, plus what a loopback deployment derives. +TEST_HOSTS = ["testserver", *http_transport.default_allowed_hosts("127.0.0.1", 9989)] + +HEADERS = { + "Accept": "application/json, text/event-stream", + "Content-Type": "application/json", +} +INITIALIZE = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "test", "version": "0"}, + }, +} + + +@pytest.fixture +def store(tmp_path): + return auth.Store.at(tmp_path / "state") + + +def make_app(store, **kwargs): + """The app, with a Runner that never reaches a CLI. + + ``entry`` returns 0 without doing anything: nothing in this file calls a + tool for its effect, and a Runner that could reach `hhstream.cli` would + make these tests depend on a broker socket. + """ + + kwargs.setdefault("allowed_hosts", TEST_HOSTS) + kwargs.setdefault("json_response", True) + return http_transport.build_app(Runner(entry=lambda argv: 0), store, **kwargs) + + +def post(client, body, token=None, headers=None, path="/mcp"): + """One POST, and **never** following a redirect. + + `follow_redirects=False` is load-bearing, not tidiness. The test client + follows redirects by default, which is how a `Mount`-shaped 307 on the + exact path `/mcp` passed this whole file once while failing a real client: + a redirected POST has to be re-sent with its body, and `urllib` will not do + that at all. See `test_the_exact_path_does_not_redirect`. + """ + + sent = dict(HEADERS) + if token is not None: + sent["Authorization"] = f"Bearer {token}" + sent.update(headers or {}) + return client.post( + path, content=json.dumps(body), headers=sent, follow_redirects=False + ) + + +def session(client, token): + """Initialize and return the headers that carry the session on.""" + + response = post(client, INITIALIZE, token=token) + assert response.status_code == 200, response.content + extra = {} + sid = response.headers.get("mcp-session-id") + if sid: + extra["mcp-session-id"] = sid + post(client, {"jsonrpc": "2.0", "method": "notifications/initialized"}, + token=token, headers=extra) + return extra + + +def call(client, token, method, params=None, headers=None, request_id=2): + body = {"jsonrpc": "2.0", "id": request_id, "method": method} + if params is not None: + body["params"] = params + response = post(client, body, token=token, headers=headers) + assert response.status_code == 200, response.content + return json.loads(response.content) + + +# ── parsing the header ───────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("header", "expected"), + [ + ("Bearer abc", "abc"), + ("bearer abc", "abc"), # RFC 9110: the scheme is case-insensitive + ("BEARER abc", "abc"), + ("Bearer abc ", "abc"), + ("", None), + ("abc", None), # no scheme + ("Basic abc", None), # wrong scheme + ("Bearer", None), # no token + ("Bearer ", None), + ], +) +def test_bearer_token_parsing(header, expected): + assert http_transport.bearer_token(header) == expected + + +# ── the refusals ─────────────────────────────────────────────────────────── + + +def test_no_header_is_401_with_an_empty_body(store): + store.mint() + with TestClient(make_app(store)) as client: + response = post(client, INITIALIZE) + assert response.status_code == 401 + assert response.content == b"" + assert response.headers["www-authenticate"].startswith("Bearer ") + assert response.headers["cache-control"] == "no-store" + + +def test_a_wrong_token_is_401_and_is_not_echoed(store): + store.mint() + wrong = "hhsmcp_definitely-not-a-real-token" + with TestClient(make_app(store)) as client: + response = post(client, INITIALIZE, token=wrong) + assert response.status_code == 401 + assert response.content == b"" + # Not in the body, and not in any header either. + assert wrong not in "".join(f"{k}{v}" for k, v in response.headers.items()) + + +def test_a_revoked_token_is_401(store): + grant, token = store.mint() + store.revoke(grant.id) + with TestClient(make_app(store)) as client: + assert post(client, INITIALIZE, token=token).status_code == 401 + + +def test_an_expired_token_is_401(store): + from hhstreamd.clock import ManualClock + + clock = ManualClock() + store.clock = clock + _, token = store.mint(ttl=60) + clock.advance(61) + with TestClient(make_app(store)) as client: + assert post(client, INITIALIZE, token=token).status_code == 401 + + +def test_the_wrong_scheme_is_401(store): + _, token = store.mint() + with TestClient(make_app(store)) as client: + response = post(client, INITIALIZE, headers={"Authorization": f"Basic {token}"}) + assert response.status_code == 401 + + +def test_an_empty_table_refuses_everything(store): + with TestClient(make_app(store)) as client: + assert post(client, INITIALIZE, token="hhsmcp_anything").status_code == 401 + + +def test_the_refusal_does_not_say_which_kind_it_was(store): + """Unknown, revoked and expired are one answer, byte for byte. + + Telling them apart would tell someone who guessed a real id that they had. + """ + + grant, revoked = store.mint() + store.revoke(grant.id) + _, live = store.mint() + responses = [] + with TestClient(make_app(store)) as client: + for token in ("hhsmcp_unknown", revoked, live[:-1] + "x"): + response = post(client, INITIALIZE, token=token) + responses.append((response.status_code, response.content, + response.headers.get("www-authenticate"))) + assert len(set(responses)) == 1 + + +@pytest.mark.parametrize("path", ["/mcp", "/mcp/"]) +def test_the_exact_path_does_not_redirect(store, path): + """Both spellings are the endpoint, and neither is a redirect to the other. + + The regression this exists for: `Starlette(routes=[Mount("/mcp", ...)])` + serves `/mcp/` and answers `/mcp` with a 307 — and every MCP client + configuration spells the URL without the trailing slash. The redirect is + invisible to a client that follows it on a POST and fatal to one that does + not, which is why the endpoint matches the path itself instead. + """ + + _, token = store.mint() + with TestClient(make_app(store)) as client: + response = post(client, INITIALIZE, token=token, path=path) + assert response.status_code == 200, ( + f"{path} answered {response.status_code} " + f"(location: {response.headers.get('location')!r})" + ) + + +def test_a_custom_path_is_honoured(store): + _, token = store.mint() + with TestClient(make_app(store, path="/agent/mcp")) as client: + assert post(client, INITIALIZE, token=token, path="/agent/mcp").status_code == 200 + assert post(client, INITIALIZE, token=token, path="/mcp").status_code == 404 + + +def test_an_unknown_path_leaks_nothing_without_a_token(store): + store.mint() + with TestClient(make_app(store)) as client: + # 401 and not 404: an unauthenticated caller does not learn what is + # mounted here, or that anything is. + assert client.get("/elsewhere").status_code == 401 + + +def test_an_unknown_path_is_a_404_once_authenticated(store): + _, token = store.mint() + with TestClient(make_app(store)) as client: + response = client.get( + "/elsewhere", + headers={"Authorization": f"Bearer {token}"}, + follow_redirects=False, + ) + assert response.status_code == 404 + + +def test_repeated_failures_are_rate_limited(store): + from hhstream_live.server import RateLimiter + + store.mint() + app = make_app(store) + app.limiter = RateLimiter(limit=3) + with TestClient(app) as client: + codes = [post(client, INITIALIZE).status_code for _ in range(5)] + assert codes[:3] == [401, 401, 401] + assert codes[3:] == [429, 429] + + +def test_a_good_token_is_not_rate_limited(store): + from hhstream_live.server import RateLimiter + + _, token = store.mint() + app = make_app(store) + app.limiter = RateLimiter(limit=2) + with TestClient(app) as client: + for _ in range(5): + assert post(client, INITIALIZE, token=token).status_code == 200 + + +# ── the one way through ──────────────────────────────────────────────────── + + +def test_a_good_token_completes_the_handshake(store): + _, token = store.mint() + with TestClient(make_app(store)) as client: + response = post(client, INITIALIZE, token=token) + assert response.status_code == 200 + result = json.loads(response.content)["result"] + assert result["serverInfo"]["name"] == "hhstream" + assert "instructions" in result + + +def test_the_full_surface_is_offered_to_an_unrestricted_token(store): + _, token = store.mint() + with TestClient(make_app(store)) as client: + extra = session(client, token) + listed = call(client, token, "tools/list", headers=extra)["result"]["tools"] + offered = call(client, token, "resources/list", headers=extra, + request_id=3)["result"]["resources"] + assert len(listed) == len(tools.TOOLS) + # Counted against the server's own table, never a literal: a resource added + # by a later contract version must not have to be counted here as well. The + # sibling stdio check learned this the hard way. + assert len(offered) == len(resources.FIXED) + + +def test_using_a_token_stamps_it(store): + grant, token = store.mint() + with TestClient(make_app(store)) as client: + session(client, token) + assert store.load()[0].last_used is not None + assert store.load()[0].id == grant.id + + +# ── what a token's toolsets do ───────────────────────────────────────────── + + +def test_a_scoped_token_is_offered_only_its_toolsets(store): + _, token = store.mint(toolsets=["frames"]) + with TestClient(make_app(store)) as client: + extra = session(client, token) + listed = call(client, token, "tools/list", headers=extra)["result"]["tools"] + assert {tool["name"] for tool in listed} == set(tools.TOOLSETS["frames"]) + + +def test_a_scoped_token_cannot_call_outside_its_toolsets(store): + _, token = store.mint(toolsets=["frames"]) + with TestClient(make_app(store)) as client: + extra = session(client, token) + result = call( + client, token, "tools/call", + {"name": "session_gc", "arguments": {}}, headers=extra, + )["result"] + assert result["isError"] is True + text = result["content"][0]["text"] + assert "session_gc" in text + # The message names both possible narrowings, because the agent cannot tell + # them apart and neither is its to change. + assert "--toolsets" in text + assert "authorization" in text + + +def test_a_token_cannot_widen_the_processs_own_toolsets(store): + """The intersection, not the token's list. + + A unit started with `--toolsets frames` must not be talked into serving + `session_start` by a token that names `sessions`. + """ + + _, token = store.mint(toolsets=["frames", "sessions"]) + with TestClient(make_app(store, toolsets=["frames"])) as client: + extra = session(client, token) + listed = call(client, token, "tools/list", headers=extra)["result"]["tools"] + assert {tool["name"] for tool in listed} == set(tools.TOOLSETS["frames"]) + + +def test_two_tokens_on_one_server_see_different_surfaces(store): + """The property the per-token narrowing exists for. + + One process, two callers, two tool budgets. A launch-time flag cannot do + this, which is the whole argument for putting toolsets on the token. + """ + + _, broad = store.mint(label="broad") + _, narrow = store.mint(label="narrow", toolsets=["frames"]) + with TestClient(make_app(store)) as client: + broad_extra = session(client, broad) + narrow_extra = session(client, narrow) + broad_tools = call(client, broad, "tools/list", + headers=broad_extra)["result"]["tools"] + narrow_tools = call(client, narrow, "tools/list", headers=narrow_extra, + request_id=3)["result"]["tools"] + assert len(broad_tools) == len(tools.TOOLS) + assert {tool["name"] for tool in narrow_tools} == set(tools.TOOLSETS["frames"]) + + +def test_resources_are_not_narrowed_by_a_token(store): + """A stated limit, not an oversight. + + `docs/CONTRACT-mcp.md` keeps resources out of `--toolsets` because they are + the host's context rather than the model's budget. A token is an + authorization rather than a budget, so this is a real gap and it is written + down in `docs/TODO/mcp-tokens-do-not-scope-resources.md` rather than + quietly implied by the tests. + """ + + _, token = store.mint(toolsets=["frames"]) + with TestClient(make_app(store)) as client: + extra = session(client, token) + listed = call(client, token, "resources/list", headers=extra)["result"]["resources"] + assert any(entry["uri"] == "hhstream://sessions" for entry in listed) + + +def test_a_token_naming_an_unknown_toolset_offers_nothing(store): + """A grant from a future build: refuse everything rather than widen.""" + + grant, token = store.mint() + grant.toolsets = ("a-family-this-build-has-never-heard-of",) + store._write([grant]) + with TestClient(make_app(store)) as client: + extra = session(client, token) + listed = call(client, token, "tools/list", headers=extra)["result"]["tools"] + assert listed == [] + + +# ── DNS-rebinding protection ─────────────────────────────────────────────── + + +def test_rebinding_protection_refuses_an_unnamed_host(store): + _, token = store.mint() + app = make_app(store, allowed_hosts=["somewhere.else"]) + with TestClient(app) as client: + response = post(client, INITIALIZE, token=token) + # The token was good; the Host was not. 421 Misdirected Request. + assert response.status_code == 421 + + +def test_the_token_is_checked_before_the_host(store): + """Order matters: an unauthenticated caller learns nothing about the host + allowlist, which is itself a hint about how this server is deployed.""" + + store.mint() + app = make_app(store, allowed_hosts=["somewhere.else"]) + with TestClient(app) as client: + assert post(client, INITIALIZE).status_code == 401 + + +@pytest.mark.parametrize("address", ["127.0.0.1", "::1", "localhost"]) +def test_loopback_derives_a_working_allowlist(address): + hosts = http_transport.default_allowed_hosts(address, 9989) + assert "127.0.0.1:9989" in hosts + assert "localhost:9989" in hosts + assert "[::1]:9989" in hosts + # The SDK's wildcard-port form, for a client that reached a proxy on + # another port and was forwarded here. + assert "127.0.0.1:*" in hosts + + +def test_a_named_address_derives_itself_and_not_loopback(): + hosts = http_transport.default_allowed_hosts("10.0.0.5", 9989) + assert hosts == ["10.0.0.5:9989", "10.0.0.5:*", "10.0.0.5"] + + +@pytest.mark.parametrize("address", ["0.0.0.0", "::", "*"]) +def test_a_wildcard_bind_derives_nothing(address): + """Which is what makes the launch path refuse it. + + Nothing can be guessed about the Host a client will send, and an empty + allowlist with protection on refuses every request. So the operator is made + to name the hostnames instead. + """ + + assert http_transport.default_allowed_hosts(address, 9989) == [] + + +# ── the grant on the request ─────────────────────────────────────────────── + + +def test_current_grant_is_none_off_a_request(): + """The stdio case: no request context at all, and no restriction either.""" + + from mcp.server.lowlevel import Server + + assert http_transport.current_grant(Server("probe")) is None + + +def test_offered_for_returns_everything_without_a_grant(): + from mcp.server.lowlevel import Server + + chooser = http_transport.offered_for(Server("probe"), tools.TOOLS) + assert chooser() == tools.TOOLS diff --git a/tests/unit/test_mcp_server.py b/tests/unit/test_mcp_server.py index 56c4348..6d03e81 100644 --- a/tests/unit/test_mcp_server.py +++ b/tests/unit/test_mcp_server.py @@ -520,7 +520,10 @@ def test_a_tool_outside_the_selection_cannot_be_called_by_name(session): assert result.isError is True text = result.content[0].text assert "session_kill" in text - assert "without its toolset" in text + # Both narrowings are named, because on the HTTP transport the token can be + # the one that excluded it and the agent cannot tell from here which it was. + assert "--toolsets" in text + assert "authorization" in text assert fake.calls == [] @@ -575,3 +578,122 @@ def test_content_for_a_text_only_result_has_no_image_block(): blocks = server.content_for(tools.Result(text="hello")) assert [block.type for block in blocks] == ["text"] assert isinstance(blocks[0], types.TextContent) + + +# ── the command line, now that it has subcommands ────────────────────────── +# +# `hhstream-mcp` grew `serve` and `token` beneath it, and the forms that +# existed before have to keep working unchanged: an MCP client's `command` +# entry is a configuration someone else wrote, and a flag that silently became +# a subcommand would break it with a usage error nobody can read from the far +# side of a pipe. + + +@pytest.mark.parametrize( + "argv", + [ + [], + ["--toolsets", "frames"], + ["--toolsets=frames"], + ["serve"], + ["serve", "--toolsets", "frames"], + ], +) +def test_the_pre_subcommand_forms_still_mean_serve_stdio(argv): + args = server.build_parser().parse_args(argv) + assert getattr(args, "command", None) in (None, "serve") + assert getattr(args, "http", False) is False + + +def test_a_toolsets_given_before_the_subcommand_survives_it(): + """argparse copies a subparser's namespace over the top-level one. + + With an ordinary default on the subcommand's copy of `--toolsets`, that + copy would overwrite a value given *before* the subcommand with `None` -- + so `hhstream-mcp --toolsets=frames serve` would silently serve all + twenty-one tools. `SUPPRESS` is what stops that, and this is the test that + notices if it is ever removed. + """ + + args = server.build_parser().parse_args(["--toolsets=frames", "serve"]) + assert args.toolsets == "frames" + + +def test_the_subcommand_wins_when_both_sides_name_it(): + args = server.build_parser().parse_args(["--toolsets=frames", "serve", "--toolsets=keyboard"]) + assert args.toolsets == "keyboard" + + +def test_list_tools_works_on_either_side_of_serve(capsys): + assert server.main(["--list-tools", "--toolsets", "keyboard"]) == 0 + before = capsys.readouterr().out + assert server.main(["serve", "--toolsets", "keyboard", "--list-tools"]) == 0 + assert capsys.readouterr().out == before + + +def test_list_resources_still_works(capsys): + assert server.main(["--list-resources"]) == 0 + out = capsys.readouterr().out + assert "hhstream://status" in out + + +def test_http_is_off_unless_asked_for(): + args = server.build_parser().parse_args(["serve"]) + assert args.http is False + args = server.build_parser().parse_args(["serve", "--http"]) + assert args.http is True + assert args.address == "127.0.0.1" # loopback, not a wildcard + assert args.port == 9989 + + +def test_http_refuses_to_start_with_an_empty_table(tmp_path, monkeypatch): + """A listener that 401s every request is almost always a forgotten mint.""" + + monkeypatch.setenv("HHSTREAM_MCP_STATE_DIR", str(tmp_path / "state")) + with pytest.raises(SystemExit) as exit_info: + server.main(["serve", "--http"]) + assert exit_info.value.code == 2 + + +def test_http_starts_with_an_empty_table_when_told_to(tmp_path, monkeypatch): + """`--allow-no-tokens` is for provisioning the unit before its first mint. + + Patched at `http.serve` rather than actually bound: what is under test is + that the launch path got past its own refusal, with the arguments it was + given. + """ + + monkeypatch.setenv("HHSTREAM_MCP_STATE_DIR", str(tmp_path / "state")) + from hhstream_mcp import http as http_transport + + seen: dict = {} + + def fake_serve(runner, store, **kwargs): + seen.update(kwargs) + + monkeypatch.setattr(http_transport, "serve", fake_serve) + assert server.main(["serve", "--http", "--allow-no-tokens"]) == 0 + assert seen["address"] == "127.0.0.1" + # The derived allowlist, not an empty one: empty would 421 every request. + assert "127.0.0.1:9989" in seen["allowed_hosts"] + + +def test_http_refuses_a_wildcard_bind_with_no_allowed_host(tmp_path, monkeypatch): + monkeypatch.setenv("HHSTREAM_MCP_STATE_DIR", str(tmp_path / "state")) + with pytest.raises(SystemExit) as exit_info: + server.main(["serve", "--http", "--allow-no-tokens", "--address", "0.0.0.0"]) + assert exit_info.value.code == 2 + + +def test_http_accepts_a_wildcard_bind_that_names_its_hosts(tmp_path, monkeypatch): + monkeypatch.setenv("HHSTREAM_MCP_STATE_DIR", str(tmp_path / "state")) + from hhstream_mcp import http as http_transport + + seen: dict = {} + monkeypatch.setattr(http_transport, "serve", lambda runner, store, **kw: seen.update(kw)) + rc = server.main([ + "serve", "--http", "--allow-no-tokens", + "--address", "0.0.0.0", "--allowed-host", "desk.lan:*", + ]) + assert rc == 0 + assert seen["allowed_hosts"] == ["desk.lan:*"]