feat(remote): serve local WebUI with an explicit host contract
This commit is contained in:
1 parent
02ce0cfb6f
commit
5aa91b66cc
14 files changed
+489
-59
No files matched your search
@@ -0,0 +1,59 @@
|
||||
"""Published package versions never substitute for wire compatibility."""
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.webui.client_contract import assess_webui_contract, compatibility_error, webui_contract
|
||||
|
||||
|
||||
def test_initial_host_declaration_is_an_independent_wire_fixture():
|
||||
# Frozen initial host payload; intentionally not built using the current producer.
|
||||
initial_host = {
|
||||
"version": "0.3.5",
|
||||
"min_protocol": 1,
|
||||
"max_protocol": 1,
|
||||
"capabilities": ["webui.core.v1"],
|
||||
}
|
||||
assert assess_webui_contract(initial_host)["status"] == "compatible"
|
||||
|
||||
|
||||
def test_current_producer_remains_acceptable_to_initial_client():
|
||||
# Initial client's advertised requirement, independent of today's constants.
|
||||
contract = webui_contract()
|
||||
assert contract["min_protocol"] <= 1 <= contract["max_protocol"]
|
||||
assert "webui.core.v1" in contract["capabilities"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", ["0.0.1", "9.99.0", "0.3.5.dev17", "custom-build"])
|
||||
def test_independently_released_hosts_share_a_protocol(version):
|
||||
report = assess_webui_contract({**webui_contract(), "version": version})
|
||||
assert report["status"] == "compatible"
|
||||
assert report["host_version"] == version
|
||||
assert compatibility_error(report) == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [None, {}, "1", {"min_protocol": True, "max_protocol": 1},
|
||||
{"min_protocol": 2, "max_protocol": 1, "capabilities": []},
|
||||
{"min_protocol": 1, "max_protocol": 1, "capabilities": "webui.core.v1"},
|
||||
{"min_protocol": 1, "max_protocol": 1, "capabilities": [123]},
|
||||
])
|
||||
def test_missing_or_malformed_metadata_is_unknown_not_outdated(value):
|
||||
report = assess_webui_contract(value)
|
||||
assert report["status"] == "unknown"
|
||||
assert compatibility_error(report) == "webui_compatibility_unknown"
|
||||
|
||||
|
||||
def test_new_host_can_explicitly_retain_old_protocol_support():
|
||||
assert assess_webui_contract({**webui_contract(), "max_protocol": 2})["status"] == "compatible"
|
||||
|
||||
|
||||
def test_recovery_targets_the_correct_machine():
|
||||
future = {**webui_contract(), "min_protocol": 2, "max_protocol": 2}
|
||||
assert compatibility_error(assess_webui_contract(future)) == "client_update_required"
|
||||
missing = {**webui_contract(), "capabilities": []}
|
||||
assert compatibility_error(assess_webui_contract(missing)) == "host_update_required"
|
||||
|
||||
|
||||
def test_unknown_optional_capabilities_do_not_break_connection():
|
||||
value = webui_contract()
|
||||
value["capabilities"] = ["webui.core.v1", "a-future-optional-feature"]
|
||||
assert assess_webui_contract(value)["status"] == "compatible"
|
||||
@@ -7,6 +7,7 @@ from websockets.datastructures import Headers
|
||||
from websockets.http11 import Request
|
||||
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui.client_contract import gateway_identity
|
||||
from nanobot.webui.gateway_tokens import GatewayTokenStore
|
||||
from nanobot.webui.ws_http import GatewayHTTPHandler
|
||||
|
||||
@@ -22,9 +23,7 @@ def test_terminal_probe_is_private_stable_and_does_not_issue_credentials():
|
||||
for _ in range(3):
|
||||
response = handler._handle_bootstrap(connection, request, terminal_probe=True)
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body) == {
|
||||
"protocolVersion": 1, "gatewayId": handler.tokens.instance_id,
|
||||
}
|
||||
assert json.loads(response.body) == gateway_identity(handler.tokens.instance_id)
|
||||
assert "no-store" in response.headers["Cache-Control"]
|
||||
assert not handler.tokens.api_tokens and not handler.tokens.issued_tokens
|
||||
assert GatewayTokenStore().instance_id != handler.tokens.instance_id
|
||||
@@ -16,6 +16,7 @@ from websockets.http11 import Request
|
||||
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui import remote_instances, remote_ssh
|
||||
from nanobot.webui.client_contract import webui_contract
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
from nanobot.webui.remote_instances import RemoteInstances
|
||||
from nanobot.webui.remote_proxy import RemoteProxy
|
||||
@@ -48,13 +49,13 @@ def ssh(monkeypatch):
|
||||
probe = AsyncMock(return_value={"port": 8765, "secret": "private-webui-secret", "hostname": "team-host"})
|
||||
monkeypatch.setattr(remote_ssh, "probe", probe)
|
||||
monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=tunnel))
|
||||
state = {"status": 200, "identity": {"protocolVersion": 1, "gatewayId": "remote-one"}}
|
||||
state = {"status": 200, "identity": {"protocolVersion": 1, "gatewayId": "remote-one", "webui": webui_contract()}}
|
||||
|
||||
def respond(request):
|
||||
if request.url.path == "/webui/terminal":
|
||||
assert request.headers["X-Nanobot-Auth"] == "private-webui-secret"
|
||||
return httpx.Response(state["status"], json=state["identity"])
|
||||
return httpx.Response(200, text="<!doctype html><title>nanobot</title>", headers={"content-type": "text/html"})
|
||||
raise AssertionError(f"A data-only host must not be asked for a frontend: {request.url.path}")
|
||||
|
||||
real_client = httpx.AsyncClient
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs))
|
||||
@@ -69,6 +70,48 @@ async def test_save_survives_restart_without_credentials(manager):
|
||||
await save(manager, private_key="must-never-save")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("contract,code", [
|
||||
(None, "webui_compatibility_unknown"),
|
||||
({**webui_contract(), "min_protocol": 2, "max_protocol": 2}, "client_update_required"),
|
||||
({**webui_contract(), "capabilities": []}, "host_update_required"),
|
||||
])
|
||||
async def test_contract_failure_keeps_profile_and_reports_correct_update_target(manager, ssh, contract, code):
|
||||
key = await save(manager)
|
||||
ssh.state["identity"]["webui"] = contract
|
||||
with pytest.raises(RemoteError, match=code):
|
||||
await manager.action("connect", {"id": key})
|
||||
RemoteProxy.open.assert_not_awaited()
|
||||
ssh.tunnel.close.assert_awaited_once()
|
||||
snapshot = manager.snapshot()
|
||||
assert len(snapshot["profiles"]) == 1
|
||||
assert snapshot["profiles"][0]["connection_error"] == code
|
||||
assert not snapshot["profiles"][0]["connected"]
|
||||
assert snapshot["profiles"][0]["compatibility"]["status"] != "compatible"
|
||||
assert not manager.connections
|
||||
|
||||
|
||||
async def test_server_upgrade_rechecks_compatibility_without_new_pairing(manager, ssh):
|
||||
key = await save(manager)
|
||||
ssh.state["identity"].pop("webui")
|
||||
with pytest.raises(RemoteError, match="webui_compatibility_unknown"):
|
||||
await manager.action("connect", {"id": key})
|
||||
saved = manager.path.read_text(encoding="utf-8")
|
||||
ssh.state["identity"]["webui"] = {**webui_contract(), "version": "9.0.0"}
|
||||
await manager.action("connect", {"id": key})
|
||||
assert manager.snapshot()["profiles"][0]["compatibility"]["status"] == "compatible"
|
||||
# The stable saved host remains; only its reserved local origin is added.
|
||||
assert set(json.loads(manager.path.read_text(encoding="utf-8"))) == set(json.loads(saved))
|
||||
|
||||
|
||||
async def test_host_contract_change_invalidates_live_proxy(manager, ssh):
|
||||
key = await save(manager)
|
||||
await manager.action("connect", {"id": key})
|
||||
ssh.state["identity"]["webui"] = {**webui_contract(), "capabilities": []}
|
||||
await manager.health()
|
||||
ssh.proxy.pause.assert_awaited_once()
|
||||
assert manager.snapshot()["profiles"][0]["connection_error"] == "host_update_required"
|
||||
|
||||
|
||||
async def test_new_local_manager_has_new_view_identity_for_same_remote(manager, ssh):
|
||||
key = await save(manager)
|
||||
first = await manager.action("connect", {"id": key})
|
||||
@@ -531,16 +574,19 @@ async def test_old_profile_origin_is_remembered_before_first_edit(manager, ssh):
|
||||
assert RemoteInstances(manager.path.parent)._remember_origins({}) == {23456}
|
||||
|
||||
|
||||
async def test_legacy_transparent_origin_is_not_reused(manager, ssh):
|
||||
@pytest.mark.parametrize("proxy_origin", [False, True])
|
||||
async def test_legacy_transparent_or_remote_code_origin_is_not_reused(manager, ssh, proxy_origin):
|
||||
key = await save(manager)
|
||||
old = json.loads(manager.path.read_text())
|
||||
old[key]["local_port"] = 12345
|
||||
old[key]["proxy_origin"] = proxy_origin
|
||||
manager.path.write_text(json.dumps(old))
|
||||
await manager.action("connect", {"id": key})
|
||||
kwargs = RemoteProxy.open.call_args.kwargs
|
||||
assert kwargs["local_port"] == 0
|
||||
assert 12345 in kwargs["excluded_ports"]
|
||||
assert json.loads(manager.path.read_text())[key]["proxy_origin"] is True
|
||||
assert json.loads(manager.path.read_text())[key]["local_client_origin"] is True
|
||||
assert "proxy_origin" not in manager.snapshot()["profiles"][0]
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,9 @@ from websockets.http11 import Request
|
||||
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui import remote_ssh
|
||||
from nanobot.webui.client_contract import webui_contract
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
from nanobot.webui.local_client_assets import LocalClientAssets
|
||||
from nanobot.webui.remote_proxy import RemoteProxy
|
||||
from nanobot.webui.remote_ssh import RemoteProfile, open_tunnel
|
||||
|
||||
@@ -31,6 +33,13 @@ MEDIA = "/api/media/AAAAAAAAAAAAAAAAAAAAAA/remoteFilePayload"
|
||||
|
||||
@pytest.fixture
|
||||
async def remote(tmp_path, monkeypatch):
|
||||
assets = tmp_path / "local-dist"
|
||||
assets.mkdir()
|
||||
(assets / "index.html").write_text("<!doctype html><title>Local nanobot</title>", encoding="utf-8")
|
||||
(assets / "assets").mkdir()
|
||||
for name in ["index-AbcD1234.js", "index-AbcD1234.css", "index.js"]:
|
||||
(assets / "assets" / name).write_text("local client asset", encoding="utf-8")
|
||||
monkeypatch.setattr("nanobot.webui.remote_proxy.LocalClientAssets", lambda: LocalClientAssets(assets))
|
||||
config = WebSocketConfig(host="127.0.0.1", token_issue_secret=ROOT, path="/custom/ws")
|
||||
services = build_gateway_services(
|
||||
config=config, bus=MagicMock(), session_manager=None, static_dist_path=None,
|
||||
@@ -39,8 +48,10 @@ async def remote(tmp_path, monkeypatch):
|
||||
runtime_surface="browser", runtime_capabilities_overrides=None,
|
||||
)
|
||||
seen, children = [], []
|
||||
# Frozen initial wire declaration: current client vs an independently defined host.
|
||||
state = SimpleNamespace(block=asyncio.Event(), entered=asyncio.Event(), ws_redirect=False,
|
||||
asset_cache="public, max-age=31536000, immutable")
|
||||
contract={"version": "0.3.5", "min_protocol": 1, "max_protocol": 1,
|
||||
"capabilities": ["webui.core.v1"]})
|
||||
|
||||
async def process(connection, request):
|
||||
seen.append(request)
|
||||
@@ -48,7 +59,7 @@ async def remote(tmp_path, monkeypatch):
|
||||
if path.startswith("/assets/"):
|
||||
response = connection.respond(200, "fixture asset")
|
||||
response.headers["Content-Type"] = "application/javascript"
|
||||
response.headers["Cache-Control"] = state.asset_cache
|
||||
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||||
if "private" in request.path:
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
if "cookie" in request.path:
|
||||
@@ -75,7 +86,14 @@ async def remote(tmp_path, monkeypatch):
|
||||
response.headers["Content-Type"] = "image/png"
|
||||
response.headers["Content-Range"] = "bytes 0-4/10"
|
||||
return response
|
||||
return await services.endpoint.process_request(connection, request, is_allowed=lambda _: True)
|
||||
response = await services.endpoint.process_request(connection, request, is_allowed=lambda _: True)
|
||||
if path == "/webui/bootstrap" and response.status_code == 200:
|
||||
payload = json.loads(response.body)
|
||||
payload["terminal"]["webui"] = state.contract
|
||||
response.body = json.dumps(payload).encode()
|
||||
del response.headers["Content-Length"]
|
||||
response.headers["Content-Length"] = str(len(response.body))
|
||||
return response
|
||||
|
||||
async def messages(ws):
|
||||
assert ws in services.endpoint.webui_connections
|
||||
@@ -130,29 +148,65 @@ async def bootstrap(remote, headers=None):
|
||||
|
||||
@pytest.mark.parametrize("path,cacheable", [
|
||||
("/assets/index-AbcD1234.js", True), ("/assets/index-AbcD1234.css", True),
|
||||
("/assets/private-AbcD1234.js", False), ("/assets/cookie-AbcD1234.js", False),
|
||||
("/assets/index-AbcD1234.js?token=secret", False), ("/assets/config.json", False),
|
||||
("/assets/index.js", False), ("/assets/index-AbcD1234.html", False),
|
||||
("/assets/index.js", False), ("/", False),
|
||||
])
|
||||
async def test_cache_only_versioned_public_build_assets(remote, path, cacheable):
|
||||
async def test_only_local_assets_are_served_and_versioned_files_cached(remote, path, cacheable):
|
||||
response = await remote.client.get(remote.proxy.origin + path)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["cache-control"] == ("private, max-age=31536000, immutable" if cacheable else "no-store")
|
||||
assert response.headers["cache-control"] == ("private, max-age=31536000, immutable" if cacheable else "no-cache")
|
||||
assert response.headers["x-nanobot-ui"] == "local"
|
||||
assert "set-cookie" not in response.headers
|
||||
assert remote.seen == []
|
||||
assert "local" in response.text.lower()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("directive", ["no-cache", 'no-cache="Content-Type"', "must-revalidate"])
|
||||
async def test_proxy_preserves_upstream_asset_revalidation(remote, directive):
|
||||
remote.state.asset_cache = f"public, max-age=0, immutable, {directive}"
|
||||
response = await remote.client.get(remote.proxy.origin + "/assets/index-AbcD1234.js")
|
||||
assert response.status_code == 200
|
||||
assert response.headers["cache-control"] == "no-store"
|
||||
@pytest.mark.parametrize("path", ["/assets/remote-only-AbcD1234.js", "/auth/callback", "/missing",
|
||||
"/assets/%2e%2e/config.json", "/assets/%2e%2e/%2e%2e/config.json", "/assets/foo%5cbar.js"])
|
||||
async def test_missing_local_files_never_fall_back_to_remote_html_or_code(remote, path):
|
||||
assert (await remote.client.get(remote.proxy.origin + path)).status_code == 404
|
||||
assert remote.seen == []
|
||||
|
||||
|
||||
async def test_proxy_does_not_extend_upstream_asset_freshness(remote):
|
||||
remote.state.asset_cache = "public, max-age=60, immutable"
|
||||
response = await remote.client.get(remote.proxy.origin + "/assets/index-AbcD1234.js")
|
||||
assert response.headers["cache-control"] == "private, max-age=60, immutable"
|
||||
async def test_static_symlink_cannot_escape_local_bundle(remote, tmp_path):
|
||||
outside = tmp_path / "private.js"
|
||||
outside.write_text("not a UI asset", encoding="utf-8")
|
||||
link = remote.proxy.assets.directory / "assets" / "escape.js"
|
||||
try:
|
||||
link.symlink_to(outside)
|
||||
except OSError:
|
||||
pytest.skip("This platform does not permit unprivileged symlinks")
|
||||
assert (await remote.client.get(remote.proxy.origin + "/assets/escape.js")).status_code == 404
|
||||
assert remote.seen == []
|
||||
|
||||
|
||||
async def test_compressed_sibling_cannot_escape_local_bundle(remote, tmp_path):
|
||||
outside = tmp_path / "private.gz"
|
||||
outside.write_bytes(b"not a UI asset")
|
||||
link = remote.proxy.assets.directory / "assets" / "index.js.gz"
|
||||
try:
|
||||
link.symlink_to(outside)
|
||||
except OSError:
|
||||
pytest.skip("This platform does not permit unprivileged symlinks")
|
||||
response = await remote.client.get(remote.proxy.origin + "/assets/index.js", headers={
|
||||
"Accept-Encoding": "gzip",
|
||||
})
|
||||
assert response.status_code == 404
|
||||
assert remote.seen == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("contract,error", [
|
||||
(None, "webui_compatibility_unknown"),
|
||||
({**webui_contract(), "min_protocol": 2, "max_protocol": 2}, "client_update_required"),
|
||||
({**webui_contract(), "capabilities": []}, "host_update_required"),
|
||||
])
|
||||
async def test_bootstrap_rechecks_contract_before_issuing_local_credentials(remote, contract, error):
|
||||
remote.state.contract = contract
|
||||
response = await remote.client.get(remote.proxy.origin + "/webui/bootstrap",
|
||||
headers={"X-Nanobot-Auth": remote.proxy.secret})
|
||||
assert response.status_code == 409
|
||||
assert response.json()["error"] == error
|
||||
assert "token" not in response.json() and ROOT not in response.text
|
||||
assert not remote.proxy._api and not remote.proxy._ws
|
||||
|
||||
|
||||
async def test_remote_credentials_never_leave_the_backend(remote):
|
||||
@@ -237,13 +291,16 @@ async def test_signed_media_wrapped_over_http_and_websocket_and_range_preserved(
|
||||
response = await remote.client.get(remote.proxy.origin + local, headers={"Range": "bytes=0-4"})
|
||||
assert response.status_code == 206 and response.content == b"bytes"
|
||||
assert response.headers["content-range"] == "bytes 0-4/10"
|
||||
assert response.headers["x-content-type-options"] == "nosniff"
|
||||
assert response.headers["content-security-policy"].startswith("sandbox;")
|
||||
assert "allow-scripts" not in response.headers["content-security-policy"]
|
||||
assert remote.seen[-1].headers["Range"] == "bytes=0-4"
|
||||
assert (await remote.client.get(remote.proxy.origin + MEDIA)).status_code == 401
|
||||
|
||||
|
||||
async def test_http_and_websocket_redirects_cannot_disclose_credentials(remote):
|
||||
response = await remote.client.get(remote.proxy.origin + "/redirect")
|
||||
assert response.status_code == 502
|
||||
assert response.status_code == 404
|
||||
assert ROOT not in response.text and "location" not in response.headers
|
||||
assert "set-cookie" not in response.headers
|
||||
remote.state.ws_redirect = True
|
||||
|
||||
Reference in new issue
Block a user