perf(remote): reuse guarded SSH transports and cache static assets

This commit is contained in:
Xubin Ren committed 2026-10-02 11:36:34 +08:00
1 parent 719a5c3fcf
commit 4fd4dc522d
8 files changed
+441 -15

No files matched your search

+23 -2
View File
@@ -144,8 +144,10 @@ nanobot remote revoke DEVICE_ID --ssh-user LOGIN_ACCOUNT
```
Only that device's exact managed key entry is removed; existing login keys stay
unchanged. Close any already-open remote sessions too: removing an authorized
key prevents new SSH authentication, not existing sessions. If setup is cancelled
unchanged. Current pairing bridges also check the grant and its expiry before
each new stream, including streams on a reused SSH transport. Close any
already-open remote sessions too: revocation does not terminate existing streams.
Older bridges enforce the grant only at SSH authentication. If setup is cancelled
after server authorization, use the revoke command printed in that terminal.
Re-pairing after expiry uses a new independent key, not an extension of an old grant.
@@ -256,6 +258,25 @@ these values when it finds the service; otherwise use **Specify a different
location** in the nanobot step. Editing a saved connection also exposes these
fields. The connection does not grant new sudo privileges.
## Connection performance
On macOS and Linux, connections with an app-pinned host key reuse a private
OpenSSH transport instead of authenticating for every HTTP request. Each
connection owns its control socket; nanobot never borrows your shell's shared
SSH session. Disconnecting closes the transport. Windows and unpinned
connections retain the independent-stream path.
Paired connections enable reuse only after the server bridge confirms that it
checks expiry and revocation on every new stream. Older bridges still work with
fresh authentication per stream. Pair again after upgrading the server to install
the guarded bridge; upgrading nanobot alone does not rewrite existing grants.
Versioned public JS/CSS and other build assets are cached in this browser, so
refreshes do not download the same bundle again. HTML, API responses, credentials
and media capabilities remain uncached by the proxy. Initial authentication,
uncached assets and network latency still affect the first connection; reuse
does not bypass a blocked SSH route or VPN policy.
## Using the remote instance
The remote instance's **own complete WebUI** fills the main window. Its UI
+91
View File
@@ -0,0 +1,91 @@
"""An owned OpenSSH master, never a user's shared control socket."""
from __future__ import annotations
import asyncio
import contextlib
import tempfile
from pathlib import Path
class SSHMaster:
"""One authenticated transport per pinned connection, reaped on pause."""
def __init__(self, args: list[str], host: str) -> None:
self.args = args
self.host = host
self._directory: tempfile.TemporaryDirectory[str] | None = None
self._process: asyncio.subprocess.Process | None = None
self._stderr: asyncio.Task[None] | None = None
self._error = bytearray()
self._lock = asyncio.Lock()
async def arguments(self, channel: list[str]) -> list[str]:
from nanobot.webui.remote_ssh import RemoteError, ssh_error
async with self._lock:
if self._process is None or self._process.returncode is not None:
await self.close()
self._directory = tempfile.TemporaryDirectory(prefix="nb-ssh-")
path = str(Path(self._directory.name) / "s")
# Unix-domain socket paths have a small platform-dependent limit.
if len(path.encode()) >= 100:
await self.close()
return channel
self._error.clear()
args = [self.args[0], "-o", "ControlMaster=yes", "-o", f"ControlPath={path}",
"-o", "ControlPersist=no", *self.args[1:], "-N", self.host]
spawn = asyncio.create_task(asyncio.create_subprocess_exec(
*args, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.PIPE,
))
try:
self._process = await asyncio.shield(spawn)
except asyncio.CancelledError:
self._process = await spawn
await self.close()
raise
except BaseException:
await self.close()
raise
process = self._process
assert process is not None
async def errors() -> None:
assert process.stderr is not None
while chunk := await process.stderr.read(4096):
self._error.extend(chunk[:max(0, 8192 - len(self._error))])
self._stderr = asyncio.create_task(errors())
try:
async with asyncio.timeout(20):
while not Path(path).exists():
if process.returncode is not None:
await self._stderr
raise RemoteError(ssh_error(bytes(self._error)))
await asyncio.sleep(0.02)
except TimeoutError:
await self.close()
raise RemoteError("ssh_unreachable") from None
except BaseException:
await self.close()
raise
assert self._directory is not None
# OpenSSH uses the first occurrence. Our private path overrides the
# explicit no-sharing defaults, not host/agent/forwarding safeguards.
return [channel[0], "-S", str(Path(self._directory.name) / "s"), *channel[1:]]
async def close(self) -> None:
from nanobot.webui.remote_ssh import stop_process
if self._process is not None:
await stop_process(self._process)
self._process = None
if self._stderr is not None:
self._stderr.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._stderr
self._stderr = None
if self._directory is not None:
self._directory.cleanup()
self._directory = None
+23 -3
View File
@@ -23,8 +23,23 @@ from nanobot.webui.remote_pairing import PairReceipt, PairRequest, private_write
from nanobot.webui.remote_ssh import RemoteError
# No dynamic command, destination or environment input is accepted by the bridge.
# SSH_ORIGINAL_COMMAND is deliberately ignored. Each invocation is one TCP stream.
_BRIDGE = '''import os, socket, threading
# SSH_ORIGINAL_COMMAND only negotiates the guard marker, never executed.
# Each invocation is one TCP stream to the fixed loopback destination.
_BRIDGE = '''import os, socket, threading, pathlib, sys, time
# A multiplexed SSH transport authenticates only once. Re-check the exact
# managed grant on EVERY new channel, including expiry and operator revocation.
root = pathlib.Path(__file__).resolve().parent
try:
line = (root / "authorization").read_text()
keys = root.parents[1] / "authorized_keys"
valid = line.endswith(" nanobot-remote:" + root.name + "\\n") and line in keys.read_text().splitlines(keepends=True)
except (OSError, ValueError):
valid = False
if not valid or time.time() >= UNTIL:
sys.stderr.write("Permission denied: device authorization expired or revoked\\n")
sys.exit(1)
if os.environ.get("SSH_ORIGINAL_COMMAND") == "nanobot-remote-bridge-v2":
os.write(1, b"NANOBOT_REMOTE_BRIDGE_2\\n")
s = socket.create_connection(("127.0.0.1", PORT), timeout=10)
s.settimeout(None)
def send():
@@ -50,6 +65,11 @@ finally:
'''
def bridge_source(port: int, until: int) -> str:
"""Render only fixed, operator-approved destination and authorization expiry."""
return _BRIDGE.replace("PORT", str(port)).replace("UNTIL", str(until))
def metadata(config: Path) -> dict[str, Any]:
"""Read only the WebUI credential out of the operator-selected config."""
try:
@@ -100,7 +120,7 @@ def write_authorization(home: Path, request: PairRequest, port: int, until: int)
target.mkdir(mode=0o700)
try:
bridge = target / "bridge.py"
private_write(bridge, _BRIDGE.replace("PORT", str(port)).encode())
private_write(bridge, bridge_source(port, until).encode())
command = shlex.join(["/usr/bin/python3", "-I", "-S", str(bridge)]).replace("\\", "\\\\").replace('"', '\\"')
expiry = datetime.datetime.fromtimestamp(until, datetime.UTC).strftime("%Y%m%d%H%M%SZ")
line = f'restrict,expiry-time="{expiry}",command="{command}" {request.ssh_key} nanobot-remote:{request.id}\n'
+10
View File
@@ -31,6 +31,7 @@ from nanobot.webui.remote_ssh import Tunnel, _listen # pyright: ignore[reportPr
_MAX_BYTES = 64 * 1024 * 1024
_MAX_CAPABILITIES = 10000
_STATIC_ASSET = re.compile(r"/assets/[^/]+-[A-Za-z0-9_-]{8,}\.(?:js|css|woff2?|ttf|svg|png|webp|ico)$")
_MEDIA_PATH = r"/api/media/[A-Za-z0-9_-]{22}/[A-Za-z0-9_-]+"
# Consume absolute URLs unchanged before matching gateway-relative media paths.
# An external site's similarly named route is not this proxy's capability.
@@ -307,6 +308,15 @@ class RemoteProxy:
outgoing = {key: value for key, value in upstream.headers.items()
if key.lower() in _RESPONSE_HEADERS}
outgoing["Cache-Control"] = "no-store"
upstream_cache = upstream.headers.get("cache-control", "").lower()
if (upstream.status_code == 200 and _STATIC_ASSET.fullmatch(path)
and not request.rel_url.query and "set-cookie" not in upstream.headers
and "public" in upstream_cache and "immutable" in upstream_cache
and "no-store" not in upstream_cache and "private" not in upstream_cache
and "application/json" not in upstream.headers.get("content-type", "")):
# Only versioned public build assets, never HTML, API data,
# credentials or media capabilities. Keep caches browser-local.
outgoing["Cache-Control"] = "private, max-age=31536000, immutable"
if "application/json" in upstream.headers.get("content-type", ""):
body = bytearray()
async for chunk in upstream.aiter_bytes():
+60 -5
View File
@@ -20,6 +20,10 @@ from typing import Any, cast
from pydantic import BaseModel, ConfigDict, Field, field_validator
from nanobot.webui.remote_mux import SSHMaster
_BRIDGE_READY = b"NANOBOT_REMOTE_BRIDGE_2\n"
class RemoteError(Exception):
"""A stable, non-secret error code for the connection UI."""
@@ -53,7 +57,7 @@ def transport_arguments(profile: RemoteProfile, remote_port: int, known_hosts: P
if isinstance(profile, PairedSSHProfile):
# The server key's forced command owns the fixed destination. Do not
# request forwarding or execute the ordinary credential probe.
return [*args, profile.host, "nanobot-remote-bridge"]
return [*args, profile.host, "nanobot-remote-bridge-v2"]
return [*args, "-W", f"127.0.0.1:{remote_port}", profile.host]
@@ -269,13 +273,26 @@ class Tunnel:
self.enabled = True
self.error = ""
self._streams: set[asyncio.Task[None]] = set()
self._master: SSHMaster | None = None
self._master_args: tuple[list[str], str] | None = None
self._paired = False
self._reuse_verified = False
self._probe_started = False
# Leave room below OpenSSH's usual MaxSessions=10, including a live WS.
self._slots = asyncio.Semaphore(8)
@property
def active(self) -> bool:
return self.enabled and self.server is not None and self.server.is_serving()
def resume(self, profile: RemoteProfile, remote_port: int, known_hosts: Path) -> None:
def resume(self, profile: RemoteProfile, remote_port: int, known_hosts: Path | None) -> None:
self.args = transport_arguments(profile, remote_port, known_hosts)
self._paired = isinstance(profile, PairedSSHProfile)
self._master_args = ((ssh_arguments(profile, known_hosts), profile.host)
if os.name != "nt" and known_hosts and known_hosts.is_file() else None)
self._master = SSHMaster(*self._master_args) if self._master_args else None
self._reuse_verified = not self._paired
self._probe_started = False
self.error = ""
self.enabled = True
@@ -294,9 +311,14 @@ class Tunnel:
task.add_done_callback(finished)
async def _relay(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
async with self._slots:
await self._stream(reader, writer)
async def _stream(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
process: asyncio.subprocess.Process | None = None
pumps: list[asyncio.Task[None]] = []
stderr = bytearray()
master: SSHMaster | None = None
async def copy(source: asyncio.StreamReader, destination: asyncio.StreamWriter) -> None:
while data := await source.read(65536):
@@ -310,10 +332,16 @@ class Tunnel:
stderr.extend(data[:max(0, 8192 - len(stderr))])
try:
if self._master and (self._reuse_verified or not self._probe_started):
# The first channel follows fresh SSH authentication. Only a
# guarded bridge can authorize MORE channels on that transport.
master = self._master
self._probe_started = True
args = await master.arguments(self.args) if master else self.args
# Shield process creation so cancellation cannot lose a spawned child
# before we have its handle and can reap it.
spawn = asyncio.create_task(asyncio.create_subprocess_exec(
*self.args, stdin=asyncio.subprocess.PIPE,
*args, stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
))
try:
@@ -323,8 +351,25 @@ class Tunnel:
raise
assert process is not None
assert process.stdin is not None and process.stdout is not None and process.stderr is not None
async def response() -> None:
assert process is not None and process.stdout is not None
if self._paired:
first = await process.stdout.readline()
if first == _BRIDGE_READY:
# Only the guarded bridge advertises this capability.
# Old bridges forward HTTP unchanged: keep authenticating
# every stream until the server bridge is upgraded.
self._reuse_verified = True
if self._master_args and self._master is None:
self._master = SSHMaster(*self._master_args)
else:
self._reuse_verified = False
writer.write(first)
await writer.drain()
await copy(process.stdout, writer)
pumps = [asyncio.create_task(copy(reader, process.stdin)),
asyncio.create_task(copy(process.stdout, writer)),
asyncio.create_task(response()),
asyncio.create_task(drain_errors(process.stderr))]
done, _ = await asyncio.wait(pumps[:2], return_when=asyncio.FIRST_COMPLETED)
for task in done:
@@ -338,7 +383,9 @@ class Tunnel:
await pumps[2]
if process.returncode:
self.error = ssh_error(bytes(stderr))
except (OSError, ConnectionError):
except RemoteError as exc:
self.error = str(exc)
except (OSError, ConnectionError, ValueError):
self.error = "ssh_unreachable"
finally:
for task in pumps:
@@ -346,6 +393,10 @@ class Tunnel:
await asyncio.gather(*pumps, return_exceptions=True)
if process is not None:
await stop_process(process)
if master is not None and not self._reuse_verified:
await master.close()
if self._master is master:
self._master = None
writer.close()
with contextlib.suppress(OSError):
await writer.wait_closed()
@@ -356,6 +407,9 @@ class Tunnel:
for task in streams:
task.cancel()
await asyncio.gather(*streams, return_exceptions=True)
if self._master is not None:
await self._master.close()
self._master = None
async def close(self) -> None:
await self.pause()
@@ -403,6 +457,7 @@ async def open_tunnel(
listener = _listen(local_port, excluded_ports or set())
tunnel = Tunnel(args, int(listener.getsockname()[1]))
try:
tunnel.resume(profile, remote_port, known_hosts)
tunnel.server = await asyncio.start_server(tunnel.accept, sock=listener)
return tunnel
except BaseException:
+179
View File
@@ -0,0 +1,179 @@
"""Private SSH master lifetime and guarded-bridge compatibility."""
import asyncio
import os
import sys
from pathlib import Path
from unittest.mock import AsyncMock
import pytest
from nanobot.webui import remote_mux, remote_ssh
from nanobot.webui.remote_mux import SSHMaster
from nanobot.webui.remote_ssh import PairedSSHProfile, RemoteError
@pytest.fixture
def master_child(monkeypatch):
real_spawn = asyncio.create_subprocess_exec
children, commands = [], []
state = {"fail": False, "gate": None, "started": asyncio.Event()}
async def spawn(*args, **kwargs):
commands.append(args)
path = next(arg.split("=", 1)[1] for arg in args if arg.startswith("ControlPath="))
script = ("import sys;sys.stderr.write('Permission denied');sys.exit(255)" if state["fail"] else
"import socket,sys,time;s=socket.socket(socket.AF_UNIX);s.bind(sys.argv[1]);s.listen();time.sleep(120)")
child = await real_spawn(sys.executable, "-u", "-c", script, path, **kwargs)
children.append(child)
state["started"].set()
if state["gate"] is not None:
await state["gate"].wait()
return child
monkeypatch.setattr(remote_mux.asyncio, "create_subprocess_exec", spawn)
return state, children, commands
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
async def test_parallel_channels_share_only_owned_master_and_close_cleans_it(master_child):
_, children, commands = master_child
master = SSHMaster(["ssh", "-o", "ControlMaster=no", "-o", "ControlPath=none"], "pinned-host")
channel = ["ssh", "-o", "ControlPath=none", "-W", "127.0.0.1:8765", "pinned-host"]
paths = []
try:
results = await asyncio.gather(*(master.arguments(channel) for _ in range(8)))
assert len(children) == 1
paths = [Path(result[2]) for result in results]
assert len(set(paths)) == 1 and paths[0].exists()
assert paths[0].parent.stat().st_mode & 0o777 == 0o700
assert commands[0][-2:] == ("-N", "pinned-host")
assert "ControlPersist=no" in commands[0]
assert all(result[3:] == channel[1:] for result in results)
await master.close()
assert children[0].returncode is not None
assert not paths[0].parent.exists()
renewed = await master.arguments(channel)
assert renewed[2] != str(paths[0]) and len(children) == 2
finally:
await master.close()
assert all(child.returncode is not None for child in children)
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
async def test_dead_master_reauthenticates_and_does_not_share_other_connections(master_child):
_, children, _ = master_child
first = SSHMaster(["ssh"], "host")
second = SSHMaster(["ssh"], "host")
channel = ["ssh", "host", "bridge"]
try:
original = await first.arguments(channel)
isolated = await second.arguments(channel)
assert original[2] != isolated[2]
children[0].terminate()
await children[0].wait()
renewed = await first.arguments(channel)
assert len(children) == 3
assert renewed[2] not in (original[2], isolated[2])
assert not Path(original[2]).parent.exists()
assert children[1].returncode is None
assert await second.arguments(channel) == isolated
finally:
await first.close()
await second.close()
assert all(child.returncode is not None for child in children)
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
async def test_long_socket_path_falls_back_without_starting_a_master(tmp_path, monkeypatch, master_child):
_, children, _ = master_child
directory = tmp_path / ("long-" * 25)
directory.mkdir()
monkeypatch.setattr(remote_mux.tempfile, "tempdir", str(directory))
master = SSHMaster(["ssh"], "host")
channel = ["ssh", "host", "bridge"]
assert await master.arguments(channel) == channel
assert master._directory is None
assert children == []
assert list(directory.iterdir()) == []
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
async def test_failed_authentication_is_not_hidden_by_fallback(master_child):
state, children, _ = master_child
state["fail"] = True
master = SSHMaster(["ssh"], "host")
with pytest.raises(RemoteError, match="ssh_auth_failed"):
await master.arguments(["ssh", "host", "bridge"])
assert master._directory is None
assert children[0].returncode == 255
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
async def test_cancel_during_master_spawn_reaps_process_and_socket(master_child):
state, children, _ = master_child
state["gate"] = asyncio.Event()
master = SSHMaster(["ssh"], "host")
task = asyncio.create_task(master.arguments(["ssh", "host", "bridge"]))
await state["started"].wait()
task.cancel()
state["gate"].set()
with pytest.raises(asyncio.CancelledError):
await task
assert master._directory is None
assert all(child.returncode is not None for child in children)
@pytest.mark.parametrize("guarded", [False, True])
@pytest.mark.parametrize("loses_guard", [False, True])
async def test_paired_tunnel_reuses_only_after_guarded_bridge_marker(tmp_path, monkeypatch, guarded, loses_guard):
real_spawn = asyncio.create_subprocess_exec
known = tmp_path / "known_hosts"
known.write_text("pinned fixture")
masters = []
class Master:
def __init__(self, *args):
self.arguments = AsyncMock(side_effect=lambda channel: channel)
self.close = AsyncMock()
masters.append(self)
monkeypatch.setattr(remote_ssh, "SSHMaster", Master)
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")
children = []
script = (f"import os\nos.write(1, {remote_ssh._BRIDGE_READY!r})\n" if guarded else "import os\n")
script += "while data := os.read(0,65536):\n os.write(1,data)\n"
async def spawn(*args, **kwargs):
source = script
if loses_guard and len(children) >= 1:
source = "import os\nwhile data := os.read(0,65536):\n os.write(1,data)\n"
child = await real_spawn(sys.executable, "-u", "-c", source, **kwargs)
children.append(child)
return child
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
profile = PairedSSHProfile(name="Fixture", host="fixture.test")
tunnel = await remote_ssh.open_tunnel(profile, 8765, known)
try:
for _ in range(3):
reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)
writer.write(b"HTTP/1.1 200 OK\r\nbody")
await writer.drain()
writer.write_eof()
assert await asyncio.wait_for(reader.read(), 5) == b"HTTP/1.1 200 OK\r\nbody"
writer.close()
await writer.wait_closed()
if guarded and os.name != "nt":
assert len(masters) == 1
assert masters[0].arguments.await_count == (2 if loses_guard else 3)
elif os.name != "nt":
assert len(masters) == 1
assert masters[0].arguments.await_count == 1
else:
assert masters == []
finally:
await tunnel.close()
assert all(child.returncode is not None for child in children)
if masters:
masters[0].close.assert_awaited_once()
+33 -5
View File
@@ -176,11 +176,12 @@ def test_paired_transport_cannot_fall_back_to_generic_probe_or_forwarding(pair,
assert args[1:3] == ["-F", os.devnull]
transport = transport_arguments(profile, value.port, store.path(request.id) / "known_hosts")
assert "-W" not in transport
assert transport[-1] == "nanobot-remote-bridge"
assert transport[-1] == "nanobot-remote-bridge-v2"
assert "sudo" not in " ".join(transport)
def test_fixed_bridge_streams_only_to_baked_in_loopback_port():
@pytest.mark.parametrize("command", ["echo MUST-NOT-EXECUTE", "nanobot-remote-bridge-v2"])
def test_fixed_bridge_streams_only_to_baked_in_loopback_port(tmp_path, command):
# Real bidirectional bytes, no SSH_ORIGINAL_COMMAND interpolation.
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
@@ -196,12 +197,39 @@ def test_fixed_bridge_streams_only_to_baked_in_loopback_port():
connection.sendall(b"received:" + data)
worker = threading.Thread(target=serve, daemon=True)
worker.start()
result = subprocess.run([sys.executable, "-I", "-S", "-c", remote_pair_server._BRIDGE.replace("PORT", str(port))],
target = tmp_path / ".ssh" / "nanobot-remote" / "device"
target.mkdir(parents=True)
line = "restrict fixture-key nanobot-remote:device\n"
(target / "authorization").write_text(line)
(tmp_path / ".ssh" / "authorized_keys").write_text(line)
bridge = target / "bridge.py"
bridge.write_text(remote_pair_server.bridge_source(port, int(time.time()) + 60))
result = subprocess.run([sys.executable, "-I", "-S", str(bridge)],
input=b"hello-webui", capture_output=True, timeout=5,
env={**os.environ, "SSH_ORIGINAL_COMMAND": "echo MUST-NOT-EXECUTE"})
env={**os.environ, "SSH_ORIGINAL_COMMAND": command})
worker.join(2)
assert result.returncode == 0
assert result.stdout == b"received:hello-webui"
prefix = remote_ssh._BRIDGE_READY if command == "nanobot-remote-bridge-v2" else b""
assert result.stdout == prefix + b"received:hello-webui"
@pytest.mark.parametrize("reason", ["expired", "revoked", "missing", "another-device"])
def test_guarded_bridge_rejects_new_channels_without_connecting(tmp_path, reason):
target = tmp_path / ".ssh" / "nanobot-remote" / "device"
target.mkdir(parents=True)
line = "restrict fixture-key nanobot-remote:device\n"
(target / "authorization").write_text(line)
keys = tmp_path / ".ssh" / "authorized_keys"
keys.write_text(line if reason == "expired" else line.replace(":device", ":other") if reason == "another-device" else "")
if reason == "missing":
keys.unlink()
bridge = target / "bridge.py"
bridge.write_text(remote_pair_server.bridge_source(1, int(time.time()) + (-1 if reason == "expired" else 60)))
result = subprocess.run([sys.executable, "-I", "-S", str(bridge)], capture_output=True, timeout=5,
env={**os.environ, "SSH_ORIGINAL_COMMAND": "nanobot-remote-bridge-v2"})
assert result.returncode == 1
assert not result.stdout # No reuse capability or connection to the target.
assert b"Permission denied" in result.stderr
async def test_api_pair_finalization_pins_host_and_hides_credentials(tmp_path):
+22
View File
@@ -44,6 +44,15 @@ async def remote(tmp_path, monkeypatch):
async def process(connection, request):
seen.append(request)
path = urlsplit(request.path).path
if path.startswith("/assets/"):
response = connection.respond(200, "fixture asset")
response.headers["Content-Type"] = "application/javascript"
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:
response.headers["Set-Cookie"] = "session=private"
return response
if path == "/redirect" or (state.ws_redirect and path == config.path):
response = connection.respond(302, "redirect")
response.headers["Location"] = "http://127.0.0.1:1/?token=" + ROOT
@@ -118,6 +127,19 @@ async def bootstrap(remote, headers=None):
return response.json()
@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),
])
async def test_cache_only_versioned_public_build_assets(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 "set-cookie" not in response.headers
async def test_remote_credentials_never_leave_the_backend(remote):
first, second = await asyncio.gather(bootstrap(remote), bootstrap(remote))
assert first["token"] != second["token"]