Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/loop_link/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ The package needs a token. It reads the `GEOVIEWER_TOKEN` environment
variable. If this variable is not set, it uses the token that the viewer
saved.

The link is not encrypted. For a host that is not on this computer
(`Viewer(host=...)` with an address that is not loopback), the package does
not use the saved token and does not read the instance files of the local
viewer. Give the token with `token=` or `GEOVIEWER_TOKEN`. The package gives
a warning, because the token and the data go over the network as plain text.

## Example

```python
Expand Down
17 changes: 14 additions & 3 deletions packages/loop_link/src/loop_link/_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ class WebSocketClient:

def __init__(self, sock: socket.socket) -> None:
self._sock = sock
self._buffer = b""
self._buffer = bytearray()
self._partial = False
self._fragmenting = False
self._fragment_opcode = OP_BINARY
Expand Down Expand Up @@ -198,7 +198,7 @@ def _handshake(self, host: str, port: int, token: str, path: str) -> None:
except OSError as error:
raise WebSocketError(f"The handshake failed: {error}") from error
head, _, rest = data.partition(b"\r\n\r\n")
self._buffer = rest
self._buffer = bytearray(rest)
status_line, *header_lines = head.decode("latin-1").split("\r\n")
parts = status_line.split(" ", 2)
status = parts[1] if len(parts) > 1 else ""
Expand Down Expand Up @@ -245,6 +245,10 @@ def _send_frame(self, opcode: int, payload: bytes) -> None:
# This includes a timeout: part of the frame can be sent, so the stream is broken.
self._abort()
raise WebSocketError(f"Cannot send to the viewer: {error}") from error
except BaseException:
# For example Ctrl-C: part of the frame can be sent, so the stream is broken.
self._abort()
raise

def send_binary(self, data: bytes) -> None:
"""Send one binary message.
Expand Down Expand Up @@ -284,8 +288,10 @@ def _read_exactly(self, count: int) -> bytes:
if not chunk:
self.closed = True
raise WebSocketClosed("The viewer closed the connection.")
# A bytearray grows in place: bytes concatenation made large frames quadratic.
self._buffer += chunk
data, self._buffer = self._buffer[:count], self._buffer[count:]
data = bytes(self._buffer[:count])
del self._buffer[:count]
return data

def _read_frame(self, wait: float | None) -> tuple[bool, int, bytes]:
Expand Down Expand Up @@ -401,6 +407,11 @@ def receive(self, timeout: float) -> bytes | None:
except OSError as error:
self._abort()
raise WebSocketError(f"Cannot read from the viewer: {error}") from error
except BaseException:
# For example Ctrl-C in the middle of a frame: the next read would be misaligned.
if self._partial:
self._abort()
raise

def _check_open(self) -> None:
"""Raise ``WebSocketClosed`` if the connection is closed."""
Expand Down
39 changes: 31 additions & 8 deletions packages/loop_link/src/loop_link/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@

from __future__ import annotations

import ipaddress
import json
import math
import os
import socket
import sys
from dataclasses import dataclass
import warnings
from dataclasses import dataclass, field
from pathlib import Path

from loop_link.errors import NoViewerError, TokenError
Expand Down Expand Up @@ -40,7 +42,16 @@ class ViewerAddress:

host: str
port: int
token: str
token: str = field(repr=False)


def _is_loopback(host: str) -> bool:
if host.lower() == "localhost":
return True
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False


def settings_dir() -> Path:
Expand Down Expand Up @@ -75,13 +86,14 @@ def _file_token(settings: Path) -> str:
return ""


def _resolve_token(token: str | None, settings: Path) -> str:
def _resolve_token(token: str | None, settings: Path, local: bool) -> str:
if token:
return token
env_token = os.environ.get("GEOVIEWER_TOKEN")
if env_token:
return env_token
file_token = _file_token(settings)
# The saved token belongs to the viewer on this computer: never send it to another host.
file_token = _file_token(settings) if local else ""
if file_token:
return file_token
raise TokenError(_TOKEN_TEXT)
Expand All @@ -100,7 +112,8 @@ def _find_port(settings: Path, host: str, timeout: float) -> int:
live: list[tuple[tuple[bool, int], int]] = []
folder = settings / "instances"
try:
files = sorted(folder.glob("*.json"))
# The instance files list the ports of the viewers on this computer only.
files = sorted(folder.glob("*.json")) if _is_loopback(host) else []
except OSError:
files = []
for path in files:
Expand Down Expand Up @@ -143,9 +156,12 @@ def find_viewer(
function does not check it and does not read the instance files.
token : str, optional
The access token. If not given, the function reads the
``GEOVIEWER_TOKEN`` environment variable, then ``link.json``.
``GEOVIEWER_TOKEN`` environment variable, then ``link.json``. For a
host that is not loopback, it does not read ``link.json``.
host : str
The host of the viewer.
The host of the viewer. For a host that is not loopback, the function
does not read the instance files and gives a warning, because the link
is not encrypted.
settings : pathlib.Path, optional
The settings folder. The default is :func:`settings_dir`.
timeout : float
Expand All @@ -164,7 +180,14 @@ def find_viewer(
If no viewer is running.
"""
folder = settings if settings is not None else settings_dir()
resolved = _resolve_token(token, folder)
local = _is_loopback(host)
if not local:
warnings.warn(
f"The link to {host} is not encrypted: the token and the data are sent in plain text.",
UserWarning,
stacklevel=2,
)
resolved = _resolve_token(token, folder, local)
if port is not None:
return ViewerAddress(host=host, port=port, token=resolved)
return ViewerAddress(host=host, port=_find_port(folder, host, timeout), token=resolved)
7 changes: 5 additions & 2 deletions packages/loop_link/src/loop_link/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ def __init__(
@property
def connected(self) -> bool:
"""True while the connection is open."""
return self._client is not None
client = self._client
return client is not None and not client.closed

def connect(self) -> ToolConnection:
"""Connect to the ``/tool`` path of the viewer. No ``hello`` is sent.
Expand Down Expand Up @@ -247,8 +248,10 @@ def post(self, build: Callable[[int], bytes]) -> int:

def _connect_locked(self) -> WebSocketClient:
"""Return the open client, or open one. The caller holds the lock."""
if self._client is not None:
if self._client is not None and not self._client.closed:
return self._client
# A client closes itself after a broken send: drop it and open a new one.
self._drop_locked()
if self._resolve is not None:
address = self._resolve()
else:
Expand Down
10 changes: 6 additions & 4 deletions packages/loop_link/src/loop_link/viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ def scene_crs(self) -> str:
@property
def connected(self) -> bool:
"""True while the connection is open."""
return self._client is not None and not self._dead
client = self._client
return client is not None and not client.closed and not self._dead

@property
def tool_connected(self) -> bool:
Expand Down Expand Up @@ -1252,9 +1253,10 @@ def _ensure_connected(self) -> None:
raise ViewerClosedError
if self._client is None:
self.connect()
elif self._dead:
# The last connection failed: open a new one. If the viewer is gone, give
# the error of a closed viewer, as the failed send did.
elif self._dead or self._client.closed:
# The last connection failed, or the client closed itself after a broken send:
# open a new one. If the viewer is gone, give the error of a closed viewer, as
# the failed send did.
try:
self.connect()
except NoViewerError as error:
Expand Down
43 changes: 43 additions & 0 deletions packages/loop_link/tests/test_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,3 +290,46 @@ def test_non_finite_focused_counts_as_zero(tmp_path, listeners):
(tmp_path / "instances" / "222.json").write_text(text, encoding="utf-8")
address = find_viewer(settings=tmp_path)
assert address.port == good_port


# A host that is not loopback


REMOTE = "203.0.113.5"


def test_remote_host_does_not_get_the_saved_token(tmp_path):
write_link(tmp_path)
with pytest.warns(UserWarning, match="not encrypted"), pytest.raises(TokenError):
find_viewer(port=4321, host=REMOTE, settings=tmp_path)


def test_remote_host_uses_explicit_or_env_token(tmp_path, monkeypatch):
write_link(tmp_path)
with pytest.warns(UserWarning, match="not encrypted"):
assert find_viewer(port=1, token="given", host=REMOTE, settings=tmp_path).token == "given"
monkeypatch.setenv("GEOVIEWER_TOKEN", "env-token")
with pytest.warns(UserWarning, match="not encrypted"):
assert find_viewer(port=1, host=REMOTE, settings=tmp_path).token == "env-token"


def test_remote_host_skips_instance_files(tmp_path, monkeypatch):
write_instance(tmp_path, 111, 5555)
probed: list[tuple[str, int]] = []
monkeypatch.setattr(
discovery, "_is_alive", lambda host, port, timeout: probed.append((host, port)) or False
)
with pytest.warns(UserWarning), pytest.raises(NoViewerError):
find_viewer(token="given", host=REMOTE, settings=tmp_path)
assert probed == [(REMOTE, DEFAULT_PORT)]


@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "127.1.2.3", "::1"])
def test_loopback_host_uses_saved_token_without_warning(tmp_path, host, recwarn):
write_link(tmp_path)
assert find_viewer(port=1, host=host, settings=tmp_path).token == "file-token"
assert not recwarn.list


def test_viewer_address_repr_hides_the_token():
assert "secret" not in repr(ViewerAddress(host="h", port=1, token="secret"))
30 changes: 30 additions & 0 deletions packages/loop_link/tests/test_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,36 @@ def test_socket_closed_in_the_middle_of_a_request(
assert viewer.tool_connections == 2


def test_post_after_interrupted_post_reconnects(
connection: ToolConnection, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A Ctrl-C in the middle of a frame closes the client, so the next post opens a new one."""
connection.connect()
first = connection._client
real = first._sock

class Interrupted:
# The second sendall of a frame is the body: stop there, after the head went out.
calls = 0

def __getattr__(self, name: str) -> Any:
return getattr(real, name)

def sendall(self, data: bytes) -> None:
Interrupted.calls += 1
if Interrupted.calls == 2:
raise KeyboardInterrupt
real.sendall(data)

monkeypatch.setattr(first, "_sock", Interrupted())
with pytest.raises(KeyboardInterrupt):
connection.post(encode.selection_get_frame)
assert not connection.connected
connection.post(encode.selection_get_frame)
assert connection._client is not first
assert connection.connected


def test_wrong_token_gives_token_error(direct: Callable[..., ToolConnection]) -> None:
with FakeViewer() as viewer:
tool = direct(viewer, token="wrong")
Expand Down
32 changes: 32 additions & 0 deletions packages/loop_link/tests/test_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,3 +625,35 @@ def test_send_after_heartbeat_failure_reconnects(fake_viewer: Any, viewer_factor
viewer.send(small_points(), id="after")
assert viewer.connected
assert viewer.flush() == []


def test_send_after_interrupted_send_reconnects(
fake_viewer: Any, viewer_factory: FACTORY, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A Ctrl-C in the middle of a frame closes the client, so the next send opens a new one."""
viewer = viewer_factory()
viewer.connect()
first = viewer._client
real = first._sock

class Interrupted:
# The second sendall of a frame is the body: stop there, after the head went out.
calls = 0

def __getattr__(self, name: str) -> Any:
return getattr(real, name)

def sendall(self, data: bytes) -> None:
Interrupted.calls += 1
if Interrupted.calls == 2:
raise KeyboardInterrupt
real.sendall(data)

monkeypatch.setattr(first, "_sock", Interrupted())
with pytest.raises(KeyboardInterrupt):
viewer.send(small_points(), id="before")
assert not viewer.connected
viewer.send(small_points(), id="after")
assert viewer._client is not first
assert viewer.connected
assert viewer.flush() == []
Loading
Loading