# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """The two checks that make a loopback bind actually mean loopback.""" from __future__ import annotations from typing import TYPE_CHECKING import pytest from signal_bot.manage import guard from tests.manage_fixture import BASE_URL, PORT, client_for, deps_at if TYPE_CHECKING: from pathlib import Path @pytest.mark.parametrize( "host", ["127.0.0.1:8140", "localhost:8140", "127.0.0.1", "localhost", "[::1]:8140"], ) def test_a_loopback_host_is_this_machine_asking(host: str) -> None: assert guard.allowed_host(host, PORT) is True @pytest.mark.parametrize( "host", [ # DNS rebinding: the name resolves to 127.0.0.1 by the time the # request is made, but the browser still sends the attacker's host. "evil.example.com", "evil.example.com:8140", # A different port on this machine is a different application. "127.0.0.1:9999", # HTTP/1.1 requires it; something omitting it is not an ordinary # browser and does not get the benefit of the doubt. "", ], ) def test_anything_else_is_refused(host: str) -> None: assert guard.allowed_host(host, PORT) is False def test_a_rebound_request_never_reaches_a_route(tmp_path: Path) -> None: with client_for(deps_at(tmp_path)) as client: answer = client.get("/api/status", headers={"host": "evil.example.com"}) assert answer.status_code == 421 assert "loopback" in answer.json()["reason"] def test_a_cross_origin_form_post_cannot_write_anything(tmp_path: Path) -> None: # A cross-origin