Skip to content

The agent that grows with you

fix(webapp): open private launch links through a user-only page

unsupportedpastels166bc0f82299
diff --git a/hermes_cli/webapp_launcher.py b/hermes_cli/webapp_launcher.py
index 406e8248b30..aa66301ddd6 100644
--- a/hermes_cli/webapp_launcher.py
+++ b/hermes_cli/webapp_launcher.py
@@ -6,12 +6,18 @@ serves the current profile, asks it for a one-use launch link over the control s
only) and opens that link, so the credential appears in no argv, output or link. On Linux the gateway
checks that the browser's connection is the user's; on Windows nothing checks it, and the link travels
only in the browser launcher's command line, which other standard users cannot read. On macOS, the BSDs
-and WSL neither holds, so it prints the one-use link for the user to open instead.
+and illumos neither holds, so it writes the link into a page only the user can read and opens that page:
+the launcher's command line carries only the page's path. Where it cannot open a browser, and on WSL
+(whose Windows browser reaches the gateway through a relay any Windows account can use), it prints the
+link for the user to open instead.
``--status`` and ``--sign-out`` talk to a running gateway and never start one.
"""
from __future__ import annotations
+import html
import json
+import os
+import secrets
import sys
import time
from pathlib import Path
@@ -88,6 +94,45 @@ def _open(url: str) -> bool:
return False
+# The page a private launch link reaches the browser in: it moves on to the link at once and names nothing
+# else, so the referrer and any script stay out of it.
+_LAUNCH_PAGE = ('<!doctype html><meta charset="utf-8"><meta name="referrer" content="no-referrer">'
+ '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'">'
+ '<meta http-equiv="refresh" content="0;url={url}"><title>Opening Hermes</title>'
+ '<p><a href="{url}">Open Hermes Webapp</a></p>\n')
+
+
+def _open_privately(target: Path, url: str) -> bool:
+ """Open *url*, a launch link nobody checks the redeemer of, in a browser without handing it to the
+ browser launcher, whose command line other local users can read: write it into a page in *target*'s
+ user-only ``webapp`` folder, readable by this OS user alone, and open that page. Pages of earlier
+ launches go first, so at most one is left, and its link stops working within the link's lifetime.
+ False, leaving no page, on WSL (the Windows browser cannot read the page as this user only), when the
+ folder or page cannot be kept user-only, or when no browser opens it."""
+ from gateway.webapp_listener import TOKEN_PATH, _close_to_other_users, _readable_by_other_users
+ from hermes_constants import is_wsl
+ if os.name == "nt" or is_wsl():
+ return False
+ folder = Path(target) / TOKEN_PATH.parent
+ try:
+ folder.mkdir(mode=0o700, parents=True, exist_ok=True)
+ _close_to_other_users(folder)
+ if _readable_by_other_users(folder):
+ return False
+ for earlier in folder.glob("launch-*.html"):
+ earlier.unlink(missing_ok=True)
+ page = folder / f"launch-{secrets.token_hex(8)}.html"
+ fd = os.open(page, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
+ stream.write(_LAUNCH_PAGE.format(url=html.escape(url, quote=True)))
+ except OSError:
+ return False
+ if _open(page.as_uri()):
+ return True
+ page.unlink(missing_ok=True)
+ return False
+
+
def _profile_choice(home: Path, target: Path) -> dict:
"""``{"profile": name}`` when the gateway serves *home* as one of its named profiles, so the
Webapp opens on the profile this command ran for."""
@@ -295,8 +340,12 @@ def cmd_webapp(args) -> int:
print(f"Open the Webapp and sign in with your dashboard account: {link['url']}")
return 0
if link.get("private"):
- # macOS, the BSDs, WSL: nothing checks who redeems this one-use link, so it is for the user to
- # open, never for a browser launcher whose arguments other processes can read.
+ # macOS, the BSDs, illumos, WSL: nothing checks who redeems this one-use link, so it never goes to a
+ # browser launcher, whose arguments other users' processes can read. A page only this user can read
+ # carries it to the browser; failing that, the user opens it by hand.
+ if not args.no_open and _open_privately(target, link["url"]):
+ print("Opened the Webapp in your browser.")
+ return 0
print(f"Open this link in your browser within {link['expires_in_seconds']} seconds. It works "
"once and signs the browser in as you, so keep it private:")
print(f" {link['url']}")
diff --git a/tests/hermes_cli/test_webapp_launcher.py b/tests/hermes_cli/test_webapp_launcher.py
index aa5be9ca680..367868d27b6 100644
--- a/tests/hermes_cli/test_webapp_launcher.py
+++ b/tests/hermes_cli/test_webapp_launcher.py
@@ -417,11 +417,12 @@ def test_the_webapp_command_takes_one_action_at_a_time():
def test_a_link_for_the_user_to_open_by_hand_is_printed_and_never_handed_to_a_browser_launcher(world, capsys):
"""Where the gateway cannot check who redeems a launch link (macOS, the BSDs) it marks the link
- private: the command prints it with its lifetime and never passes it to a browser launcher, whose
- arguments other local users can read."""
+ private. With no browser to carry it there in a user-only page, the command prints it with its
+ lifetime and never passes it to a browser launcher, whose arguments other local users can read."""
world["answers"]["webapp-launch"] = {"ok": True, "result": {"url": LINK, "private": True,
"expires_in_seconds": 60}}
+ world["monkeypatch"].setattr(launcher, "_open", lambda url: world["calls"]["opened"].append(url) and False)
assert launcher.cmd_webapp(_args()) == 0
- assert world["calls"]["opened"] == []
+ assert all("ticket" not in url for url in world["calls"]["opened"])
out = capsys.readouterr().out
assert LINK in out and "keep it private" in out and "60 seconds" in out and "once" in out
diff --git a/tests/hermes_cli/test_webapp_private_launch.py b/tests/hermes_cli/test_webapp_private_launch.py
new file mode 100644
index 00000000000..269544c8ba9
--- /dev/null
+++ b/tests/hermes_cli/test_webapp_private_launch.py
@@ -0,0 +1,99 @@
+"""``hermes webapp`` where nothing checks who redeems a one-use launch link (macOS, the BSDs, illumos, WSL).
+
+The gateway marks such a link private (``gateway.webapp_listener._one_use_links_work``). The command never
+hands it to a browser launcher, whose command line other local users can read, and never prints it when it
+can open a browser: it writes the link into a page in the gateway home's user-only ``webapp`` folder and
+opens that page, so the launcher's command line carries only the page's path. It prints the link only
+where it cannot open a browser (``--no-open``, no graphical browser, a folder it cannot keep user-only)
+and on WSL, whose Windows browser cannot read a page as this user only. These tests simulate those
+hosts on Linux: a real macOS or BSD run is a live check.
+"""
+import html
+import re
+import stat
+from pathlib import Path
+from urllib.parse import unquote, urlsplit
+
+import pytest
+
+from hermes_cli import webapp_launcher as launcher
+from tests.hermes_cli import test_webapp_launcher as launcher_tests
+
+LINK, _args = launcher_tests.LINK, launcher_tests._args
+world = launcher_tests.world # the launcher's recorded side effects, as those tests use them
+
+
+def private(world):
+ world["answers"]["webapp-launch"] = {"ok": True, "result": {"url": LINK, "private": True,
+ "expires_in_seconds": 60}}
+ return world
+
+
+def _pages(world) -> list[Path]:
+ return sorted((world["root"] / "webapp").glob("launch-*.html"))
+
+
+def _page_path(url: str) -> Path:
+ parts = urlsplit(url)
+ assert parts.scheme == "file"
+ return Path(unquote(parts.path))
+
+
+def test_a_private_link_reaches_the_browser_in_a_page_only_the_user_can_read(private, capsys):
+ assert launcher.cmd_webapp(_args()) == 0
+ [opened] = private["calls"]["opened"]
+ assert "ticket" not in opened
+ page = _page_path(opened)
+ assert _pages(private) == [page]
+ assert stat.S_IMODE(page.stat().st_mode) == 0o600
+ assert stat.S_IMODE(page.parent.stat().st_mode) == 0o700
+ refresh = re.search(r'http-equiv="refresh" content="0;url=([^"]*)"', page.read_text(encoding="utf-8"))
+ assert html.unescape(refresh[1]) == LINK
+ out = capsys.readouterr().out
+ assert "Opened the Webapp in your browser" in out and "ticket=" not in out
+
+
+def test_a_folder_other_users_could_read_is_closed_before_the_page_is_written(private):
+ folder = private["root"] / "webapp"
+ folder.mkdir(mode=0o755)
+ folder.chmod(0o755)
+ assert launcher.cmd_webapp(_args()) == 0
+ assert stat.S_IMODE(folder.stat().st_mode) == 0o700
+ assert len(_pages(private)) == 1
+
+
+def test_pages_of_earlier_launches_are_removed(private):
+ folder = private["root"] / "webapp"
+ folder.mkdir(mode=0o700)
+ (folder / "launch-earlier.html").write_text("old", encoding="utf-8")
+ assert launcher.cmd_webapp(_args()) == 0
+ assert [p.name for p in _pages(private)] != ["launch-earlier.html"]
+ assert len(_pages(private)) == 1
+
+
[email protected]("case", ["no-open", "no browser", "wsl", "folder others can read"])
+def test_where_no_user_only_page_can_carry_it_the_link_is_printed_and_no_page_is_left(private, capsys, case):
+ monkeypatch = private["monkeypatch"]
+ if case == "no browser":
+ monkeypatch.setattr(launcher, "_open", lambda url: private["calls"]["opened"].append(url) and False)
+ if case == "wsl":
+ monkeypatch.setattr("hermes_constants.is_wsl", lambda: True)
+ if case == "folder others can read":
+ monkeypatch.setattr("gateway.webapp_listener._readable_by_other_users", lambda path: True)
+ assert launcher.cmd_webapp(_args(no_open=case == "no-open")) == 0
+ assert all("ticket" not in url for url in private["calls"]["opened"])
+ if case != "no browser":
+ assert private["calls"]["opened"] == []
+ assert _pages(private) == []
+ out = capsys.readouterr().out
+ assert LINK in out and "keep it private" in out and "60 seconds" in out
+
+
+def test_a_checked_link_still_goes_straight_to_the_browser(world):
+ """Linux and Windows links (``private: False``) are unchanged: no page, the link itself is opened."""
+ assert launcher.cmd_webapp(_args()) == 0
+ assert world["calls"]["opened"] == [LINK]
+ assert _pages(world) == []
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index b9d0edff7db..8534b2b1e03 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1939,9 +1939,11 @@ The link is valid for 60 seconds and works once; the browser exchanges it for th
that tab. Only your own OS user can get a link: the gateway answers this command over its private
control socket. On Linux the gateway checks that the browser's connection belongs to your OS user; on
Windows it checks nothing, and the link travels only in the browser launcher's command line, which other
-standard users cannot read. On macOS, the BSDs and WSL neither holds, so the command prints the link
-for you to open and never passes it to a browser launcher. Until it is
-used it signs a browser in as you, so keep it private.
+standard users cannot read. On macOS, the BSDs and illumos neither holds, so the command never passes
+the link to a browser launcher: it writes it into a page only your OS user can read
+(`webapp/launch-*.html` in the gateway home) and opens that page. Where it cannot open a browser, and
+on WSL, it prints the link for you to open. Until it is used it signs a browser in as you, so keep it
+private.
For a named profile served by the default gateway (`hermes -p work webapp`), the Webapp opens on that
profile.
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 0e59326e547..30a1f243bcc 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -55,9 +55,11 @@ bare URL shows instructions instead of access: run `hermes webapp` again for a n
Window**, profile windows and session pop-outs hand the sign-in over with their own one-use link. On
Linux the gateway checks that the browser's connection belongs to your OS user; on Windows the link
travels only in the browser launcher's command line, which other standard users cannot read. On macOS,
-the BSDs and WSL (where the Windows browser reaches the gateway through WSL's relay) neither holds, so
-the command prints the one-use link for you to open instead of opening a browser; until it is used it
-signs a browser in as you, so keep it private. `hermes webapp --sign-out` signs out every
+the BSDs and illumos neither holds, so the command writes the link into a page only your OS user can
+read (in the gateway home's `webapp` folder) and opens that page: the launcher sees only its path.
+Where it cannot open a browser (`--no-open`, an SSH session) and on WSL (where the Windows browser
+reaches the gateway through WSL's relay), it prints the one-use link for you to open instead; until it
+is used it signs a browser in as you, so keep it private. `hermes webapp --sign-out` signs out every
tab at once: their open connections close, Bot Desktop viewers included, and each shows the sign-in
instructions. Behind the sign-in gate (below) it also signs out every browser that signed in with a
dashboard account; each must sign in again. The account tokens such a login keeps in its cookies work