From b7be116f8b775ff0d123278d06ab69333d7a4e18 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Mon, 23 Nov 2026 23:58:49 +0000 Subject: [PATCH 01/14] [PROD-871] gumloop browser proxy link keeps this computer connected in the background Co-authored-by: Cursor --- README.md | 14 + docs/client-capabilities.md | 1 + src/gumloop/_version.py | 2 +- src/gumloop/cli/commands/auth.py | 27 +- src/gumloop/cli/commands/browser.py | 4 +- src/gumloop/cli/commands/custom_proxy.py | 430 ++++++++++++++++ src/gumloop/cli/custom_proxy_key.py | 72 ++- src/gumloop/cli/custom_proxy_lock.py | 43 ++ src/gumloop/cli/custom_proxy_service.py | 201 ++++++++ .../skills/gumloop-cli/references/commands.md | 12 +- src/gumloop/linked_proxy/connection.py | 115 +++-- src/gumloop/linked_proxy/tls_check.py | 38 ++ src/gumloop/types.py | 2 + tests/cli/test_custom_proxy_command.py | 461 ++++++++++++++++++ tests/cli/test_custom_proxy_key.py | 48 +- tests/cli/test_custom_proxy_service.py | 101 ++++ tests/linked_proxy/test_connection.py | 226 +++++++-- tests/linked_proxy/test_tls_check.py | 68 +++ 18 files changed, 1771 insertions(+), 94 deletions(-) create mode 100644 src/gumloop/cli/commands/custom_proxy.py create mode 100644 src/gumloop/cli/custom_proxy_lock.py create mode 100644 src/gumloop/cli/custom_proxy_service.py create mode 100644 src/gumloop/linked_proxy/tls_check.py create mode 100644 tests/cli/test_custom_proxy_command.py create mode 100644 tests/cli/test_custom_proxy_service.py create mode 100644 tests/linked_proxy/test_tls_check.py diff --git a/README.md b/README.md index 8aa43fa..4f8bf21 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,20 @@ curl -fsSL https://gumloop.com/cli/import-logins.sh | sh Cookies only: local storage and IndexedDB stay on your machine, so sites that keep the session there ask the agent to sign in once, after which the agent's browser keeps it. Imported cookies are encrypted with the profile's own key before storage and are never shown back in the UI or API; sign-ins the agent picks up while running are saved back to the same profile. Rename, remove sites from, or delete profiles on the Secrets page in Gumloop. +### Let your agents' browser go out through this computer + +Sites that only accept sign-ins from your network or your IP can be reached by linking this computer: your agents' browser connects to them from here. On macOS or Linux, after `gumloop login`: + +```bash +gumloop browser proxy link # automatically runs in the background on startup +gumloop browser proxy status +gumloop browser proxy unlink +``` + +On Linux without a systemd user session, such as a container, `link` can't run it in the background. Run `gumloop browser proxy connect` and keep it open instead. + +The computer only opens connections to public addresses on ports 80 and 443. Its key stays in the OS keychain. `gumloop logout` unlinks it. A network that inspects TLS traffic can't be used, since sites would show the agent's browser certificate errors. + ### Sync a folder into your Brain Mirror a local directory into a file-upload Brain source. Files are compared by name and sha256, so a re-run uploads only what changed; indexing starts on its own after each upload. diff --git a/docs/client-capabilities.md b/docs/client-capabilities.md index 872c2e5..10a9d90 100644 --- a/docs/client-capabilities.md +++ b/docs/client-capabilities.md @@ -22,6 +22,7 @@ The feature parity audit adds client adapters over existing APIs and selected ba | Company Brain search and uploaded-file sources | `client.brain` | `gumloop brain` | | Generated file metadata, downloads, rename, delete, versions, and sharing | `client.artifacts` | `gumloop artifacts` | | Personal browser profile CRUD and existing listing/cookie import | `client.browser_profiles` | `gumloop browser` | +| Linking this computer for agents' browser traffic | `client.custom_proxies` (list, register, set default and delete) | `gumloop browser proxy` | | Connected Brain source inspection, sync history, issues, indexed children, and sync requests | `client.brain` | `gumloop brain sources` | | Integration trigger catalog, account selection/configuration, and run history | `client.agents` trigger methods | `gumloop agents triggers` | | Team and organization membership discovery | `client.teams.list`, `client.organizations.list` | `gumloop teams list`, `gumloop organizations list` | diff --git a/src/gumloop/_version.py b/src/gumloop/_version.py index e4db625..62ec344 100644 --- a/src/gumloop/_version.py +++ b/src/gumloop/_version.py @@ -1,3 +1,3 @@ from __future__ import annotations -__version__ = "0.5.16" +__version__ = "0.5.17" diff --git a/src/gumloop/cli/commands/auth.py b/src/gumloop/cli/commands/auth.py index d217d52..bab1a1e 100644 --- a/src/gumloop/cli/commands/auth.py +++ b/src/gumloop/cli/commands/auth.py @@ -4,12 +4,15 @@ from typing import Annotated from typing import Literal +import httpx import questionary import typer +from rich.markup import escape as escape_markup from rich.prompt import Prompt from gumloop import Gumloop from gumloop import GumloopError +from gumloop.cli.commands.custom_proxy import remove_custom_proxy from gumloop.cli.console import console from gumloop.cli.console import print_json from gumloop.cli.context import CliContext @@ -18,6 +21,7 @@ from gumloop.cli.credentials import keyring_backend_name from gumloop.cli.credentials import save_credentials from gumloop.cli.errors import exit_with_error +from gumloop.cli.custom_proxy_key import backend_host from gumloop.cli.oauth import DEFAULT_REDIRECT_PORT from gumloop.cli.oauth import perform_oauth_login from gumloop.cli.oauth import revoke_oauth_token @@ -202,9 +206,17 @@ def logout( typer.Option("--json", help="Print the result as JSON."), ] = False, ) -> None: - """Clear stored Gumloop credentials.""" + """Clear stored Gumloop credentials, and unlink this computer.""" cli: CliContext = ctx.obj + # Before the revoke, which would leave no login to delete the personal proxy with. + custom_proxy_removed = False + custom_proxy_error: str | None = None + try: + custom_proxy_removed = remove_custom_proxy(cli, backend_host(cli.effective_base_url)) + except (GumloopError, httpx.HTTPError) as error: + custom_proxy_error = str(error) + # Server-side revoke first so the refresh token can't outlive the # local logout. Revoke failures never block the local clear. oauth_revoked = False @@ -220,9 +232,15 @@ def logout( clear_credentials() - payload: dict[str, object] = {"status": "ok", "oauth_revoked": oauth_revoked} + payload: dict[str, object] = { + "status": "ok", + "oauth_revoked": oauth_revoked, + "custom_proxy_removed": custom_proxy_removed, + } if revoke_failed: payload["oauth_revoke_failed"] = True + if custom_proxy_error is not None: + payload["custom_proxy_remove_failed"] = True if json_output: print_json(payload) @@ -234,3 +252,8 @@ def logout( "[yellow]Note:[/yellow] could not reach the server to revoke the refresh token; " "it will remain valid until it expires." ) + if custom_proxy_error is not None: + console.print( + "[yellow]Note:[/yellow] could not unlink this computer " + f"({escape_markup(custom_proxy_error)}). Log in again and run `gumloop browser proxy unlink`." + ) diff --git a/src/gumloop/cli/commands/browser.py b/src/gumloop/cli/commands/browser.py index 3681af2..74fdb45 100644 --- a/src/gumloop/cli/commands/browser.py +++ b/src/gumloop/cli/commands/browser.py @@ -20,6 +20,7 @@ from gumloop.browser_logins.chromium_cookies import KeychainAccessError from gumloop.cli.commands._confirmation import Yes from gumloop.cli.commands._confirmation import confirm_or_exit +from gumloop.cli.commands.custom_proxy import proxy_app from gumloop.cli.console import console from gumloop.cli.console import print_json from gumloop.cli.context import CliContext @@ -30,12 +31,13 @@ from gumloop.types import BrowserProfileImportSummary browser_app = typer.Typer( - help="Bring your browser sign-ins to Gumloop agents.", + help="Bring your browser sign-ins, and this computer's network, to Gumloop agents.", no_args_is_help=True, rich_markup_mode="rich", ) profiles_app = typer.Typer(help="Manage browser profiles.", no_args_is_help=True, rich_markup_mode="rich") browser_app.add_typer(profiles_app, name="profiles") +browser_app.add_typer(proxy_app, name="proxy") def _pick_local_profile(browser: str | None, browser_profile: str | None, *, non_interactive: bool) -> LocalProfile: diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py new file mode 100644 index 0000000..25f837b --- /dev/null +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -0,0 +1,430 @@ +from __future__ import annotations + +import asyncio +import base64 +import json +import os +import socket +import sys +from datetime import datetime +from datetime import timezone +from typing import Annotated + +import httpx +import keyring.errors +import typer +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from pydantic import ValidationError +from rich.markup import escape as escape_markup + +from gumloop import APIStatusError +from gumloop import GumloopError +from gumloop._client import DEFAULT_BASE_URL +from gumloop._version import __version__ +from gumloop.cli.console import console +from gumloop.cli.console import error_console +from gumloop.cli.console import print_json +from gumloop.cli.context import CliContext +from gumloop.cli.credentials import Credentials +from gumloop.cli.credentials import load_credentials +from gumloop.cli.custom_proxy_key import CustomProxyConnectionStatus +from gumloop.cli.custom_proxy_key import CustomProxyRegistration +from gumloop.cli.custom_proxy_key import backend_host +from gumloop.cli.custom_proxy_key import forget +from gumloop.cli.custom_proxy_key import forget_connection_status +from gumloop.cli.custom_proxy_key import forget_registration +from gumloop.cli.custom_proxy_key import load_connection_status +from gumloop.cli.custom_proxy_key import load_or_create_key +from gumloop.cli.custom_proxy_key import load_registration +from gumloop.cli.custom_proxy_key import save_connection_status +from gumloop.cli.custom_proxy_key import save_registration +from gumloop.cli.custom_proxy_lock import custom_proxy_lock +from gumloop.cli.custom_proxy_lock import is_running +from gumloop.cli.custom_proxy_service import CustomProxyService +from gumloop.cli.custom_proxy_service import NoBackgroundService +from gumloop.cli.custom_proxy_service import gumloop_executable +from gumloop.cli.custom_proxy_service import service_for_current_platform +from gumloop.cli.errors import exit_with_error +from gumloop.linked_proxy.connection import GatewayConnection +from gumloop.linked_proxy.connection import GatewayTokenUnavailable +from gumloop.linked_proxy.connection import SignedOut +from gumloop.linked_proxy.connection import SignInRefused +from gumloop.linked_proxy.destinations import Target +from gumloop.linked_proxy.sign_in import public_key_text +from gumloop.linked_proxy.tls_check import TlsInspected +from gumloop.linked_proxy.tls_check import check_tls_not_inspected +from gumloop.types import CustomProxyGatewayToken + +proxy_app = typer.Typer( + help="Let your agents' browser go out to the internet through this computer.", + no_args_is_help=True, + rich_markup_mode="rich", +) + +_NAME_MAX_LENGTH = 100 +_CREDENTIAL_OVERRIDES = ("GUMLOOP_ACCESS_TOKEN", "GUMLOOP_API_KEY", "GUMLOOP_USER_ID") +_ROLE_DENIED = "Your organization's roles don't allow you to use personal proxies. Ask an admin to turn them on." +# Why this member can't use personal proxies right now, keyed by Gumloop API error code. +_UNAVAILABLE_REASONS = { + "policy_denied": _ROLE_DENIED, + "organization_permission_required": _ROLE_DENIED, + "insufficient_permissions": _ROLE_DENIED, + "tier_required_enterprise": "Personal proxies need an Enterprise plan.", + "route_not_found": "Personal proxies aren't available for your organization yet.", +} +# The only refusal that forgets the registration. +_REMOVED = "personal_custom_proxy_not_found" + + +@proxy_app.command( + "link", + epilog="Examples:\n gumloop browser proxy link\n gumloop browser proxy link --name 'Office desktop'", +) +def link( + ctx: typer.Context, + name: Annotated[ + str | None, + typer.Option( + "--name", help="Name for this computer in Gumloop when it is first linked. Default: its hostname." + ), + ] = None, +) -> None: + """Link this computer and keep it connected in the background, also after a restart.""" + cli: CliContext = ctx.obj + host = backend_host(cli.effective_base_url) + try: + if not _signed_in(host): + raise GumloopError(f"Run `gumloop login` first. Linking this computer needs a stored login for {host}.") + # The background service runs as the stored login, so it couldn't connect a computer added as anyone else. + overrides = [variable for variable in _CREDENTIAL_OVERRIDES if os.environ.get(variable)] + if overrides: + raise GumloopError( + f"Linking this computer can't use {', '.join(overrides)}. " + "Save the login with `gumloop login`, then retry." + ) + try: + service: CustomProxyService | None = service_for_current_platform() + except NoBackgroundService: + service = None + executable = gumloop_executable() if service is not None else None + check_tls_not_inspected() + key = load_or_create_key(host) + registration = load_registration(host) + if registration is not None and _is_someone_else(registration, _stored_credentials()): + raise GumloopError( + "This computer is linked to another Gumloop user. Run `gumloop browser proxy unlink`, then link again." + ) + if registration is None or registration.public_key != public_key_text(key): + _register(cli, host, key, name) + if service is not None and executable is not None: + service.install(executable) + except TlsInspected as error: + exit_with_error(_tls_inspected_error(error)) + except (GumloopError, ValidationError) as error: + exit_with_error(_explained(error)) + + if service is None: + console.print( + "It can't stay connected in the background: this computer has no systemd user session. " + "Run `gumloop browser proxy connect` and keep it open, for example in tmux." + ) + return + console.print("[green]Connected.[/green] Your agents' browser now goes out through this computer.") + if sys.platform.startswith("linux"): + console.print("[dim]It connects when you log in, once your keyring is unlocked.[/dim]") + + +@proxy_app.command("status") +def status( + ctx: typer.Context, + json_output: Annotated[bool, typer.Option("--json", help="Print the status as JSON.")] = False, +) -> None: + """Show whether this computer is linked and whether it is connected.""" + cli: CliContext = ctx.obj + host = backend_host(cli.effective_base_url) + registration = load_registration(host) + service = _service_or_none() + service_installed = service is not None and service.is_installed() + running = registration is not None and is_running(host) + connection = load_connection_status(host) if running else None + if registration is None: + state = None + elif not running: + state = "not_running" + else: + state = "connected" if connection and connection.connected else "connecting" + if json_output: + print_json( + { + "backend": host, + "custom_proxy_id": registration.custom_proxy_id if registration else None, + "name": registration.name if registration else None, + "service_installed": service_installed, + "state": state, + "since": connection.since.isoformat() if connection else None, + "last_error": connection.last_error if connection else None, + } + ) + return + + if registration is None: + console.print("This computer is not linked. Run `gumloop browser proxy link`.") + return + prefix = f'"{escape_markup(registration.name)}"' + if not running: + start = "link" if service is not None else "connect" + console.print(f"{prefix}: not running. Run `gumloop browser proxy {start}` to start.") + elif connection and connection.connected: + console.print(f"{prefix}: connected since {_clock_time(connection.since)}.") + elif connection and connection.last_error: + console.print(f"{prefix}: connecting. Last attempt failed: {escape_markup(connection.last_error)}.") + else: + console.print(f"{prefix}: connecting.") + + +@proxy_app.command("unlink") +def unlink(ctx: typer.Context) -> None: + """Unlink this computer from Gumloop, and delete its key from this computer.""" + cli: CliContext = ctx.obj + host = backend_host(cli.effective_base_url) + try: + removed = remove_custom_proxy(cli, host) + except (GumloopError, httpx.HTTPError) as error: + exit_with_error(_explained(error)) + if removed: + console.print("Unlinked this computer and deleted its key.") + else: + console.print("This computer is not linked.") + + +def remove_custom_proxy(cli: CliContext, host: str) -> bool: + """Returns whether there was a personal proxy to unlink. When Gumloop can't + delete it, the key and registration stay so the removal can be retried.""" + login_host = _login_host(_stored_credentials()) + service_still_needed = login_host != host and load_registration(login_host) is not None + service = None if service_still_needed else _service_or_none() + registration = load_registration(host) + service_installed = service is not None and service.is_installed() + if service is not None and service_installed: + service.remove() + if registration is not None: + custom_proxy_id = registration.custom_proxy_id + try: + cli.call_with_refresh(lambda client: client.custom_proxies.delete(custom_proxy_id)) + except APIStatusError as error: + if error.status_code != 404: + raise + forget(host) + return service_installed or registration is not None + + +@proxy_app.command("connect") +def connect( + ctx: typer.Context, + verbose: Annotated[ + bool, + typer.Option("--verbose", "-v", help="Show more detail while connected."), + ] = False, +) -> None: + """Keep this computer connected from this terminal until you stop it with Ctrl-C.""" + # The background service runs this too. A clean exit means the service should stay down. + cli: CliContext = ctx.obj + host = backend_host(cli.effective_base_url) + try: + with custom_proxy_lock(host): + registration = load_registration(host) + if registration is None: + error_console.print("This computer is not linked. Run `gumloop browser proxy link`.") + return + key = load_or_create_key(host) + if registration.public_key != public_key_text(key): + forget_registration(host) + error_console.print( + "This computer's personal proxy key is gone from the OS keychain. " + "Run `gumloop browser proxy link` to link it again." + ) + return + check_tls_not_inspected() + announced = False + + def on_connected() -> None: + nonlocal announced + _record_connection(host, connected=True) + if not announced: + announced = True + console.print( + "[green]Connected.[/green] Agents can now send browser traffic through this computer. " + "Press Ctrl-C to stop." + ) + + connection = GatewayConnection( + gateway_url=registration.gateway_url, + linked_proxy_id=registration.custom_proxy_id, + key=key, + signed_in=lambda: _owner_login(host, registration) is not None, + gateway_token=lambda: _gateway_token(host, registration), + on_open=_print_destination if verbose else None, + on_connected=on_connected, + on_failed=lambda error: _record_connection(host, connected=False, last_error=error), + ) + _record_connection(host, connected=False) + try: + asyncio.run(connection.run()) + finally: + forget_connection_status(host) + except TlsInspected as error: + exit_with_error(_tls_inspected_error(error)) + except SignInRefused as refusal: + if refusal.reason == _REMOVED: + forget_registration(host) + error_console.print( + "This computer was unlinked from Gumloop. Run `gumloop browser proxy link` to link it again." + ) + else: + reason = _UNAVAILABLE_REASONS.get(refusal.reason, "You can't use personal proxies right now.") + error_console.print( + f"{reason} This computer disconnected. Run `gumloop browser proxy link` once that changes." + ) + except SignedOut: + if _signed_in(host): + error_console.print( + "You logged in to Gumloop as someone else, so this computer disconnected. " + "Log back in as the person who linked it, or run `gumloop browser proxy unlink` and link it again." + ) + else: + error_console.print("You logged out of Gumloop, so this computer disconnected.") + except KeyboardInterrupt: + console.print("Stopped.") + except GumloopError as error: + exit_with_error(error) + + +def _signed_in(host: str) -> bool: + """A stored login for this backend. Logging out, or in to another backend, stops the personal proxy.""" + credentials = _stored_credentials() + return credentials.has_any and _login_host(credentials) == host + + +def _stored_credentials() -> Credentials: + try: + return load_credentials() + except keyring.errors.KeyringError as error: + raise GumloopError(f"Could not read your Gumloop login from the OS keychain: {error}") from error + + +def _login_host(credentials: Credentials) -> str: + """The backend the background service serves, whatever overrides the current command has.""" + return backend_host(credentials.base_url or DEFAULT_BASE_URL) + + +def _owner_login(host: str, registration: CustomProxyRegistration) -> Credentials | None: + """The stored login, while it is for this backend and not someone other than who linked this computer.""" + credentials = _stored_credentials() + if not credentials.has_any or _login_host(credentials) != host or _is_someone_else(registration, credentials): + return None + return credentials + + +def _is_someone_else(registration: CustomProxyRegistration, credentials: Credentials) -> bool: + """Only when both users are known: another user's gateway token request answers personal_custom_proxy_not_found.""" + login_user_id = _login_user_id(credentials) + return None not in (registration.user_id, login_user_id) and login_user_id != registration.user_id + + +def _login_user_id(credentials: Credentials) -> str | None: + """Read from the access token without verifying it, which only tells logins apart.""" + if credentials.auth_method == "api_key": + return credentials.user_id + if not credentials.access_token: + return None + try: + payload = credentials.access_token.split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + except (IndexError, ValueError): + return None + subject = claims.get("sub") if isinstance(claims, dict) else None + return subject if isinstance(subject, str) else None + + +def _gateway_token(host: str, registration: CustomProxyRegistration) -> CustomProxyGatewayToken: + """Only the codes that say the personal proxy is gone or unavailable to its owner stop the + personal proxy. Any other refusal is retried.""" + # The service outlives logins, so each request uses the login stored now, not the one it started with. + credentials = _owner_login(host, registration) + if credentials is None: + raise SignedOut() + try: + response = CliContext(credentials=credentials).call_with_refresh( + lambda client: client.custom_proxies.create_gateway_token(registration.custom_proxy_id) + ) + except APIStatusError as error: + code = error.code if isinstance(error.code, str) else None + if code is not None and (code == _REMOVED or code in _UNAVAILABLE_REASONS): + raise SignInRefused(code) from error + raise GatewayTokenUnavailable(f"Gumloop didn't give a gateway token (HTTP {error.status_code})") from error + except (GumloopError, httpx.HTTPError) as error: + raise GatewayTokenUnavailable(f"Gumloop didn't give a gateway token ({error})") from error + return response + + +def _register(cli: CliContext, host: str, key: Ed25519PrivateKey, name: str | None) -> CustomProxyRegistration: + machine_name = socket.gethostname() + response = cli.call_with_refresh( + lambda client: client.custom_proxies.register_cli( + name=name or machine_name[:_NAME_MAX_LENGTH], + public_key=public_key_text(key), + machine_name=machine_name, + cli_version=__version__, + ) + ) + registration = CustomProxyRegistration( + custom_proxy_id=response.custom_proxy.id, + name=response.custom_proxy.name, + gateway_url=response.gateway_url, + public_key=public_key_text(key), + user_id=_login_user_id(_stored_credentials()), + ) + save_registration(host, registration) + added_name = escape_markup(response.custom_proxy.name) + console.print(f"Linked this computer to Gumloop as '{added_name}'.") + return registration + + +def _service_or_none() -> CustomProxyService | None: + try: + return service_for_current_platform() + except GumloopError: + return None + + +def _explained(error: Exception) -> Exception: + """Personal proxies being off for this member, in words. Any other error stays as it is.""" + if isinstance(error, APIStatusError) and error.code in _UNAVAILABLE_REASONS: + return GumloopError(_UNAVAILABLE_REASONS[error.code]) + return error + + +def _tls_inspected_error(error: TlsInspected) -> GumloopError: + return GumloopError( + f"This network inspects TLS traffic ({error}), so sites would show your agents' browser " + "certificate errors. Use this computer on a network without TLS inspection." + ) + + +def _record_connection(host: str, *, connected: bool, last_error: str | None = None) -> None: + save_connection_status( + host, + CustomProxyConnectionStatus(connected=connected, since=datetime.now(timezone.utc), last_error=last_error), + ) + + +def _clock_time(moment: datetime) -> str: + local = moment.astimezone() + if local.date() == datetime.now().astimezone().date(): + return local.strftime("%-I:%M %p") + return local.strftime("%b %-d, %-I:%M %p") + + +def _print_destination(target: Target) -> None: + opened = datetime.now().astimezone().strftime("%b %-d, %-I:%M:%S %p") + console.print(f"[dim]{opened} {escape_markup(target.host)}[/dim]", highlight=False) diff --git a/src/gumloop/cli/custom_proxy_key.py b/src/gumloop/cli/custom_proxy_key.py index cd2769d..4071ec0 100644 --- a/src/gumloop/cli/custom_proxy_key.py +++ b/src/gumloop/cli/custom_proxy_key.py @@ -1,11 +1,12 @@ """This machine's personal proxy on one backend: the Ed25519 key it signs in to the -linked proxy gateway with, kept in the OS keychain, and the personal proxy that key -registered as.""" +linked proxy gateway with, kept in the OS keychain, the personal proxy that key +registered as, and whether its tunnel is connected.""" from __future__ import annotations import base64 import os +from datetime import datetime from pathlib import Path from urllib.parse import urlsplit @@ -32,7 +33,12 @@ class CustomProxyRegistration(BaseModel): model_config = ConfigDict(extra="forbid") custom_proxy_id: str = Field(min_length=1) + name: str = Field(min_length=1) gateway_url: str = Field(min_length=1) + # The key it registered, which the keychain no longer has if it was reset. + public_key: str = Field(min_length=1) + # The Gumloop user who linked it; None when their login didn't say. + user_id: str | None = None @field_validator("gateway_url") @classmethod @@ -44,6 +50,17 @@ def _require_encrypted_gateway(cls, gateway_url: str) -> str: raise ValueError("the linked proxy gateway must use wss:// unless it runs on this computer") +class CustomProxyConnectionStatus(BaseModel): + """Written by the running personal proxy; stale once it no longer holds the lock.""" + + model_config = ConfigDict(extra="forbid") + + connected: bool + # When this status was recorded: the connect, or the start of the current attempt or failure. + since: datetime + last_error: str | None = None + + def backend_host(base_url: str) -> str: """Each backend gets its own key and registration, so staging and production never share one.""" return urlsplit(base_url).netloc @@ -75,18 +92,57 @@ def load_registration(host: str, home: Path | None = None) -> CustomProxyRegistr def save_registration(host: str, registration: CustomProxyRegistration, home: Path | None = None) -> None: - destination = _registration_path(host, home) + _write_private(_registration_path(host, home), registration.model_dump_json()) + + +def forget_registration(host: str, home: Path | None = None) -> None: + _registration_path(host, home).unlink(missing_ok=True) + + +def load_connection_status(host: str, home: Path | None = None) -> CustomProxyConnectionStatus | None: + try: + return CustomProxyConnectionStatus.model_validate_json(_status_path(host, home).read_text(encoding="utf-8")) + except (OSError, ValidationError): + return None + + +def save_connection_status(host: str, status: CustomProxyConnectionStatus, home: Path | None = None) -> None: + _write_private(_status_path(host, home), status.model_dump_json()) + + +def forget_connection_status(host: str, home: Path | None = None) -> None: + _status_path(host, home).unlink(missing_ok=True) + + +def forget(host: str, home: Path | None = None) -> None: + """Deletes the key, the registration and the connection status. The personal proxy + stays in Gumloop until it is deleted there.""" + try: + keyring.delete_password(KEYRING_SERVICE, _key_account(host)) + except keyring.errors.PasswordDeleteError: + pass + except keyring.errors.KeyringError as error: + raise GumloopError(f"Could not delete the personal proxy key from the OS keychain: {error}") from error + forget_registration(host, home) + forget_connection_status(host, home) + + +def _key_account(host: str) -> str: + return f"custom-proxy:{host}" + + +def _write_private(destination: Path, text: str) -> None: destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) staging = destination.with_name(f".{destination.name}.tmp") descriptor = os.open(staging, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(descriptor, "w", encoding="utf-8") as file: - file.write(registration.model_dump_json()) + file.write(text) staging.replace(destination) -def _key_account(host: str) -> str: - return f"custom-proxy:{host}" - - def _registration_path(host: str, home: Path | None) -> Path: return (home or Path.home()) / ".gumloop" / "custom-proxy" / f"{host}.json" + + +def _status_path(host: str, home: Path | None) -> Path: + return (home or Path.home()) / ".gumloop" / "custom-proxy" / f"{host}.status.json" diff --git a/src/gumloop/cli/custom_proxy_lock.py b/src/gumloop/cli/custom_proxy_lock.py new file mode 100644 index 0000000..b7dd058 --- /dev/null +++ b/src/gumloop/cli/custom_proxy_lock.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import fcntl +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +from gumloop import GumloopError + + +@contextmanager +def custom_proxy_lock(host: str, home: Path | None = None) -> Iterator[None]: + """Held while the personal proxy runs, so a second one on this machine stops + instead of competing for the gateway's one connection per personal proxy.""" + path = _lock_path(host, home) + try: + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + handle = path.open("a+", encoding="utf-8") + except OSError as error: + raise GumloopError(f"Could not create the lock file {path}: {error}") from error + try: + fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + handle.close() + raise GumloopError("This computer is already connected as a personal proxy.") from error + try: + yield + finally: + handle.close() + + +def is_running(host: str, home: Path | None = None) -> bool: + if not _lock_path(host, home).exists(): + return False + try: + with custom_proxy_lock(host, home): + return False + except GumloopError: + return True + + +def _lock_path(host: str, home: Path | None) -> Path: + return (home or Path.home()) / ".gumloop" / "custom-proxy" / f"{host}.lock" diff --git a/src/gumloop/cli/custom_proxy_service.py b/src/gumloop/cli/custom_proxy_service.py new file mode 100644 index 0000000..6c967d3 --- /dev/null +++ b/src/gumloop/cli/custom_proxy_service.py @@ -0,0 +1,201 @@ +"""Runs ``gumloop browser proxy connect`` in the background: a LaunchAgent on +macOS, a systemd user unit on Linux. Both start it at login and restart it +after a failure, but not after a clean exit, which is how it stops once the +user logs out or Gumloop refuses the personal proxy.""" + +from __future__ import annotations + +import os +import plistlib +import shutil +import subprocess +import sys +import tempfile +from collections.abc import Callable +from collections.abc import Sequence +from pathlib import Path +from typing import Protocol + +from gumloop import GumloopError + +LAUNCH_AGENT_LABEL = "com.gumloop.custom-proxy" +SYSTEMD_UNIT = "gumloop-custom-proxy.service" +_CONNECT_ARGUMENTS = ("browser", "proxy", "connect") +_RESTART_SECONDS = 30 +# Present only when systemd is the running init system. +_SYSTEMD_BOOTED_DIR = Path("/run/systemd/system") +_SAFE_PATH = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" +# Credentials come from the keychain, never from the shell that ran `add`. +_CLEARED_ENVIRONMENT = ( + "GUMLOOP_ACCESS_TOKEN", + "GUMLOOP_API_KEY", + "GUMLOOP_BASE_URL", + "GUMLOOP_TEAM_ID", + "GUMLOOP_USER_ID", +) + +CommandRunner = Callable[[Sequence[str]], subprocess.CompletedProcess[str]] + + +class NoBackgroundService(GumloopError): + """This computer can't keep the personal proxy running in the background, such + as a Linux container or SSH session without a systemd user session.""" + + +class CustomProxyService(Protocol): + def install(self, executable_path: Path) -> None: + """Writes the service and (re)starts it.""" + ... + + def remove(self) -> None: ... + + def is_installed(self) -> bool: ... + + +class LaunchAgentService: + def __init__( + self, + *, + home: Path, + run_command: CommandRunner | None = None, + get_uid: Callable[[], int] | None = None, + ) -> None: + self._home = home + self._run_command = run_command or _run_command + self._get_uid = get_uid or os.getuid + + @property + def plist_path(self) -> Path: + return self._home / "Library" / "LaunchAgents" / f"{LAUNCH_AGENT_LABEL}.plist" + + def install(self, executable_path: Path) -> None: + log_path = self._home / ".gumloop" / "custom-proxy" / "service.log" + try: + log_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + except OSError as error: + raise GumloopError(f"Could not create {log_path.parent}: {error}") from error + payload = { + "EnvironmentVariables": { + **dict.fromkeys(_CLEARED_ENVIRONMENT, ""), + "HOME": str(self._home), + "PATH": _SAFE_PATH, + }, + "KeepAlive": {"SuccessfulExit": False}, + "Label": LAUNCH_AGENT_LABEL, + "ProgramArguments": [str(executable_path), *_CONNECT_ARGUMENTS], + "RunAtLoad": True, + "StandardErrorPath": str(log_path), + "ThrottleInterval": _RESTART_SECONDS, + } + _write_private(self.plist_path, plistlib.dumps(payload, fmt=plistlib.FMT_XML, sort_keys=True)) + self._run_command(["launchctl", "bootout", self._job_target()]) + _check(self._run_command(["launchctl", "bootstrap", f"gui/{self._get_uid()}", str(self.plist_path)])) + + def remove(self) -> None: + self._run_command(["launchctl", "bootout", self._job_target()]) + _unlink(self.plist_path) + + def is_installed(self) -> bool: + return self.plist_path.is_file() + + def _job_target(self) -> str: + return f"gui/{self._get_uid()}/{LAUNCH_AGENT_LABEL}" + + +class SystemdUserService: + def __init__(self, *, config_home: Path, run_command: CommandRunner | None = None) -> None: + self._config_home = config_home + self._run_command = run_command or _run_command + + @property + def unit_path(self) -> Path: + return self._config_home / "systemd" / "user" / SYSTEMD_UNIT + + def install(self, executable_path: Path) -> None: + command = " ".join(_systemd_quote(part) for part in [str(executable_path), *_CONNECT_ARGUMENTS]) + unit = ( + "[Unit]\n" + "Description=Gumloop personal proxy\n" + "After=network-online.target\n" + "\n" + "[Service]\n" + f"ExecStart={command}\n" + f"UnsetEnvironment={' '.join(_CLEARED_ENVIRONMENT)}\n" + "Restart=on-failure\n" + f"RestartSec={_RESTART_SECONDS}\n" + "\n" + "[Install]\n" + "WantedBy=default.target\n" + ) + _write_private(self.unit_path, unit.encode()) + _check(self._systemctl("daemon-reload")) + _check(self._systemctl("enable", SYSTEMD_UNIT)) + _check(self._systemctl("restart", SYSTEMD_UNIT)) + + def remove(self) -> None: + self._systemctl("disable", "--now", SYSTEMD_UNIT) + _unlink(self.unit_path) + self._systemctl("daemon-reload") + + def is_installed(self) -> bool: + return self.unit_path.is_file() + + def _systemctl(self, *args: str) -> subprocess.CompletedProcess[str]: + return self._run_command(["systemctl", "--user", *args]) + + +def service_for_current_platform(*, home: Path | None = None) -> CustomProxyService: + home = home or Path.home() + if sys.platform == "darwin": + return LaunchAgentService(home=home) + if sys.platform.startswith("linux"): + if not _SYSTEMD_BOOTED_DIR.is_dir() or not os.environ.get("XDG_RUNTIME_DIR"): + raise NoBackgroundService("This computer has no systemd user session to run the personal proxy in.") + return SystemdUserService(config_home=Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config")) + raise GumloopError("`gumloop browser proxy` runs on macOS and Linux only.") + + +def gumloop_executable() -> Path: + found = shutil.which("gumloop") + if found is None: + raise GumloopError( + "Could not find the `gumloop` command on PATH, so this computer can't stay connected in the background." + ) + return Path(found).absolute() + + +def _systemd_quote(value: str) -> str: + escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%").replace("$", "$$") + return f'"{escaped}"' + + +def _write_private(destination: Path, content: bytes) -> None: + try: + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=destination.parent, prefix=f".{destination.name}.", delete=False) as file: + staging = Path(file.name) + staging.chmod(0o600) + file.write(content) + staging.replace(destination) + except OSError as error: + raise GumloopError(f"Could not write {destination}: {error}") from error + + +def _unlink(path: Path) -> None: + try: + path.unlink(missing_ok=True) + except OSError as error: + raise GumloopError(f"Could not remove {path}: {error}") from error + + +def _check(result: subprocess.CompletedProcess[str]) -> None: + if result.returncode != 0: + command = " ".join(str(part) for part in result.args) + raise GumloopError(f"`{command}` failed: {result.stderr.strip() or result.returncode}") + + +def _run_command(args: Sequence[str]) -> subprocess.CompletedProcess[str]: + try: + return subprocess.run(list(args), check=False, capture_output=True, text=True, timeout=10) + except (OSError, subprocess.SubprocessError) as error: + raise GumloopError(f"Could not run `{args[0]}`: {error}") from error diff --git a/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md b/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md index 249b5d8..debc5c4 100644 --- a/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md +++ b/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md @@ -9,7 +9,7 @@ gumloop login # interactive: pick OAuth (browser) or AP gumloop login --method oauth # OAuth; add --no-browser to print the URL instead gumloop login --api-key gum_xxx --user-id user_abc echo "$GUMLOOP_API_KEY" | gumloop login --api-key - --user-id user_abc # keep key out of history -gumloop logout # clears keychain entries, revokes OAuth refresh token +gumloop logout # clears keychain entries, revokes OAuth refresh token, unlinks this computer ``` Environment variables (override stored credentials for one invocation; ideal for CI): @@ -153,6 +153,16 @@ gumloop sync # enroll persistent sync (macOS) of org-ma gumloop sync --once --non-interactive # one-shot sync; requires GUMLOOP_API_KEY + GUMLOOP_USER_ID ``` +## Personal proxy + +```bash +gumloop browser proxy link # automatically runs in the background on startup +gumloop browser proxy status +gumloop browser proxy unlink +``` + +macOS and Linux only. Needs a stored `gumloop login`; logging out unlinks this computer. + ## Maintenance ```bash diff --git a/src/gumloop/linked_proxy/connection.py b/src/gumloop/linked_proxy/connection.py index 096d71c..6ea957a 100644 --- a/src/gumloop/linked_proxy/connection.py +++ b/src/gumloop/linked_proxy/connection.py @@ -1,19 +1,18 @@ """Keeps this machine's tunnel to the linked proxy gateway open: signs in, serves the -gateway's streams, and reconnects until the gateway refuses the sign-in or the +gateway's streams, and reconnects until Gumloop refuses a gateway token or the user signs out.""" from __future__ import annotations import asyncio -import functools import random -import ssl import time from collections.abc import Awaitable from collections.abc import Callable from contextlib import AbstractAsyncContextManager +from datetime import datetime +from datetime import timezone -import certifi from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from websockets.asyncio.client import connect as websocket_connect from websockets.exceptions import ConnectionClosed @@ -25,25 +24,33 @@ from gumloop.linked_proxy.frames import MAX_FRAME_LENGTH from gumloop.linked_proxy.frames import ProtocolError from gumloop.linked_proxy.sign_in import sign_in_token +from gumloop.linked_proxy.tls_check import tls_context from gumloop.linked_proxy.tunnel import Connection from gumloop.linked_proxy.tunnel import Tunnel +from gumloop.types import CustomProxyGatewayToken -# The gateway's close code and refusal header for a sign-in it won't accept. -CLOSE_SIGN_IN_REFUSED = 4001 +# The gateway's refusal header for a sign-in it won't accept. ERROR_HEADER = "X-Gumloop-Linked-Proxy-Error" SIGN_IN_REFUSED = "sign_in_refused" FIRST_RETRY_SECONDS = 1.0 +# Spreads out the linked proxies that all reconnect at once when a gateway replica restarts. +FIRST_RETRY_CAP_SECONDS = 5.0 MAX_RETRY_SECONDS = 60.0 # A connection that stayed up this long starts the backoff over. STABLE_SECONDS = 60.0 _OPEN_TIMEOUT_SECONDS = 10.0 +# An open tunnel sends a fresh gateway token this long before its current one expires. +REFRESH_BEFORE_EXPIRY_SECONDS = 15 * 60.0 +# The least time between refreshes, which is also the wait before retrying a failed one. +MIN_REFRESH_SECONDS = 60.0 + Open = Callable[[str, dict[str, str]], AbstractAsyncContextManager[Connection]] class SignInRefused(Exception): - """The gateway won't accept this linked proxy: it was unlinked, or its owner can't use it anymore.""" + """Gumloop won't give this linked proxy a gateway token: it was unlinked, or its owner can't use it anymore.""" def __init__(self, reason: str) -> None: super().__init__(reason) @@ -66,10 +73,13 @@ def __init__( linked_proxy_id: str, key: Ed25519PrivateKey, signed_in: Callable[[], bool], - gateway_token: Callable[[], str], + gateway_token: Callable[[], CustomProxyGatewayToken], on_open: Callable[[Target], None] | None = None, + on_connected: Callable[[], None] | None = None, + on_failed: Callable[[str], None] | None = None, open_websocket: Open | None = None, sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, + refresh_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, ) -> None: self._gateway_url = gateway_url self._linked_proxy_id = linked_proxy_id @@ -77,15 +87,20 @@ def __init__( self._signed_in = signed_in self._gateway_token = gateway_token self._on_open = on_open + self._on_connected = on_connected + self._on_failed = on_failed self._open = open_websocket or _open_websocket self._sleep = sleep + self._refresh_sleep = refresh_sleep async def run(self) -> None: """Runs until it raises ``SignInRefused`` or ``SignedOut``. Every other failure reconnects after a random wait whose cap doubles up to ``MAX_RETRY_SECONDS``. - ``gateway_token`` runs in a thread before each connect, and raises - ``SignInRefused`` or ``GatewayTokenUnavailable`` when it has no token.""" - retry_cap = FIRST_RETRY_SECONDS + ``gateway_token`` runs in a thread before each connect and each refresh, and raises + ``SignInRefused`` or ``GatewayTokenUnavailable`` when it has no token. A gateway + refusal reconnects too: a wrong clock looks the same to the gateway as an unlinked + linked proxy, and the next gateway token request tells them apart.""" + retry_cap = FIRST_RETRY_CAP_SECONDS while True: if not self._signed_in(): raise SignedOut() @@ -93,11 +108,10 @@ async def run(self) -> None: try: await self._serve() except (OSError, asyncio.TimeoutError, WebSocketException, ProtocolError, GatewayTokenUnavailable) as error: - reason = _sign_in_refusal(error) - if reason is not None: - raise SignInRefused(reason) from error + if self._on_failed is not None: + self._on_failed(describe_failure(error)) if time.monotonic() - started >= STABLE_SECONDS: - retry_cap = FIRST_RETRY_SECONDS + retry_cap = FIRST_RETRY_CAP_SECONDS await self._sleep(random.uniform(FIRST_RETRY_SECONDS, retry_cap)) retry_cap = min(retry_cap * 2, MAX_RETRY_SECONDS) @@ -107,22 +121,58 @@ async def _serve(self) -> None: self._key, linked_proxy_id=self._linked_proxy_id, audience=self._gateway_url, - gateway_token=gateway_token, + gateway_token=gateway_token.gateway_token, ) async with self._open(self._gateway_url, {"Authorization": f"Bearer {token}"}) as websocket: - await Tunnel(websocket, on_open=self._on_open).run() - - -def _sign_in_refusal(error: BaseException) -> str | None: - if isinstance(error, ConnectionClosed) and error.rcvd is not None and error.rcvd.code == CLOSE_SIGN_IN_REFUSED: - return error.rcvd.reason or SIGN_IN_REFUSED - if ( - isinstance(error, InvalidStatus) - and error.response.status_code == 401 - and error.response.headers.get(ERROR_HEADER) == SIGN_IN_REFUSED - ): - return SIGN_IN_REFUSED - return None + if self._on_connected is not None: + self._on_connected() + tunnel = Tunnel(websocket, on_open=self._on_open) + refresh = asyncio.ensure_future(self._refresh(tunnel, gateway_token)) + try: + await tunnel.run() + finally: + refresh.cancel() + await asyncio.gather(refresh, return_exceptions=True) + + async def _refresh(self, tunnel: Tunnel, gateway_token: CustomProxyGatewayToken) -> None: + """Sends a fresh gateway token before each one expires. When Gumloop refuses one, the + gateway's own recheck closes the tunnel. A gateway token without ``expires_at`` comes + from a backend older than refreshes, whose gateway would reject one.""" + while gateway_token.expires_at is not None: + await self._refresh_sleep(_seconds_until_refresh(gateway_token.expires_at)) + try: + gateway_token = await asyncio.to_thread(self._gateway_token) + except GatewayTokenUnavailable: + continue + except (SignInRefused, SignedOut): + return + await tunnel.send_gateway_token(gateway_token.gateway_token) + + +def _seconds_until_refresh(expires_at: str) -> float: + # Python 3.10's fromisoformat rejects a trailing Z. + expiry = datetime.fromisoformat(expires_at.replace("Z", "+00:00")) + remaining = (expiry - datetime.now(timezone.utc)).total_seconds() + return max(remaining - REFRESH_BEFORE_EXPIRY_SECONDS, MIN_REFRESH_SECONDS) + + +def describe_failure(error: BaseException) -> str: + """Why a connection attempt or an open tunnel ended, in words for ``gumloop browser proxy status``.""" + if isinstance(error, ConnectionClosed): + if error.rcvd is None: + return "the connection dropped" + return f"the gateway closed the connection ({error.rcvd.reason or error.rcvd.code})" + if isinstance(error, InvalidStatus): + if error.response.headers.get(ERROR_HEADER) == SIGN_IN_REFUSED: + return "the gateway refused the sign-in (is this computer's clock right?)" + return f"the gateway answered HTTP {error.response.status_code}" + if isinstance(error, asyncio.TimeoutError): + return "the gateway didn't answer in time" + if isinstance(error, ProtocolError): + return f"the gateway sent an invalid message ({error})" + if isinstance(error, OSError): + return f"can't reach the gateway ({(error.strerror or str(error) or type(error).__name__).lower()})" + return str(error) or type(error).__name__ def _open_websocket(url: str, headers: dict[str, str]) -> AbstractAsyncContextManager[Connection]: @@ -130,13 +180,8 @@ def _open_websocket(url: str, headers: dict[str, str]) -> AbstractAsyncContextMa url, additional_headers=headers, user_agent_header=user_agent(), - ssl=_tls_context() if url.startswith("wss://") else None, + ssl=tls_context() if url.startswith("wss://") else None, compression=None, max_size=MAX_FRAME_LENGTH, open_timeout=_OPEN_TIMEOUT_SECONDS, ) - - -@functools.cache -def _tls_context() -> ssl.SSLContext: - return ssl.create_default_context(cafile=certifi.where()) diff --git a/src/gumloop/linked_proxy/tls_check.py b/src/gumloop/linked_proxy/tls_check.py new file mode 100644 index 0000000..5b85555 --- /dev/null +++ b/src/gumloop/linked_proxy/tls_check.py @@ -0,0 +1,38 @@ +"""Whether this network inspects TLS. A proxy that re-signs traffic with its own +CA would show the agent's browser a certificate error on every site.""" + +from __future__ import annotations + +import functools +import socket +import ssl + +import certifi + +CHECK_HOST = "example.com" +_TIMEOUT_SECONDS = 5.0 + + +class TlsInspected(Exception): + """A public site's certificate did not chain to a public CA.""" + + +@functools.cache +def tls_context() -> ssl.SSLContext: + """Trusts certifi's roots only: a CA that inspection software adds to the OS store must not pass.""" + context = ssl.create_default_context(cafile=certifi.where()) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + return context + + +def check_tls_not_inspected(host: str = CHECK_HOST, port: int = 443) -> None: + """Raises ``TlsInspected`` on a certificate error. Any other failure passes, + since the tunnel keeps retrying until the network is back.""" + try: + with socket.create_connection((host, port), timeout=_TIMEOUT_SECONDS) as raw: + with tls_context().wrap_socket(raw, server_hostname=host): + pass + except ssl.SSLCertVerificationError as error: + raise TlsInspected(error.verify_message) from error + except OSError: + return diff --git a/src/gumloop/types.py b/src/gumloop/types.py index a4df77e..e89df9d 100644 --- a/src/gumloop/types.py +++ b/src/gumloop/types.py @@ -834,6 +834,8 @@ class CustomProxyResponse(_Model): class CustomProxyGatewayToken(_Model): # Opaque to the CLI, which puts it in its sign-in tokens. It expires after an hour. gateway_token: str + # ISO 8601. Older backends leave it out. + expires_at: str | None = None MAX_SDP_OFFER_BYTES = 1024 * 1024 diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py new file mode 100644 index 0000000..c2c8986 --- /dev/null +++ b/tests/cli/test_custom_proxy_command.py @@ -0,0 +1,461 @@ +from __future__ import annotations + +import base64 +import json +from collections.abc import Callable +from datetime import datetime +from datetime import timezone +from pathlib import Path + +import keyring +import pytest +import respx + +from gumloop.cli.credentials import KEYRING_SERVICE +from gumloop.cli.credentials import Credentials +from gumloop.cli.credentials import save_credentials +from gumloop.cli.custom_proxy_key import CustomProxyConnectionStatus +from gumloop.cli.custom_proxy_key import CustomProxyRegistration +from gumloop.cli.custom_proxy_key import load_or_create_key +from gumloop.cli.custom_proxy_key import load_registration +from gumloop.cli.custom_proxy_key import save_connection_status +from gumloop.cli.custom_proxy_key import save_registration +from gumloop.cli.custom_proxy_service import NoBackgroundService +from gumloop.cli.main import app +from gumloop.linked_proxy.connection import GatewayTokenUnavailable +from gumloop.linked_proxy.connection import SignInRefused +from gumloop.linked_proxy.destinations import Target +from gumloop.linked_proxy.sign_in import public_key_text +from gumloop.types import CustomProxyGatewayToken +from tests.sdk.helpers import API_BASE + +HOST = "api.gumloop.com" +GATEWAY_URL = "wss://linked-proxy-gateway.gumloop.com/v1/cli/connect" + + +def _registration(**changes: str) -> CustomProxyRegistration: + """What `link` saves for the keychain's key and the `service` fixture's login.""" + return CustomProxyRegistration( + custom_proxy_id="dp-1", + name="Ada's laptop", + gateway_url=GATEWAY_URL, + public_key=public_key_text(load_or_create_key(HOST)), + user_id="actor", + ).model_copy(update=changes) + + +def _access_token(user_id: str) -> str: + claims = base64.urlsafe_b64encode(json.dumps({"sub": user_id}).encode()).decode().rstrip("=") + return f"header.{claims}.signature" + + +class FakeService: + def __init__(self, *, installed: bool = False) -> None: + self.installed = installed + self.executable: Path | None = None + + def install(self, executable_path: Path) -> None: + self.installed = True + self.executable = executable_path + + def remove(self) -> None: + self.installed = False + + def is_installed(self) -> bool: + return self.installed + + +@pytest.fixture +def service(monkeypatch) -> FakeService: + fake = FakeService() + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.service_for_current_platform", lambda: fake) + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.check_tls_not_inspected", lambda: None) + save_credentials(Credentials(api_key="key", user_id="actor")) + return fake + + +@respx.mock +def test_add_registers_and_turns_on_the_service(cli_runner, service, fake_executable_path): + route = respx.post(f"{API_BASE}/custom-proxies").respond( + 201, + json={ + "custom_proxy": {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": True}, + "gateway_url": GATEWAY_URL, + }, + ) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 0, result.output + assert json.loads(route.calls[0].request.content)["public_key"] == public_key_text(load_or_create_key(HOST)) + assert load_registration(HOST) == _registration() + assert service.executable == fake_executable_path / "gumloop" + + +@respx.mock +def test_link_without_a_background_service_registers_and_points_to_connect(cli_runner, service, monkeypatch): + def no_background_service() -> FakeService: + raise NoBackgroundService("no systemd user session") + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.service_for_current_platform", no_background_service) + respx.post(f"{API_BASE}/custom-proxies").respond( + 201, + json={ + "custom_proxy": {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": True}, + "gateway_url": GATEWAY_URL, + }, + ) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 0, result.output + assert load_registration(HOST) == _registration() + assert not service.installed + assert "Run `gumloop browser proxy connect`" in " ".join(result.output.split()) + + +@respx.mock +def test_add_refuses_a_temporary_credential_override(cli_runner, service): + route = respx.post(f"{API_BASE}/custom-proxies") + + result = cli_runner.invoke(app, ["browser", "proxy", "link"], env={"GUMLOOP_ACCESS_TOKEN": "other-account"}) + + assert result.exit_code == 1 + assert not route.called + assert not service.installed + + +@respx.mock +def test_a_refused_custom_proxy_stays_down_after_a_restart(cli_runner, service, monkeypatch): + save_registration(HOST, _registration()) + + class RefusedConnection: + def __init__(self, **kwargs: object) -> None: + assert kwargs["linked_proxy_id"] == "dp-1" + + async def run(self) -> None: + raise SignInRefused("personal_custom_proxy_not_found") + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", RefusedConnection) + + refused = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + restarted = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert (refused.exit_code, restarted.exit_code) == (0, 0) + assert load_registration(HOST) is None + assert not respx.calls + + +def test_connect_says_it_connected_once_across_reconnects(cli_runner, service, monkeypatch): + save_registration(HOST, _registration()) + + class ReconnectingConnection: + def __init__(self, *, on_connected: Callable[[], None], **kwargs: object) -> None: + self._on_connected = on_connected + + async def run(self) -> None: + self._on_connected() + self._on_connected() + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", ReconnectingConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert result.exit_code == 0, result.output + assert " ".join(result.stdout.split()).count("Connected. Agents can now send browser traffic") == 1 + + +@pytest.mark.parametrize(("flags", "printed"), [([], False), (["-v"], True)]) +def test_connect_prints_the_sites_agents_open_only_when_verbose(cli_runner, service, monkeypatch, flags, printed): + save_registration(HOST, _registration()) + + class OpeningConnection: + def __init__(self, *, on_open: Callable[[Target], None] | None, **kwargs: object) -> None: + self._on_open = on_open + + async def run(self) -> None: + if self._on_open is not None: + self._on_open(Target(host="example.com", port=443)) + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", OpeningConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect", *flags]) + + assert result.exit_code == 0, result.output + assert ("example.com" in result.stdout) is printed + + +@pytest.mark.parametrize( + ("reason", "kept", "expected"), + [ + ("personal_custom_proxy_not_found", False, "This computer was unlinked from Gumloop."), + ( + "organization_permission_required", + True, + "Your organization's roles don't allow you to use personal proxies.", + ), + ("route_not_found", True, "Personal proxies aren't available for your organization yet."), + ], +) +def test_connect_keeps_the_registration_unless_the_custom_proxy_was_removed( + cli_runner, service, monkeypatch, reason, kept, expected +): + save_registration(HOST, _registration()) + + class RefusedConnection: + def __init__(self, **kwargs: object) -> None: + pass + + async def run(self) -> None: + raise SignInRefused(reason) + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", RefusedConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert result.exit_code == 0, result.output + assert (load_registration(HOST) == _registration()) is kept + assert expected in " ".join(result.stderr.split()) + + +@pytest.mark.parametrize( + ("status", "payload", "expected"), + [ + ( + 403, + {"error": "policy_denied", "denied_keys": ["organization:use_personal_proxies"]}, + "Your organization's roles don't allow you to use personal proxies. Ask an admin to turn them on.", + ), + (403, {"error": "tier_required_enterprise"}, "Personal proxies need an Enterprise plan."), + (404, {"error": "route_not_found"}, "Personal proxies aren't available for your organization yet."), + ], +) +@respx.mock +def test_link_says_why_personal_proxies_are_off(cli_runner, service, status, payload, expected): + respx.post(f"{API_BASE}/custom-proxies").respond(status, json=payload) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 1 + assert expected in " ".join(result.stderr.split()) + assert load_registration(HOST) is None + assert not service.installed + + +@pytest.mark.parametrize( + ("status", "payload", "expected_token", "kept"), + [ + (200, {"gateway_token": "token-1"}, "token-1", True), + (503, {"error": "unavailable"}, GatewayTokenUnavailable, True), + (404, {"error": {"code": "personal_custom_proxy_not_found"}}, None, False), + (403, {"error": "policy_denied", "denied_keys": ["organization:use_personal_proxies"]}, None, True), + (403, {"error": {"code": "organization_permission_required"}}, None, True), + (404, {"error": "route_not_found"}, None, True), + (403, {"error": {"code": "not_a_code_the_cli_knows"}}, GatewayTokenUnavailable, True), + (404, {"error": "not_found"}, GatewayTokenUnavailable, True), + ], +) +@respx.mock +def test_connect_signs_in_with_a_gateway_token_and_stops_when_gumloop_refuses_one( + cli_runner, service, monkeypatch, status, payload, expected_token, kept +): + save_registration(HOST, _registration()) + respx.post(f"{API_BASE}/custom-proxies/dp-1/gateway-token").respond(status, json=payload) + fetched: list[object] = [] + + class TokenFetchingConnection: + def __init__(self, *, gateway_token: Callable[[], CustomProxyGatewayToken], **kwargs: object) -> None: + self._gateway_token = gateway_token + + async def run(self) -> None: + try: + fetched.append(self._gateway_token().gateway_token) + except GatewayTokenUnavailable as error: + fetched.append(type(error)) + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", TokenFetchingConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert result.exit_code == 0, result.output + assert fetched == ([expected_token] if expected_token is not None else []) + assert (load_registration(HOST) == _registration()) is kept + + +@respx.mock +def test_connect_signs_in_with_the_login_stored_after_it_started(cli_runner, service, monkeypatch): + save_registration(HOST, _registration()) + route = respx.post(f"{API_BASE}/custom-proxies/dp-1/gateway-token").respond(200, json={"gateway_token": "t"}) + + class ReconnectingConnection: + def __init__(self, *, gateway_token: Callable[[], CustomProxyGatewayToken], **kwargs: object) -> None: + self._gateway_token = gateway_token + + async def run(self) -> None: + self._gateway_token() + save_credentials(Credentials(access_token="fresh")) + self._gateway_token() + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", ReconnectingConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert result.exit_code == 0, result.output + assert [call.request.headers["authorization"] for call in route.calls] == ["Bearer key", "Bearer fresh"] + + +@pytest.mark.parametrize( + "login", + [Credentials(api_key="key", user_id="someone-else"), Credentials(access_token=_access_token("someone-else"))], +) +@respx.mock +def test_connect_as_someone_else_disconnects_and_keeps_the_registration(cli_runner, service, monkeypatch, login): + save_registration(HOST, _registration()) + save_credentials(login) + route = respx.post(f"{API_BASE}/custom-proxies/dp-1/gateway-token") + + class TokenFetchingConnection: + def __init__(self, *, gateway_token: Callable[[], CustomProxyGatewayToken], **kwargs: object) -> None: + self._gateway_token = gateway_token + + async def run(self) -> None: + self._gateway_token() + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", TokenFetchingConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert result.exit_code == 0, result.output + assert not route.called + assert load_registration(HOST) == _registration() + assert "You logged in to Gumloop as someone else" in " ".join(result.stderr.split()) + + +def test_connect_forgets_a_registration_whose_key_is_gone(cli_runner, service, monkeypatch): + save_registration(HOST, _registration(public_key="a key the keychain no longer has")) + + class UnusedConnection: + def __init__(self, **kwargs: object) -> None: + pytest.fail("connected with a key Gumloop doesn't know") + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", UnusedConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert result.exit_code == 0, result.output + assert load_registration(HOST) is None + assert "key is gone from the OS keychain" in " ".join(result.stderr.split()) + + +@respx.mock +def test_link_registers_again_when_the_keychain_key_changed(cli_runner, service): + save_registration(HOST, _registration(public_key="a key the keychain no longer has")) + route = respx.post(f"{API_BASE}/custom-proxies").respond( + 201, + json={ + "custom_proxy": {"id": "dp-2", "name": "Ada's laptop", "kind": "cli", "is_default": True}, + "gateway_url": GATEWAY_URL, + }, + ) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 0, result.output + assert route.called + assert load_registration(HOST) == _registration(custom_proxy_id="dp-2") + + +@respx.mock +def test_link_refuses_a_computer_linked_to_someone_else(cli_runner, service): + save_registration(HOST, _registration(user_id="someone-else")) + route = respx.post(f"{API_BASE}/custom-proxies") + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 1 + assert not route.called + assert not service.installed + assert "linked to another Gumloop user" in " ".join(result.stderr.split()) + + +@pytest.mark.parametrize( + ("running", "connected", "last_error", "expected"), + [ + (False, True, None, "not running. Run `gumloop browser proxy link` to start."), + (True, False, "can't reach the gateway (connection refused)", "connecting. Last attempt failed: can't reach"), + (True, True, None, "connected since"), + ], +) +def test_status_reads_the_running_custom_proxy_connection( + cli_runner, service, monkeypatch, running, connected, last_error, expected +): + save_registration(HOST, _registration()) + save_connection_status( + HOST, + CustomProxyConnectionStatus(connected=connected, since=datetime.now(timezone.utc), last_error=last_error), + ) + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.is_running", lambda host: running) + + result = cli_runner.invoke(app, ["browser", "proxy", "status"]) + + assert result.exit_code == 0, result.output + assert f'"Ada\'s laptop": {expected}' in " ".join(result.output.split()) + + +def test_status_without_a_background_service_points_to_connect(cli_runner, service, monkeypatch): + def no_background_service() -> FakeService: + raise NoBackgroundService("no systemd user session") + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.service_for_current_platform", no_background_service) + save_registration(HOST, _registration()) + + result = cli_runner.invoke(app, ["browser", "proxy", "status"]) + + assert result.exit_code == 0, result.output + assert "not running. Run `gumloop browser proxy connect` to start." in " ".join(result.output.split()) + + +@pytest.mark.parametrize("command", [["browser", "proxy", "unlink"], ["logout"]]) +@respx.mock +def test_removing_deletes_the_custom_proxy_then_the_key(cli_runner, service, command): + service.installed = True + save_registration(HOST, _registration()) + load_or_create_key(HOST) + route = respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(204) + + result = cli_runner.invoke(app, command) + + assert result.exit_code == 0, result.output + assert route.called + assert not service.installed + assert keyring.get_password(KEYRING_SERVICE, f"custom-proxy:{HOST}") is None + assert load_registration(HOST) is None + + +@pytest.mark.parametrize(("login_has_custom_proxy", "kept"), [(True, True), (False, False)]) +def test_removing_another_backends_custom_proxy_keeps_the_service_only_while_the_login_needs_it( + cli_runner, service, login_has_custom_proxy, kept +): + service.installed = True + if login_has_custom_proxy: + save_registration(HOST, _registration()) + + result = cli_runner.invoke( + app, ["browser", "proxy", "unlink"], env={"GUMLOOP_BASE_URL": "https://staging.api.gumloop.com"} + ) + + assert result.exit_code == 0, result.output + assert service.installed is kept + + +@respx.mock +def test_remove_keeps_the_key_when_gumloop_cannot_delete_the_custom_proxy(cli_runner, service): + save_registration(HOST, _registration()) + key = public_key_text(load_or_create_key(HOST)) + respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(503, json={"error": "unavailable"}) + + result = cli_runner.invoke(app, ["browser", "proxy", "unlink"]) + + assert result.exit_code == 1 + assert public_key_text(load_or_create_key(HOST)) == key + assert load_registration(HOST) == _registration() diff --git a/tests/cli/test_custom_proxy_key.py b/tests/cli/test_custom_proxy_key.py index de9d146..e5c2de7 100644 --- a/tests/cli/test_custom_proxy_key.py +++ b/tests/cli/test_custom_proxy_key.py @@ -4,24 +4,46 @@ from pydantic import ValidationError from gumloop.cli.custom_proxy_key import CustomProxyRegistration +from gumloop.cli.custom_proxy_key import load_or_create_key +from gumloop.cli.custom_proxy_key import load_registration +from gumloop.cli.custom_proxy_key import save_registration +from gumloop.linked_proxy.sign_in import public_key_text -def test_registration_accepts_an_unencrypted_gateway_on_this_computer(): - registration = CustomProxyRegistration(custom_proxy_id="dp-1", gateway_url="ws://localhost:8443/v1/cli/connect") +def test_key_and_registration_persist(temporary_home): + host = "api.gumloop.com" + first = public_key_text(load_or_create_key(host)) + registration = CustomProxyRegistration( + custom_proxy_id="dp-1", + name="Ada's laptop", + gateway_url="wss://linked-proxy-gateway.gumloop.com/v1/cli/connect", + public_key=first, + user_id="ada", + ) - assert registration.gateway_url == "ws://localhost:8443/v1/cli/connect" + save_registration(host, registration) + + assert public_key_text(load_or_create_key(host)) == first + assert load_registration(host) == registration + + +@pytest.mark.parametrize( + "gateway_url", + ["wss://linked-proxy-gateway.gumloop.com/v1/cli/connect", "ws://localhost:8443/v1/cli/connect"], +) +def test_registration_accepts_an_encrypted_or_local_gateway(gateway_url): + registration = CustomProxyRegistration( + custom_proxy_id="dp-1", name="Ada's laptop", gateway_url=gateway_url, public_key="key" + ) + + assert registration.gateway_url == gateway_url def test_registration_refuses_an_unencrypted_remote_gateway(): - with pytest.raises(ValidationError) as refused: + with pytest.raises(ValidationError): CustomProxyRegistration( - custom_proxy_id="dp-1", gateway_url="ws://linked-proxy-gateway.gumloop.com/v1/cli/connect" - ) - - assert [(error["loc"], error["type"], error["msg"]) for error in refused.value.errors()] == [ - ( - ("gateway_url",), - "value_error", - "Value error, the linked proxy gateway must use wss:// unless it runs on this computer", + custom_proxy_id="dp-1", + name="Ada's laptop", + gateway_url="ws://linked-proxy-gateway.gumloop.com/v1/cli/connect", + public_key="key", ) - ] diff --git a/tests/cli/test_custom_proxy_service.py b/tests/cli/test_custom_proxy_service.py new file mode 100644 index 0000000..daf74ca --- /dev/null +++ b/tests/cli/test_custom_proxy_service.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import plistlib +import subprocess +import sys +from collections.abc import Sequence +from pathlib import Path + +import pytest + +from gumloop.cli.custom_proxy_service import LaunchAgentService +from gumloop.cli.custom_proxy_service import NoBackgroundService +from gumloop.cli.custom_proxy_service import SystemdUserService +from gumloop.cli.custom_proxy_service import service_for_current_platform + +EXECUTABLE = Path("/opt/gumloop bin/gumloop") + + +class RecordingRunner: + def __init__(self) -> None: + self.calls: list[list[str]] = [] + + def __call__(self, args: Sequence[str]) -> subprocess.CompletedProcess[str]: + self.calls.append(list(args)) + return subprocess.CompletedProcess(list(args), 0, stdout="", stderr="") + + +def test_launch_agent_runs_the_custom_proxy_at_login_and_after_failures(tmp_path): + runner = RecordingRunner() + service = LaunchAgentService(home=tmp_path, run_command=runner, get_uid=lambda: 501) + + service.install(EXECUTABLE) + + plist = plistlib.loads(service.plist_path.read_bytes()) + assert plist["ProgramArguments"] == [str(EXECUTABLE), "browser", "proxy", "connect"] + assert plist["RunAtLoad"] is True + assert plist["KeepAlive"] == {"SuccessfulExit": False} + assert ["launchctl", "bootstrap", "gui/501", str(service.plist_path)] in runner.calls + + service.remove() + + assert not service.is_installed() + assert runner.calls[-1] == ["launchctl", "bootout", "gui/501/com.gumloop.custom-proxy"] + + +def test_systemd_unit_runs_the_custom_proxy_at_login_and_after_failures(tmp_path): + runner = RecordingRunner() + service = SystemdUserService(config_home=tmp_path, run_command=runner) + + service.install(EXECUTABLE) + + unit = service.unit_path.read_text() + assert 'ExecStart="/opt/gumloop bin/gumloop" "browser" "proxy" "connect"\n' in unit + assert "Restart=on-failure\n" in unit + assert "WantedBy=default.target\n" in unit + assert runner.calls[-2:] == [ + ["systemctl", "--user", "enable", "gumloop-custom-proxy.service"], + ["systemctl", "--user", "restart", "gumloop-custom-proxy.service"], + ] + + service.remove() + + assert not service.is_installed() + assert ["systemctl", "--user", "disable", "--now", "gumloop-custom-proxy.service"] in runner.calls + + +def test_systemd_unit_runs_an_executable_path_with_special_characters_as_written(tmp_path): + service = SystemdUserService(config_home=tmp_path, run_command=RecordingRunner()) + + service.install(Path('/home/a$b/100%/"q"\\gumloop')) + + unit = service.unit_path.read_text() + assert 'ExecStart="/home/a$$b/100%%/\\"q\\"\\\\gumloop" "browser" "proxy" "connect"\n' in unit + + +def test_systemd_unit_goes_where_systemd_looks_for_user_units(tmp_path, monkeypatch): + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setattr("gumloop.cli.custom_proxy_service._SYSTEMD_BOOTED_DIR", tmp_path) + monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path / "run")) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config")) + + service = service_for_current_platform(home=tmp_path) + + assert isinstance(service, SystemdUserService) + assert service.unit_path == tmp_path / "config" / "systemd" / "user" / "gumloop-custom-proxy.service" + + +@pytest.mark.parametrize(("systemd_booted", "runtime_dir"), [(False, "/run/user/1000"), (True, None)]) +def test_linux_without_a_systemd_user_session_has_no_background_service( + tmp_path, monkeypatch, systemd_booted, runtime_dir +): + monkeypatch.setattr(sys, "platform", "linux") + booted_dir = tmp_path if systemd_booted else tmp_path / "missing" + monkeypatch.setattr("gumloop.cli.custom_proxy_service._SYSTEMD_BOOTED_DIR", booted_dir) + if runtime_dir is None: + monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False) + else: + monkeypatch.setenv("XDG_RUNTIME_DIR", runtime_dir) + + with pytest.raises(NoBackgroundService): + service_for_current_platform(home=tmp_path) diff --git a/tests/linked_proxy/test_connection.py b/tests/linked_proxy/test_connection.py index 154ff17..2244d4d 100644 --- a/tests/linked_proxy/test_connection.py +++ b/tests/linked_proxy/test_connection.py @@ -5,8 +5,12 @@ import contextlib import json from collections.abc import AsyncIterator +from collections.abc import Awaitable from collections.abc import Callable from dataclasses import dataclass +from datetime import datetime +from datetime import timedelta +from datetime import timezone import pytest from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey @@ -16,15 +20,16 @@ from websockets.frames import Close from websockets.http11 import Response -from gumloop.linked_proxy import connection from gumloop.linked_proxy.connection import ERROR_HEADER +from gumloop.linked_proxy.connection import FIRST_RETRY_SECONDS +from gumloop.linked_proxy.connection import MIN_REFRESH_SECONDS +from gumloop.linked_proxy.connection import REFRESH_BEFORE_EXPIRY_SECONDS from gumloop.linked_proxy.connection import GatewayConnection from gumloop.linked_proxy.connection import GatewayTokenUnavailable from gumloop.linked_proxy.connection import SignedOut from gumloop.linked_proxy.connection import SignInRefused -from tests.linked_proxy.helpers import FrozenTime -from tests.linked_proxy.helpers import UpperBoundRandom -from tests.linked_proxy.helpers import tokens +from gumloop.linked_proxy.frames import Frame +from gumloop.types import CustomProxyGatewayToken GATEWAY_URL = "wss://linked-proxy-gateway.gumloop.com/v1/cli/connect" @@ -46,6 +51,8 @@ async def send(self, message: bytes) -> None: pass async def recv(self) -> bytes: + # Lets the refresh task start before the tunnel ends. + await asyncio.sleep(0) raise self._error @@ -67,6 +74,66 @@ async def sleep(self, seconds: float) -> None: self.waits.append(seconds) +class OpenConnection: + """Stays open until the CLI has sent ``closes_after`` frames, then its ``recv`` fails.""" + + def __init__(self, closes_after: int) -> None: + self.sent: list[Frame] = [] + self._closes_after = closes_after + self._closed = asyncio.Event() + + async def send(self, message: bytes) -> None: + self.sent.append(Frame.decode(message)) + if len(self.sent) >= self._closes_after: + self._closed.set() + + async def recv(self) -> bytes: + await self._closed.wait() + raise OSError("closed") + + +class OpenGateway: + def __init__(self, connection: OpenConnection) -> None: + self.connection = connection + self.waits: list[float] = [] + + @contextlib.asynccontextmanager + async def open(self, url: str, headers: dict[str, str]) -> AsyncIterator[OpenConnection]: + yield self.connection + + async def sleep(self, seconds: float) -> None: + self.waits.append(seconds) + + +class RefreshSleep: + """Records each wait before a refresh; the waits after the first ``returns`` never end.""" + + def __init__(self, returns: int) -> None: + self.waits: list[float] = [] + self._returns = returns + + async def __call__(self, seconds: float) -> None: + self.waits.append(seconds) + if len(self.waits) > self._returns: + await asyncio.Event().wait() + + +def _tokens(*results: str | CustomProxyGatewayToken | Exception) -> Callable[[], str | CustomProxyGatewayToken]: + remaining = list(results) + + def fetch() -> str | CustomProxyGatewayToken: + result = remaining.pop(0) + if isinstance(result, Exception): + raise result + return result + + return fetch + + +def _expiring_in(minutes: float, utc_suffix: str = "+00:00") -> str: + return (datetime.now(timezone.utc) + timedelta(minutes=minutes)).isoformat().replace("+00:00", utc_suffix) + + def _refused_handshake(status: int, outcome: str) -> InvalidStatus: return InvalidStatus(Response(status, "", Headers({ERROR_HEADER: outcome}))) @@ -77,37 +144,84 @@ def _gateway_token_claim(authorization: str) -> str: def _run( - gateway: ScriptedGateway, + gateway: ScriptedGateway | OpenGateway, signed_in_checks: list[bool], - gateway_token: Callable[[], str] = lambda: "token-1", + events: list[str] | None = None, + gateway_token: Callable[[], str | CustomProxyGatewayToken] = lambda: "token-1", + refresh_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, ) -> None: + recorded = events if events is not None else [] + + def fetch() -> CustomProxyGatewayToken: + token = gateway_token() + return token if isinstance(token, CustomProxyGatewayToken) else CustomProxyGatewayToken(gateway_token=token) + connection = GatewayConnection( gateway_url=GATEWAY_URL, linked_proxy_id="dp-1", key=Ed25519PrivateKey.generate(), signed_in=lambda: signed_in_checks.pop(0), - gateway_token=gateway_token, + gateway_token=fetch, + on_connected=lambda: recorded.append("connected"), + on_failed=recorded.append, open_websocket=gateway.open, sleep=gateway.sleep, + refresh_sleep=refresh_sleep, ) asyncio.run(connection.run()) @pytest.mark.parametrize( - ("outcome", "reason"), + ("refusal", "described"), [ - (Outcome(ConnectionClosed(Close(4001, "not_a_member"), None), opened=True), "not_a_member"), - (Outcome(_refused_handshake(401, "sign_in_refused")), "sign_in_refused"), + ( + Outcome(ConnectionClosed(Close(4001, "not_a_member"), None), opened=True), + "the gateway closed the connection (not_a_member)", + ), + ( + Outcome(_refused_handshake(401, "sign_in_refused")), + "the gateway refused the sign-in (is this computer's clock right?)", + ), ], ) -def test_refused_sign_in_stops_without_reconnecting(outcome, reason): - gateway = ScriptedGateway([outcome]) +def test_a_gateway_refusal_reconnects_and_gumloop_decides_whether_to_stop(refusal, described): + gateway = ScriptedGateway([refusal]) + events: list[str] = [] with pytest.raises(SignInRefused) as refused: - _run(gateway, [True]) + _run( + gateway, + [True, True], + events, + gateway_token=_tokens("token-1", SignInRefused("personal_custom_proxy_not_found")), + ) - assert refused.value.reason == reason - assert gateway.waits == [] + assert refused.value.reason == "personal_custom_proxy_not_found" + assert described in events + assert len(gateway.waits) == 1 + + +def test_other_failures_reconnect_with_a_growing_wait_until_signed_out(): + gateway = ScriptedGateway( + [ + Outcome(ConnectionClosed(Close(4002, "already_connected"), None), opened=True), + Outcome(OSError("unreachable")), + ] + ) + events: list[str] = [] + + with pytest.raises(SignedOut): + _run(gateway, [True, True, False], events) + + assert events == [ + "connected", + "the gateway closed the connection (already_connected)", + "can't reach the gateway (unreachable)", + ] + assert len(gateway.waits) == 2 + for wait, cap in zip(gateway.waits, [5.0, 10.0], strict=True): + assert FIRST_RETRY_SECONDS <= wait <= cap + assert len(set(gateway.authorizations)) == 2 @pytest.mark.parametrize( @@ -117,29 +231,35 @@ def test_refused_sign_in_stops_without_reconnecting(outcome, reason): Outcome(_refused_handshake(401, "gateway_token_refused")), ], ) -def test_other_failures_reconnect_with_a_fresh_gateway_token_and_a_growing_wait_until_signed_out( - monkeypatch, refused_token -): - monkeypatch.setattr(connection, "random", UpperBoundRandom()) - monkeypatch.setattr(connection, "time", FrozenTime()) - gateway = ScriptedGateway( - [ - Outcome(ConnectionClosed(Close(4002, "already_connected"), None), opened=True), - refused_token, - Outcome(OSError("unreachable")), - ] - ) - gateway_token = tokens("token-1", "token-2", GatewayTokenUnavailable("HTTP 503"), "token-3") +def test_a_refused_gateway_token_reconnects_with_a_fresh_one(refused_token): + gateway = ScriptedGateway([refused_token, Outcome(OSError("unreachable"))]) + tokens = iter(["token-1", "token-2"]) with pytest.raises(SignedOut): - _run(gateway, [True, True, True, True, False], gateway_token=gateway_token) + _run(gateway, [True, True, False], gateway_token=lambda: next(tokens)) - assert gateway.waits == [1.0, 2.0, 4.0, 8.0] - assert [_gateway_token_claim(authorization) for authorization in gateway.authorizations] == [ + assert [_gateway_token_claim(authorization) for authorization in gateway.authorizations] == ["token-1", "token-2"] + + +def test_a_gateway_token_gumloop_did_not_give_is_retried_before_connecting(): + gateway = ScriptedGateway([Outcome(OSError("unreachable"))]) + tokens: list[str | Exception] = [ + GatewayTokenUnavailable("Gumloop didn't give a gateway token (HTTP 503)"), "token-1", - "token-2", - "token-3", ] + events: list[str] = [] + + def gateway_token() -> str: + result = tokens.pop(0) + if isinstance(result, Exception): + raise result + return result + + with pytest.raises(SignedOut): + _run(gateway, [True, True, False], events, gateway_token=gateway_token) + + assert events == ["Gumloop didn't give a gateway token (HTTP 503)", "can't reach the gateway (unreachable)"] + assert [_gateway_token_claim(authorization) for authorization in gateway.authorizations] == ["token-1"] def test_a_gateway_token_refused_by_gumloop_stops_without_connecting(): @@ -153,3 +273,43 @@ def gateway_token() -> str: assert gateway.authorizations == [] assert gateway.waits == [] + + +@pytest.mark.parametrize("utc_suffix", ["+00:00", "Z"]) +def test_an_open_tunnel_sends_a_fresh_gateway_token_before_its_current_one_expires(utc_suffix): + gateway = OpenGateway(OpenConnection(closes_after=1)) + refresh_sleep = RefreshSleep(returns=1) + expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at=_expiring_in(20, utc_suffix)) + + with pytest.raises(SignedOut): + _run(gateway, [True, False], gateway_token=_tokens(expiring, "token-2"), refresh_sleep=refresh_sleep) + + assert refresh_sleep.waits == [pytest.approx(20 * 60 - REFRESH_BEFORE_EXPIRY_SECONDS, abs=5)] + assert gateway.connection.sent == [Frame.gateway_token("token-2")] + + +def test_a_gateway_token_without_an_expiry_is_never_refreshed(): + gateway = ScriptedGateway([Outcome(OSError("closed"), opened=True)]) + refresh_sleep = RefreshSleep(returns=0) + + with pytest.raises(SignedOut): + _run(gateway, [True, False], refresh_sleep=refresh_sleep) + + assert refresh_sleep.waits == [] + + +def test_a_gateway_token_refresh_gumloop_did_not_give_is_retried(): + gateway = OpenGateway(OpenConnection(closes_after=1)) + refresh_sleep = RefreshSleep(returns=2) + expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at=_expiring_in(10)) + + with pytest.raises(SignedOut): + _run( + gateway, + [True, False], + gateway_token=_tokens(expiring, GatewayTokenUnavailable("HTTP 503"), "token-2"), + refresh_sleep=refresh_sleep, + ) + + assert refresh_sleep.waits == [MIN_REFRESH_SECONDS, MIN_REFRESH_SECONDS] + assert gateway.connection.sent == [Frame.gateway_token("token-2")] diff --git a/tests/linked_proxy/test_tls_check.py b/tests/linked_proxy/test_tls_check.py new file mode 100644 index 0000000..339362c --- /dev/null +++ b/tests/linked_proxy/test_tls_check.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import contextlib +import socket +import ssl +import threading +from datetime import datetime +from datetime import timedelta +from datetime import timezone + +import pytest +from cryptography import x509 +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.serialization import Encoding +from cryptography.hazmat.primitives.serialization import NoEncryption +from cryptography.hazmat.primitives.serialization import PrivateFormat +from cryptography.x509.oid import NameOID + +from gumloop.linked_proxy.tls_check import TlsInspected +from gumloop.linked_proxy.tls_check import check_tls_not_inspected + + +def _privately_signed_server(tmp_path) -> ssl.SSLContext: + """What a TLS-inspecting proxy presents: a valid certificate for the host from a CA no public root trusts.""" + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")]) + now = datetime.now(timezone.utc) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=1)) + .not_valid_after(now + timedelta(days=1)) + .add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=False) + .sign(key, hashes.SHA256()) + ) + certificate_path, key_path = tmp_path / "server.pem", tmp_path / "server.key" + certificate_path.write_bytes(certificate.public_bytes(Encoding.PEM)) + key_path.write_bytes(key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(certificate_path, key_path) + return context + + +def test_a_certificate_from_a_private_ca_means_inspection(tmp_path): + context = _privately_signed_server(tmp_path) + listener = socket.create_server(("127.0.0.1", 0)) + + def serve() -> None: + connection, _ = listener.accept() + with connection, contextlib.suppress(OSError): + context.wrap_socket(connection, server_side=True).close() + + server = threading.Thread(target=serve, daemon=True) + server.start() + with listener, pytest.raises(TlsInspected): + check_tls_not_inspected("localhost", listener.getsockname()[1]) + server.join(timeout=5) + + +def test_an_unreachable_site_is_not_inspection(): + with socket.create_server(("127.0.0.1", 0)) as closed: + port = closed.getsockname()[1] + + check_tls_not_inspected("127.0.0.1", port) From 0fb9b5f519aa073ddc776c67621f622cc52f3439 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 00:51:16 +0000 Subject: [PATCH 02/14] [PROD-871] connect forgets the registration only if it is still the unlinked personal proxy's Co-authored-by: Cursor --- src/gumloop/cli/commands/custom_proxy.py | 7 ++++++- tests/cli/test_custom_proxy_command.py | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index 25f837b..48042fe 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -230,12 +230,14 @@ def connect( # The background service runs this too. A clean exit means the service should stay down. cli: CliContext = ctx.obj host = backend_host(cli.effective_base_url) + custom_proxy_id: str | None = None try: with custom_proxy_lock(host): registration = load_registration(host) if registration is None: error_console.print("This computer is not linked. Run `gumloop browser proxy link`.") return + custom_proxy_id = registration.custom_proxy_id key = load_or_create_key(host) if registration.public_key != public_key_text(key): forget_registration(host) @@ -276,7 +278,10 @@ def on_connected() -> None: exit_with_error(_tls_inspected_error(error)) except SignInRefused as refusal: if refusal.reason == _REMOVED: - forget_registration(host) + # `link` doesn't take the lock, so it may have saved a new registration meanwhile. + current = load_registration(host) + if current is not None and current.custom_proxy_id == custom_proxy_id: + forget_registration(host) error_console.print( "This computer was unlinked from Gumloop. Run `gumloop browser proxy link` to link it again." ) diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index c2c8986..b613e8a 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -146,6 +146,26 @@ async def run(self) -> None: assert not respx.calls +def test_a_refused_custom_proxy_keeps_a_registration_linked_while_it_was_connected(cli_runner, service, monkeypatch): + save_registration(HOST, _registration()) + relinked = _registration(custom_proxy_id="dp-2") + + class RefusedAfterRelinkConnection: + def __init__(self, **kwargs: object) -> None: + pass + + async def run(self) -> None: + save_registration(HOST, relinked) + raise SignInRefused("personal_custom_proxy_not_found") + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", RefusedAfterRelinkConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert result.exit_code == 0, result.output + assert load_registration(HOST) == relinked + + def test_connect_says_it_connected_once_across_reconnects(cli_runner, service, monkeypatch): save_registration(HOST, _registration()) From ba7d62ce3bac42f775fb9877074a325820b449e8 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 00:51:16 +0000 Subject: [PATCH 03/14] [PROD-871] Signing out or unlinking while connected ends the tunnel at the next gateway token refresh Co-authored-by: Cursor --- src/gumloop/linked_proxy/connection.py | 22 +++++++++++++--------- tests/linked_proxy/test_connection.py | 13 +++++++++++++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/src/gumloop/linked_proxy/connection.py b/src/gumloop/linked_proxy/connection.py index 6ea957a..9e58cd6 100644 --- a/src/gumloop/linked_proxy/connection.py +++ b/src/gumloop/linked_proxy/connection.py @@ -127,25 +127,29 @@ async def _serve(self) -> None: if self._on_connected is not None: self._on_connected() tunnel = Tunnel(websocket, on_open=self._on_open) - refresh = asyncio.ensure_future(self._refresh(tunnel, gateway_token)) + tasks = {asyncio.ensure_future(tunnel.run())} + # A gateway token without ``expires_at`` comes from a backend older than + # refreshes, whose gateway would reject one. + if gateway_token.expires_at is not None: + tasks.add(asyncio.ensure_future(self._refresh(tunnel, gateway_token))) try: - await tunnel.run() + done, _pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) finally: - refresh.cancel() - await asyncio.gather(refresh, return_exceptions=True) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + for task in done: + task.result() async def _refresh(self, tunnel: Tunnel, gateway_token: CustomProxyGatewayToken) -> None: - """Sends a fresh gateway token before each one expires. When Gumloop refuses one, the - gateway's own recheck closes the tunnel. A gateway token without ``expires_at`` comes - from a backend older than refreshes, whose gateway would reject one.""" + """Sends a fresh gateway token before each one expires, and ends the tunnel + by raising ``SignInRefused`` or ``SignedOut``.""" while gateway_token.expires_at is not None: await self._refresh_sleep(_seconds_until_refresh(gateway_token.expires_at)) try: gateway_token = await asyncio.to_thread(self._gateway_token) except GatewayTokenUnavailable: continue - except (SignInRefused, SignedOut): - return await tunnel.send_gateway_token(gateway_token.gateway_token) diff --git a/tests/linked_proxy/test_connection.py b/tests/linked_proxy/test_connection.py index 2244d4d..552c71b 100644 --- a/tests/linked_proxy/test_connection.py +++ b/tests/linked_proxy/test_connection.py @@ -313,3 +313,16 @@ def test_a_gateway_token_refresh_gumloop_did_not_give_is_retried(): assert refresh_sleep.waits == [MIN_REFRESH_SECONDS, MIN_REFRESH_SECONDS] assert gateway.connection.sent == [Frame.gateway_token("token-2")] + + +@pytest.mark.timeout(10) +@pytest.mark.parametrize("ended_by", [SignedOut(), SignInRefused("personal_custom_proxy_not_found")]) +def test_a_refresh_after_signing_out_or_unlinking_ends_the_open_tunnel(ended_by): + gateway = OpenGateway(OpenConnection(closes_after=1)) + expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at=_expiring_in(20)) + + with pytest.raises(type(ended_by)): + _run(gateway, [True], gateway_token=_tokens(expiring, ended_by), refresh_sleep=RefreshSleep(returns=1)) + + assert gateway.connection.sent == [] + assert gateway.waits == [] From 0a36cb2a164b855c54af13ca92120461bf87b520 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 00:51:17 +0000 Subject: [PATCH 04/14] [PROD-871] logout unlinks with the stored login, not a credential override Co-authored-by: Cursor --- src/gumloop/cli/commands/auth.py | 5 ++--- src/gumloop/cli/commands/custom_proxy.py | 6 ++++++ tests/cli/test_custom_proxy_command.py | 12 ++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/gumloop/cli/commands/auth.py b/src/gumloop/cli/commands/auth.py index bab1a1e..eb51dfb 100644 --- a/src/gumloop/cli/commands/auth.py +++ b/src/gumloop/cli/commands/auth.py @@ -12,7 +12,7 @@ from gumloop import Gumloop from gumloop import GumloopError -from gumloop.cli.commands.custom_proxy import remove_custom_proxy +from gumloop.cli.commands.custom_proxy import remove_stored_login_custom_proxy from gumloop.cli.console import console from gumloop.cli.console import print_json from gumloop.cli.context import CliContext @@ -21,7 +21,6 @@ from gumloop.cli.credentials import keyring_backend_name from gumloop.cli.credentials import save_credentials from gumloop.cli.errors import exit_with_error -from gumloop.cli.custom_proxy_key import backend_host from gumloop.cli.oauth import DEFAULT_REDIRECT_PORT from gumloop.cli.oauth import perform_oauth_login from gumloop.cli.oauth import revoke_oauth_token @@ -213,7 +212,7 @@ def logout( custom_proxy_removed = False custom_proxy_error: str | None = None try: - custom_proxy_removed = remove_custom_proxy(cli, backend_host(cli.effective_base_url)) + custom_proxy_removed = remove_stored_login_custom_proxy() except (GumloopError, httpx.HTTPError) as error: custom_proxy_error = str(error) diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index 48042fe..a81c7e1 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -218,6 +218,12 @@ def remove_custom_proxy(cli: CliContext, host: str) -> bool: return service_installed or registration is not None +def remove_stored_login_custom_proxy() -> bool: + """Unlinks the stored login's personal proxy, whatever overrides the current command has.""" + credentials = _stored_credentials() + return remove_custom_proxy(CliContext(credentials=credentials), _login_host(credentials)) + + @proxy_app.command("connect") def connect( ctx: typer.Context, diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index b613e8a..c38d2df 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -452,6 +452,18 @@ def test_removing_deletes_the_custom_proxy_then_the_key(cli_runner, service, com assert load_registration(HOST) is None +@respx.mock +def test_logout_unlinks_with_the_stored_login_not_a_credential_override(cli_runner, service): + save_registration(HOST, _registration()) + route = respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(204) + + result = cli_runner.invoke(app, ["logout"], env={"GUMLOOP_API_KEY": "someone-elses-key"}) + + assert result.exit_code == 0, result.output + assert route.calls.last.request.headers["Authorization"] == "Bearer key" + assert load_registration(HOST) is None + + @pytest.mark.parametrize(("login_has_custom_proxy", "kept"), [(True, True), (False, False)]) def test_removing_another_backends_custom_proxy_keeps_the_service_only_while_the_login_needs_it( cli_runner, service, login_has_custom_proxy, kept From 07a5c99125ca10aee25a22b22d6a6d3540dcfc18 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:27:38 +0000 Subject: [PATCH 05/14] [PROD-871] The CLI names its tunnel version, stops when the gateway needs a newer one, and says connected only once the tunnel is ready --- src/gumloop/cli/commands/custom_proxy.py | 6 +++ src/gumloop/linked_proxy/connection.py | 56 +++++++++++++++--------- tests/cli/test_custom_proxy_command.py | 20 +++++++++ tests/linked_proxy/test_connection.py | 47 ++++++++++++++++++-- 4 files changed, 105 insertions(+), 24 deletions(-) diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index a81c7e1..d36307a 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -49,6 +49,7 @@ from gumloop.linked_proxy.connection import GatewayTokenUnavailable from gumloop.linked_proxy.connection import SignedOut from gumloop.linked_proxy.connection import SignInRefused +from gumloop.linked_proxy.connection import UpgradeRequired from gumloop.linked_proxy.destinations import Target from gumloop.linked_proxy.sign_in import public_key_text from gumloop.linked_proxy.tls_check import TlsInspected @@ -304,6 +305,11 @@ def on_connected() -> None: ) else: error_console.print("You logged out of Gumloop, so this computer disconnected.") + except UpgradeRequired: + error_console.print( + "This version of the Gumloop CLI is too old to connect this computer. " + "Run `gumloop update`, then `gumloop browser proxy link`." + ) except KeyboardInterrupt: console.print("Stopped.") except GumloopError as error: diff --git a/src/gumloop/linked_proxy/connection.py b/src/gumloop/linked_proxy/connection.py index 9e58cd6..5b5a458 100644 --- a/src/gumloop/linked_proxy/connection.py +++ b/src/gumloop/linked_proxy/connection.py @@ -1,6 +1,6 @@ """Keeps this machine's tunnel to the linked proxy gateway open: signs in, serves the -gateway's streams, and reconnects until Gumloop refuses a gateway token or the -user signs out.""" +gateway's streams, and reconnects until Gumloop refuses a gateway token, the +user signs out, or the gateway needs a newer CLI.""" from __future__ import annotations @@ -32,6 +32,11 @@ # The gateway's refusal header for a sign-in it won't accept. ERROR_HEADER = "X-Gumloop-Linked-Proxy-Error" SIGN_IN_REFUSED = "sign_in_refused" +UPGRADE_REQUIRED = "cli_upgrade_required" +# The tunnel protocol this CLI speaks. The gateway only sends a frame type to CLIs +# whose version has it, and refuses versions it no longer supports. +TUNNEL_VERSION_HEADER = "Gumloop-Tunnel-Version" +TUNNEL_VERSION = 1 FIRST_RETRY_SECONDS = 1.0 # Spreads out the linked proxies that all reconnect at once when a gateway replica restarts. @@ -65,6 +70,10 @@ class GatewayTokenUnavailable(Exception): """Gumloop didn't hand out a gateway token this time; the connection retries.""" +class UpgradeRequired(Exception): + """The gateway no longer accepts this CLI's tunnel protocol.""" + + class GatewayConnection: def __init__( self, @@ -94,7 +103,7 @@ def __init__( self._refresh_sleep = refresh_sleep async def run(self) -> None: - """Runs until it raises ``SignInRefused`` or ``SignedOut``. Every other + """Runs until it raises ``SignInRefused``, ``SignedOut`` or ``UpgradeRequired``. Every other failure reconnects after a random wait whose cap doubles up to ``MAX_RETRY_SECONDS``. ``gateway_token`` runs in a thread before each connect and each refresh, and raises ``SignInRefused`` or ``GatewayTokenUnavailable`` when it has no token. A gateway @@ -123,23 +132,30 @@ async def _serve(self) -> None: audience=self._gateway_url, gateway_token=gateway_token.gateway_token, ) - async with self._open(self._gateway_url, {"Authorization": f"Bearer {token}"}) as websocket: - if self._on_connected is not None: - self._on_connected() - tunnel = Tunnel(websocket, on_open=self._on_open) - tasks = {asyncio.ensure_future(tunnel.run())} - # A gateway token without ``expires_at`` comes from a backend older than - # refreshes, whose gateway would reject one. - if gateway_token.expires_at is not None: - tasks.add(asyncio.ensure_future(self._refresh(tunnel, gateway_token))) - try: - done, _pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) - finally: - for task in tasks: - task.cancel() - await asyncio.gather(*tasks, return_exceptions=True) - for task in done: - task.result() + headers = {"Authorization": f"Bearer {token}", TUNNEL_VERSION_HEADER: str(TUNNEL_VERSION)} + try: + async with self._open(self._gateway_url, headers) as websocket: + await self._serve_tunnel(websocket, gateway_token) + except InvalidStatus as error: + if error.response.headers.get(ERROR_HEADER) == UPGRADE_REQUIRED: + raise UpgradeRequired() from error + raise + + async def _serve_tunnel(self, websocket: Connection, gateway_token: CustomProxyGatewayToken) -> None: + tunnel = Tunnel(websocket, on_open=self._on_open, on_ready=self._on_connected) + tasks = {asyncio.ensure_future(tunnel.run())} + # A gateway token without ``expires_at`` comes from a backend older than + # refreshes, whose gateway would reject one. + if gateway_token.expires_at is not None: + tasks.add(asyncio.ensure_future(self._refresh(tunnel, gateway_token))) + try: + done, _pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + for task in done: + task.result() async def _refresh(self, tunnel: Tunnel, gateway_token: CustomProxyGatewayToken) -> None: """Sends a fresh gateway token before each one expires, and ends the tunnel diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index c38d2df..4b39948 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -24,6 +24,7 @@ from gumloop.cli.main import app from gumloop.linked_proxy.connection import GatewayTokenUnavailable from gumloop.linked_proxy.connection import SignInRefused +from gumloop.linked_proxy.connection import UpgradeRequired from gumloop.linked_proxy.destinations import Target from gumloop.linked_proxy.sign_in import public_key_text from gumloop.types import CustomProxyGatewayToken @@ -238,6 +239,25 @@ async def run(self) -> None: assert expected in " ".join(result.stderr.split()) +def test_connect_stops_when_the_gateway_needs_a_newer_cli(cli_runner, service, monkeypatch): + save_registration(HOST, _registration()) + + class OutdatedConnection: + def __init__(self, **kwargs: object) -> None: + pass + + async def run(self) -> None: + raise UpgradeRequired() + + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", OutdatedConnection) + + result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) + + assert result.exit_code == 0, result.output + assert load_registration(HOST) == _registration() + assert "Run `gumloop update`, then `gumloop browser proxy link`." in " ".join(result.stderr.split()) + + @pytest.mark.parametrize( ("status", "payload", "expected"), [ diff --git a/tests/linked_proxy/test_connection.py b/tests/linked_proxy/test_connection.py index 552c71b..2ffe8df 100644 --- a/tests/linked_proxy/test_connection.py +++ b/tests/linked_proxy/test_connection.py @@ -24,11 +24,15 @@ from gumloop.linked_proxy.connection import FIRST_RETRY_SECONDS from gumloop.linked_proxy.connection import MIN_REFRESH_SECONDS from gumloop.linked_proxy.connection import REFRESH_BEFORE_EXPIRY_SECONDS +from gumloop.linked_proxy.connection import TUNNEL_VERSION +from gumloop.linked_proxy.connection import TUNNEL_VERSION_HEADER from gumloop.linked_proxy.connection import GatewayConnection from gumloop.linked_proxy.connection import GatewayTokenUnavailable from gumloop.linked_proxy.connection import SignedOut from gumloop.linked_proxy.connection import SignInRefused +from gumloop.linked_proxy.connection import UpgradeRequired from gumloop.linked_proxy.frames import Frame +from gumloop.linked_proxy.frames import FrameType from gumloop.types import CustomProxyGatewayToken GATEWAY_URL = "wss://linked-proxy-gateway.gumloop.com/v1/cli/connect" @@ -37,15 +41,17 @@ @dataclass(frozen=True) class Outcome: """How one connect attempt ends: ``error`` is raised while opening the - WebSocket, or by its first ``recv`` when ``opened``.""" + WebSocket, or by ``recv`` when ``opened``, after a READY frame when ``ready``.""" error: BaseException opened: bool = False + ready: bool = False class FailingConnection: - def __init__(self, error: BaseException) -> None: + def __init__(self, error: BaseException, ready: bool = False) -> None: self._error = error + self._ready = ready async def send(self, message: bytes) -> None: pass @@ -53,6 +59,9 @@ async def send(self, message: bytes) -> None: async def recv(self) -> bytes: # Lets the refresh task start before the tunnel ends. await asyncio.sleep(0) + if self._ready: + self._ready = False + return Frame(type=FrameType.READY, stream_id=0).encode() raise self._error @@ -60,15 +69,17 @@ class ScriptedGateway: def __init__(self, outcomes: list[Outcome]) -> None: self._outcomes = outcomes self.authorizations: list[str] = [] + self.versions: list[str] = [] self.waits: list[float] = [] @contextlib.asynccontextmanager async def open(self, url: str, headers: dict[str, str]) -> AsyncIterator[FailingConnection]: self.authorizations.append(headers["Authorization"]) + self.versions.append(headers[TUNNEL_VERSION_HEADER]) outcome = self._outcomes.pop(0) if not outcome.opened: raise outcome.error - yield FailingConnection(outcome.error) + yield FailingConnection(outcome.error, outcome.ready) async def sleep(self, seconds: float) -> None: self.waits.append(seconds) @@ -214,7 +225,6 @@ def test_other_failures_reconnect_with_a_growing_wait_until_signed_out(): _run(gateway, [True, True, False], events) assert events == [ - "connected", "the gateway closed the connection (already_connected)", "can't reach the gateway (unreachable)", ] @@ -224,6 +234,35 @@ def test_other_failures_reconnect_with_a_growing_wait_until_signed_out(): assert len(set(gateway.authorizations)) == 2 +def test_it_is_connected_only_once_the_gateway_says_the_tunnel_is_ready(): + gateway = ScriptedGateway( + [ + Outcome(ConnectionClosed(Close(4002, "already_connected"), None), opened=True), + Outcome(ConnectionClosed(None, None), opened=True, ready=True), + ] + ) + events: list[str] = [] + + with pytest.raises(SignedOut): + _run(gateway, [True, True, False], events) + + assert events == [ + "the gateway closed the connection (already_connected)", + "connected", + "the connection dropped", + ] + assert gateway.versions == [str(TUNNEL_VERSION)] * 2 + + +def test_a_gateway_that_needs_a_newer_cli_stops_without_retrying(): + gateway = ScriptedGateway([Outcome(_refused_handshake(426, "cli_upgrade_required"))]) + + with pytest.raises(UpgradeRequired): + _run(gateway, [True]) + + assert gateway.waits == [] + + @pytest.mark.parametrize( "refused_token", [ From 01714e88ef1043d7274398a823b8a9a25573939f Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:27:38 +0000 Subject: [PATCH 06/14] [PROD-871] Logging out ends an open tunnel within a minute, not at the next gateway token refresh Co-authored-by: Cursor --- src/gumloop/linked_proxy/connection.py | 14 +++++++++++++- tests/linked_proxy/test_connection.py | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/gumloop/linked_proxy/connection.py b/src/gumloop/linked_proxy/connection.py index 5b5a458..40d15e4 100644 --- a/src/gumloop/linked_proxy/connection.py +++ b/src/gumloop/linked_proxy/connection.py @@ -50,6 +50,8 @@ REFRESH_BEFORE_EXPIRY_SECONDS = 15 * 60.0 # The least time between refreshes, which is also the wait before retrying a failed one. MIN_REFRESH_SECONDS = 60.0 +# How often an open tunnel checks that the user who linked this computer is still logged in. +LOGIN_CHECK_SECONDS = 60.0 Open = Callable[[str, dict[str, str]], AbstractAsyncContextManager[Connection]] @@ -89,6 +91,7 @@ def __init__( open_websocket: Open | None = None, sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, refresh_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, + login_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, ) -> None: self._gateway_url = gateway_url self._linked_proxy_id = linked_proxy_id @@ -101,6 +104,7 @@ def __init__( self._open = open_websocket or _open_websocket self._sleep = sleep self._refresh_sleep = refresh_sleep + self._login_sleep = login_sleep async def run(self) -> None: """Runs until it raises ``SignInRefused``, ``SignedOut`` or ``UpgradeRequired``. Every other @@ -143,7 +147,7 @@ async def _serve(self) -> None: async def _serve_tunnel(self, websocket: Connection, gateway_token: CustomProxyGatewayToken) -> None: tunnel = Tunnel(websocket, on_open=self._on_open, on_ready=self._on_connected) - tasks = {asyncio.ensure_future(tunnel.run())} + tasks = {asyncio.ensure_future(tunnel.run()), asyncio.ensure_future(self._watch_login())} # A gateway token without ``expires_at`` comes from a backend older than # refreshes, whose gateway would reject one. if gateway_token.expires_at is not None: @@ -157,6 +161,14 @@ async def _serve_tunnel(self, websocket: Connection, gateway_token: CustomProxyG for task in done: task.result() + async def _watch_login(self) -> None: + """Ends the tunnel by raising ``SignedOut`` once the user who linked this + computer logs out or in as someone else, without waiting for a refresh.""" + while True: + await self._login_sleep(LOGIN_CHECK_SECONDS) + if not await asyncio.to_thread(self._signed_in): + raise SignedOut() + async def _refresh(self, tunnel: Tunnel, gateway_token: CustomProxyGatewayToken) -> None: """Sends a fresh gateway token before each one expires, and ends the tunnel by raising ``SignInRefused`` or ``SignedOut``.""" diff --git a/tests/linked_proxy/test_connection.py b/tests/linked_proxy/test_connection.py index 2ffe8df..a2289a0 100644 --- a/tests/linked_proxy/test_connection.py +++ b/tests/linked_proxy/test_connection.py @@ -22,6 +22,7 @@ from gumloop.linked_proxy.connection import ERROR_HEADER from gumloop.linked_proxy.connection import FIRST_RETRY_SECONDS +from gumloop.linked_proxy.connection import LOGIN_CHECK_SECONDS from gumloop.linked_proxy.connection import MIN_REFRESH_SECONDS from gumloop.linked_proxy.connection import REFRESH_BEFORE_EXPIRY_SECONDS from gumloop.linked_proxy.connection import TUNNEL_VERSION @@ -154,12 +155,17 @@ def _gateway_token_claim(authorization: str) -> str: return json.loads(base64.urlsafe_b64decode(claims + "=" * (-len(claims) % 4)))["gateway_token"] +async def _never(seconds: float) -> None: + await asyncio.Event().wait() + + def _run( gateway: ScriptedGateway | OpenGateway, signed_in_checks: list[bool], events: list[str] | None = None, gateway_token: Callable[[], str | CustomProxyGatewayToken] = lambda: "token-1", refresh_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, + login_sleep: Callable[[float], Awaitable[None]] = _never, ) -> None: recorded = events if events is not None else [] @@ -178,6 +184,7 @@ def fetch() -> CustomProxyGatewayToken: open_websocket=gateway.open, sleep=gateway.sleep, refresh_sleep=refresh_sleep, + login_sleep=login_sleep, ) asyncio.run(connection.run()) @@ -263,6 +270,21 @@ def test_a_gateway_that_needs_a_newer_cli_stops_without_retrying(): assert gateway.waits == [] +@pytest.mark.timeout(10) +def test_logging_out_ends_the_open_tunnel_before_the_next_refresh(): + gateway = OpenGateway(OpenConnection(closes_after=1)) + login_waits: list[float] = [] + + async def login_sleep(seconds: float) -> None: + login_waits.append(seconds) + + with pytest.raises(SignedOut): + _run(gateway, [True, False], login_sleep=login_sleep) + + assert login_waits == [LOGIN_CHECK_SECONDS] + assert gateway.waits == [] + + @pytest.mark.parametrize( "refused_token", [ From b2189f6b3630e0d1e44387d65ab3c2ba504ff02c Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:27:50 +0000 Subject: [PATCH 07/14] [PROD-871] connect keeps a lost key's registration and stops on any refusal that won't pass on its own; link always registers and replaces a lost key's personal proxy Co-authored-by: Cursor --- src/gumloop/cli/commands/custom_proxy.py | 70 ++++++++++---- src/gumloop/cli/custom_proxy_key.py | 24 +++-- tests/cli/test_custom_proxy_command.py | 118 +++++++++++++++++------ 3 files changed, 159 insertions(+), 53 deletions(-) diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index d36307a..52f02a0 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -34,6 +34,7 @@ from gumloop.cli.custom_proxy_key import forget_connection_status from gumloop.cli.custom_proxy_key import forget_registration from gumloop.cli.custom_proxy_key import load_connection_status +from gumloop.cli.custom_proxy_key import load_key from gumloop.cli.custom_proxy_key import load_or_create_key from gumloop.cli.custom_proxy_key import load_registration from gumloop.cli.custom_proxy_key import save_connection_status @@ -75,6 +76,11 @@ } # The only refusal that forgets the registration. _REMOVED = "personal_custom_proxy_not_found" +# Also what the API answers when the rollout flag can't be read, so connect retries it. +_NOT_RELEASED = "route_not_found" +_RETRIED_STATUSES = frozenset({408, 409, 429}) +# Gumloop answered 401 to a login that can't be refreshed, such as a revoked API key. +_LOGIN_REJECTED = "login_rejected" @proxy_app.command( @@ -115,13 +121,12 @@ def link( raise GumloopError( "This computer is linked to another Gumloop user. Run `gumloop browser proxy unlink`, then link again." ) - if registration is None or registration.public_key != public_key_text(key): - _register(cli, host, key, name) + _register(cli, host, key, name, registration) if service is not None and executable is not None: service.install(executable) except TlsInspected as error: exit_with_error(_tls_inspected_error(error)) - except (GumloopError, ValidationError) as error: + except (GumloopError, ValidationError, httpx.HTTPError) as error: exit_with_error(_explained(error)) if service is None: @@ -209,12 +214,7 @@ def remove_custom_proxy(cli: CliContext, host: str) -> bool: if service is not None and service_installed: service.remove() if registration is not None: - custom_proxy_id = registration.custom_proxy_id - try: - cli.call_with_refresh(lambda client: client.custom_proxies.delete(custom_proxy_id)) - except APIStatusError as error: - if error.status_code != 404: - raise + _delete_custom_proxy(cli, registration.custom_proxy_id) forget(host) return service_installed or registration is not None @@ -245,9 +245,9 @@ def connect( error_console.print("This computer is not linked. Run `gumloop browser proxy link`.") return custom_proxy_id = registration.custom_proxy_id - key = load_or_create_key(host) - if registration.public_key != public_key_text(key): - forget_registration(host) + # The registration stays, so `link` can replace its personal proxy in Gumloop. + key = load_key(host) + if key is None or registration.public_key != public_key_text(key): error_console.print( "This computer's personal proxy key is gone from the OS keychain. " "Run `gumloop browser proxy link` to link it again." @@ -292,6 +292,11 @@ def on_connected() -> None: error_console.print( "This computer was unlinked from Gumloop. Run `gumloop browser proxy link` to link it again." ) + elif refusal.reason == _LOGIN_REJECTED: + error_console.print( + "Gumloop no longer accepts your login, so this computer disconnected. " + "Run `gumloop login`, then `gumloop browser proxy link`." + ) else: reason = _UNAVAILABLE_REASONS.get(refusal.reason, "You can't use personal proxies right now.") error_console.print( @@ -364,8 +369,8 @@ def _login_user_id(credentials: Credentials) -> str | None: def _gateway_token(host: str, registration: CustomProxyRegistration) -> CustomProxyGatewayToken: - """Only the codes that say the personal proxy is gone or unavailable to its owner stop the - personal proxy. Any other refusal is retried.""" + """A refusal stops the personal proxy, except the ones that can pass on their own: a timeout, + a conflict, rate limiting, and ``route_not_found``.""" # The service outlives logins, so each request uses the login stored now, not the one it started with. credentials = _owner_login(host, registration) if credentials is None: @@ -376,15 +381,22 @@ def _gateway_token(host: str, registration: CustomProxyRegistration) -> CustomPr ) except APIStatusError as error: code = error.code if isinstance(error.code, str) else None - if code is not None and (code == _REMOVED or code in _UNAVAILABLE_REASONS): - raise SignInRefused(code) from error + if error.status_code == 401: + raise SignInRefused(_LOGIN_REJECTED) from error + if 400 <= error.status_code < 500 and error.status_code not in _RETRIED_STATUSES and code != _NOT_RELEASED: + raise SignInRefused(code or f"http_{error.status_code}") from error raise GatewayTokenUnavailable(f"Gumloop didn't give a gateway token (HTTP {error.status_code})") from error except (GumloopError, httpx.HTTPError) as error: raise GatewayTokenUnavailable(f"Gumloop didn't give a gateway token ({error})") from error return response -def _register(cli: CliContext, host: str, key: Ed25519PrivateKey, name: str | None) -> CustomProxyRegistration: +def _register( + cli: CliContext, host: str, key: Ed25519PrivateKey, name: str | None, previous: CustomProxyRegistration | None +) -> None: + """Registering this key again gets its personal proxy, or a new one if it was unlinked in Gumloop. A previous + registration of a key the keychain lost is unusable, so its personal proxy is replaced and its default kept.""" + replaced = previous if previous is not None and previous.public_key != public_key_text(key) else None machine_name = socket.gethostname() response = cli.call_with_refresh( lambda client: client.custom_proxies.register_cli( @@ -402,9 +414,31 @@ def _register(cli: CliContext, host: str, key: Ed25519PrivateKey, name: str | No user_id=_login_user_id(_stored_credentials()), ) save_registration(host, registration) + # Deleted only now, so a failed registration leaves the lost key's personal proxy and its default in place. + keep_default = replaced is not None and _delete_lost_custom_proxy(cli, replaced.custom_proxy_id) + if keep_default and not response.custom_proxy.is_default: + cli.call_with_refresh(lambda client: client.custom_proxies.set_default(registration.custom_proxy_id)) added_name = escape_markup(response.custom_proxy.name) console.print(f"Linked this computer to Gumloop as '{added_name}'.") - return registration + + +def _delete_lost_custom_proxy(cli: CliContext, custom_proxy_id: str) -> bool: + """Returns whether it was the default.""" + listed = cli.call_with_refresh(lambda client: client.custom_proxies.list()) + lost = next((custom_proxy for custom_proxy in listed.custom_proxies if custom_proxy.id == custom_proxy_id), None) + if lost is None: + return False + _delete_custom_proxy(cli, custom_proxy_id) + return lost.is_default + + +def _delete_custom_proxy(cli: CliContext, custom_proxy_id: str) -> None: + """One Gumloop no longer has counts as deleted.""" + try: + cli.call_with_refresh(lambda client: client.custom_proxies.delete(custom_proxy_id)) + except APIStatusError as error: + if error.code != _REMOVED: + raise def _service_or_none() -> CustomProxyService | None: diff --git a/src/gumloop/cli/custom_proxy_key.py b/src/gumloop/cli/custom_proxy_key.py index 4071ec0..89f91aa 100644 --- a/src/gumloop/cli/custom_proxy_key.py +++ b/src/gumloop/cli/custom_proxy_key.py @@ -67,17 +67,27 @@ def backend_host(base_url: str) -> str: def load_or_create_key(host: str) -> Ed25519PrivateKey: + key = load_key(host) + if key is not None: + return key + key = Ed25519PrivateKey.generate() + raw = key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption()) + try: + keyring.set_password(KEYRING_SERVICE, _key_account(host), base64.urlsafe_b64encode(raw).decode()) + except keyring.errors.KeyringError as error: + raise GumloopError(f"Could not use the personal proxy key in the OS keychain: {error}") from error + return key + + +def load_key(host: str) -> Ed25519PrivateKey | None: + """None when the keychain has no key for this backend.""" require_keyring() - account = _key_account(host) try: - stored = keyring.get_password(KEYRING_SERVICE, account) - if stored is None: - key = Ed25519PrivateKey.generate() - raw = key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption()) - keyring.set_password(KEYRING_SERVICE, account, base64.urlsafe_b64encode(raw).decode()) - return key + stored = keyring.get_password(KEYRING_SERVICE, _key_account(host)) except keyring.errors.KeyringError as error: raise GumloopError(f"Could not use the personal proxy key in the OS keychain: {error}") from error + if stored is None: + return None try: return Ed25519PrivateKey.from_private_bytes(base64.urlsafe_b64decode(stored)) except ValueError as error: diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index 4b39948..af1820b 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -32,6 +32,10 @@ HOST = "api.gumloop.com" GATEWAY_URL = "wss://linked-proxy-gateway.gumloop.com/v1/cli/connect" +REGISTERED = { + "custom_proxy": {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": True}, + "gateway_url": GATEWAY_URL, +} def _registration(**changes: str) -> CustomProxyRegistration: @@ -77,13 +81,7 @@ def service(monkeypatch) -> FakeService: @respx.mock def test_add_registers_and_turns_on_the_service(cli_runner, service, fake_executable_path): - route = respx.post(f"{API_BASE}/custom-proxies").respond( - 201, - json={ - "custom_proxy": {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": True}, - "gateway_url": GATEWAY_URL, - }, - ) + route = respx.post(f"{API_BASE}/custom-proxies").respond(201, json=REGISTERED) result = cli_runner.invoke(app, ["browser", "proxy", "link"]) @@ -93,19 +91,25 @@ def test_add_registers_and_turns_on_the_service(cli_runner, service, fake_execut assert service.executable == fake_executable_path / "gumloop" +@respx.mock +def test_link_registers_again_when_already_linked_and_saves_the_current_gateway(cli_runner, service): + save_registration(HOST, _registration(gateway_url="wss://old-gateway.gumloop.com/v1/cli/connect")) + route = respx.post(f"{API_BASE}/custom-proxies").respond(201, json=REGISTERED) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 0, result.output + assert route.called + assert load_registration(HOST) == _registration() + + @respx.mock def test_link_without_a_background_service_registers_and_points_to_connect(cli_runner, service, monkeypatch): def no_background_service() -> FakeService: raise NoBackgroundService("no systemd user session") monkeypatch.setattr("gumloop.cli.commands.custom_proxy.service_for_current_platform", no_background_service) - respx.post(f"{API_BASE}/custom-proxies").respond( - 201, - json={ - "custom_proxy": {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": True}, - "gateway_url": GATEWAY_URL, - }, - ) + respx.post(f"{API_BASE}/custom-proxies").respond(201, json=REGISTERED) result = cli_runner.invoke(app, ["browser", "proxy", "link"]) @@ -215,7 +219,8 @@ async def run(self) -> None: True, "Your organization's roles don't allow you to use personal proxies.", ), - ("route_not_found", True, "Personal proxies aren't available for your organization yet."), + ("login_rejected", True, "Gumloop no longer accepts your login"), + ("paid_plan_required", True, "You can't use personal proxies right now."), ], ) def test_connect_keeps_the_registration_unless_the_custom_proxy_was_removed( @@ -290,9 +295,11 @@ def test_link_says_why_personal_proxies_are_off(cli_runner, service, status, pay (404, {"error": {"code": "personal_custom_proxy_not_found"}}, None, False), (403, {"error": "policy_denied", "denied_keys": ["organization:use_personal_proxies"]}, None, True), (403, {"error": {"code": "organization_permission_required"}}, None, True), - (404, {"error": "route_not_found"}, None, True), - (403, {"error": {"code": "not_a_code_the_cli_knows"}}, GatewayTokenUnavailable, True), - (404, {"error": "not_found"}, GatewayTokenUnavailable, True), + (403, {"error": {"code": "not_a_code_the_cli_knows"}}, None, True), + (404, {"error": "not_found"}, None, True), + (401, {"error": "unauthorized"}, None, True), + (404, {"error": "route_not_found"}, GatewayTokenUnavailable, True), + (429, {"error": "rate_limited"}, GatewayTokenUnavailable, True), ], ) @respx.mock @@ -371,8 +378,14 @@ async def run(self) -> None: assert "You logged in to Gumloop as someone else" in " ".join(result.stderr.split()) -def test_connect_forgets_a_registration_whose_key_is_gone(cli_runner, service, monkeypatch): - save_registration(HOST, _registration(public_key="a key the keychain no longer has")) +@pytest.mark.parametrize("keychain", ["changed", "empty"]) +def test_connect_with_a_lost_key_stops_without_making_one_and_keeps_the_registration( + cli_runner, service, monkeypatch, keychain +): + lost = _registration(public_key="a key the keychain no longer has") + save_registration(HOST, lost) + if keychain == "empty": + keyring.delete_password(KEYRING_SERVICE, f"custom-proxy:{HOST}") class UnusedConnection: def __init__(self, **kwargs: object) -> None: @@ -383,14 +396,59 @@ def __init__(self, **kwargs: object) -> None: result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) assert result.exit_code == 0, result.output - assert load_registration(HOST) is None + assert load_registration(HOST) == lost + assert (keyring.get_password(KEYRING_SERVICE, f"custom-proxy:{HOST}") is None) is (keychain == "empty") assert "key is gone from the OS keychain" in " ".join(result.stderr.split()) +@pytest.mark.parametrize(("was_default", "default_route_called"), [(True, True), (False, False)]) @respx.mock -def test_link_registers_again_when_the_keychain_key_changed(cli_runner, service): +def test_link_replaces_the_custom_proxy_of_a_lost_key_and_keeps_its_default( + cli_runner, service, was_default, default_route_called +): save_registration(HOST, _registration(public_key="a key the keychain no longer has")) - route = respx.post(f"{API_BASE}/custom-proxies").respond( + lost = {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": was_default} + replacement = {"id": "dp-2", "name": "Ada's laptop", "kind": "cli", "is_default": False} + respx.get(f"{API_BASE}/custom-proxies").respond(200, json={"custom_proxies": [lost], "limit": 5}) + deleted = respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(204) + registered = respx.post(f"{API_BASE}/custom-proxies").respond( + 201, json={"custom_proxy": replacement, "gateway_url": GATEWAY_URL} + ) + made_default = respx.post(f"{API_BASE}/custom-proxies/dp-2/default").respond( + 200, json={"custom_proxy": {**replacement, "is_default": True}} + ) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 0, result.output + assert deleted.called + assert registered.called + assert made_default.called is default_route_called + assert load_registration(HOST) == _registration(custom_proxy_id="dp-2") + + +@respx.mock +def test_link_with_a_lost_key_keeps_its_custom_proxy_when_registering_fails(cli_runner, service): + lost = _registration(public_key="a key the keychain no longer has") + save_registration(HOST, lost) + listed = {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": True} + respx.get(f"{API_BASE}/custom-proxies").respond(200, json={"custom_proxies": [listed], "limit": 5}) + deleted = respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(204) + respx.post(f"{API_BASE}/custom-proxies").respond(422, json={"error": "invalid_request"}) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code != 0 + assert not deleted.called + assert load_registration(HOST) == lost + + +@respx.mock +def test_link_with_a_lost_key_registers_when_gumloop_already_removed_its_custom_proxy(cli_runner, service): + save_registration(HOST, _registration(public_key="a key the keychain no longer has")) + respx.get(f"{API_BASE}/custom-proxies").respond(200, json={"custom_proxies": [], "limit": 5}) + deleted = respx.delete(f"{API_BASE}/custom-proxies/dp-1") + respx.post(f"{API_BASE}/custom-proxies").respond( 201, json={ "custom_proxy": {"id": "dp-2", "name": "Ada's laptop", "kind": "cli", "is_default": True}, @@ -401,7 +459,7 @@ def test_link_registers_again_when_the_keychain_key_changed(cli_runner, service) result = cli_runner.invoke(app, ["browser", "proxy", "link"]) assert result.exit_code == 0, result.output - assert route.called + assert not deleted.called assert load_registration(HOST) == _registration(custom_proxy_id="dp-2") @@ -456,12 +514,15 @@ def no_background_service() -> FakeService: @pytest.mark.parametrize("command", [["browser", "proxy", "unlink"], ["logout"]]) +@pytest.mark.parametrize( + ("status", "payload"), [(204, None), (404, {"error": {"code": "personal_custom_proxy_not_found"}})] +) @respx.mock -def test_removing_deletes_the_custom_proxy_then_the_key(cli_runner, service, command): +def test_removing_deletes_the_custom_proxy_then_the_key(cli_runner, service, command, status, payload): service.installed = True save_registration(HOST, _registration()) load_or_create_key(HOST) - route = respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(204) + route = respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(status, json=payload) result = cli_runner.invoke(app, command) @@ -500,11 +561,12 @@ def test_removing_another_backends_custom_proxy_keeps_the_service_only_while_the assert service.installed is kept +@pytest.mark.parametrize(("status", "payload"), [(503, {"error": "unavailable"}), (404, {"error": "route_not_found"})]) @respx.mock -def test_remove_keeps_the_key_when_gumloop_cannot_delete_the_custom_proxy(cli_runner, service): +def test_remove_keeps_the_key_when_gumloop_cannot_delete_the_custom_proxy(cli_runner, service, status, payload): save_registration(HOST, _registration()) key = public_key_text(load_or_create_key(HOST)) - respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(503, json={"error": "unavailable"}) + respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(status, json=payload) result = cli_runner.invoke(app, ["browser", "proxy", "unlink"]) From cb042c59016f0d16e8d2c2f79b5cb0d1d5204b4f Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:27:50 +0000 Subject: [PATCH 08/14] [PROD-871] link prints one message and warns when the background service runs another CLI version Co-authored-by: Cursor --- src/gumloop/cli/commands/custom_proxy.py | 13 ++++++++++--- src/gumloop/cli/custom_proxy_service.py | 10 ++++++++++ tests/cli/test_custom_proxy_command.py | 18 ++++++++++++++++++ tests/cli/test_custom_proxy_service.py | 20 ++++++++++++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index 52f02a0..024d615 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -43,6 +43,7 @@ from gumloop.cli.custom_proxy_lock import is_running from gumloop.cli.custom_proxy_service import CustomProxyService from gumloop.cli.custom_proxy_service import NoBackgroundService +from gumloop.cli.custom_proxy_service import executable_version from gumloop.cli.custom_proxy_service import gumloop_executable from gumloop.cli.custom_proxy_service import service_for_current_platform from gumloop.cli.errors import exit_with_error @@ -129,15 +130,21 @@ def link( except (GumloopError, ValidationError, httpx.HTTPError) as error: exit_with_error(_explained(error)) - if service is None: + if service is None or executable is None: console.print( "It can't stay connected in the background: this computer has no systemd user session. " "Run `gumloop browser proxy connect` and keep it open, for example in tmux." ) return - console.print("[green]Connected.[/green] Your agents' browser now goes out through this computer.") if sys.platform.startswith("linux"): console.print("[dim]It connects when you log in, once your keyring is unlocked.[/dim]") + service_version = executable_version(executable) + if service_version != __version__: + console.print( + f"[yellow]Note:[/yellow] the background service runs `{escape_markup(str(executable))}`, " + f"which is Gumloop CLI {escape_markup(service_version or 'of an unknown version')}, not {__version__}. " + "Run `gumloop update`, then `gumloop browser proxy link` again." + ) @proxy_app.command("status") @@ -419,7 +426,7 @@ def _register( if keep_default and not response.custom_proxy.is_default: cli.call_with_refresh(lambda client: client.custom_proxies.set_default(registration.custom_proxy_id)) added_name = escape_markup(response.custom_proxy.name) - console.print(f"Linked this computer to Gumloop as '{added_name}'.") + console.print(f"[green]Linked[/green] this computer to Gumloop as '{added_name}'.") def _delete_lost_custom_proxy(cli: CliContext, custom_proxy_id: str) -> bool: diff --git a/src/gumloop/cli/custom_proxy_service.py b/src/gumloop/cli/custom_proxy_service.py index 6c967d3..6c1bb11 100644 --- a/src/gumloop/cli/custom_proxy_service.py +++ b/src/gumloop/cli/custom_proxy_service.py @@ -164,6 +164,16 @@ def gumloop_executable() -> Path: return Path(found).absolute() +def executable_version(executable_path: Path, run_command: CommandRunner | None = None) -> str | None: + """None when it can't be run or doesn't print a version.""" + try: + result = (run_command or _run_command)([str(executable_path), "--version"]) + except GumloopError: + return None + version = result.stdout.strip() + return version if result.returncode == 0 and version else None + + def _systemd_quote(value: str) -> str: escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%").replace("$", "$$") return f'"{escaped}"' diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index af1820b..146d450 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -11,6 +11,7 @@ import pytest import respx +from gumloop._version import __version__ from gumloop.cli.credentials import KEYRING_SERVICE from gumloop.cli.credentials import Credentials from gumloop.cli.credentials import save_credentials @@ -75,6 +76,7 @@ def service(monkeypatch) -> FakeService: fake = FakeService() monkeypatch.setattr("gumloop.cli.commands.custom_proxy.service_for_current_platform", lambda: fake) monkeypatch.setattr("gumloop.cli.commands.custom_proxy.check_tls_not_inspected", lambda: None) + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.executable_version", lambda executable: __version__) save_credentials(Credentials(api_key="key", user_id="actor")) return fake @@ -89,6 +91,22 @@ def test_add_registers_and_turns_on_the_service(cli_runner, service, fake_execut assert json.loads(route.calls[0].request.content)["public_key"] == public_key_text(load_or_create_key(HOST)) assert load_registration(HOST) == _registration() assert service.executable == fake_executable_path / "gumloop" + assert "Linked this computer to Gumloop as 'Ada's laptop'." in " ".join(result.stdout.split()) + assert "Connected" not in result.stdout + + +@respx.mock +def test_link_warns_when_the_background_service_runs_another_cli_version( + cli_runner, service, monkeypatch, fake_executable_path +): + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.executable_version", lambda executable: "0.0.1") + respx.post(f"{API_BASE}/custom-proxies").respond(201, json=REGISTERED) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 0, result.output + assert service.installed + assert f"which is Gumloop CLI 0.0.1, not {__version__}. Run `gumloop update`" in " ".join(result.stdout.split()) @respx.mock diff --git a/tests/cli/test_custom_proxy_service.py b/tests/cli/test_custom_proxy_service.py index daf74ca..500561d 100644 --- a/tests/cli/test_custom_proxy_service.py +++ b/tests/cli/test_custom_proxy_service.py @@ -8,9 +8,11 @@ import pytest +from gumloop import GumloopError from gumloop.cli.custom_proxy_service import LaunchAgentService from gumloop.cli.custom_proxy_service import NoBackgroundService from gumloop.cli.custom_proxy_service import SystemdUserService +from gumloop.cli.custom_proxy_service import executable_version from gumloop.cli.custom_proxy_service import service_for_current_platform EXECUTABLE = Path("/opt/gumloop bin/gumloop") @@ -99,3 +101,21 @@ def test_linux_without_a_systemd_user_session_has_no_background_service( with pytest.raises(NoBackgroundService): service_for_current_platform(home=tmp_path) + + +@pytest.mark.parametrize( + ("outcome", "expected"), + [ + (subprocess.CompletedProcess([], 0, stdout="1.4.0\n", stderr=""), "1.4.0"), + (subprocess.CompletedProcess([], 2, stdout="", stderr="No such option: --version"), None), + (GumloopError("Could not run `gumloop`"), None), + ], +) +def test_executable_version_reads_what_the_service_executable_prints(outcome, expected): + def run_command(args: Sequence[str]) -> subprocess.CompletedProcess[str]: + assert list(args) == [str(EXECUTABLE), "--version"] + if isinstance(outcome, GumloopError): + raise outcome + return outcome + + assert executable_version(EXECUTABLE, run_command) == expected From 4e8cf0eea87deea608ffcc1ab8cc95725d62ce95 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:35:28 +0000 Subject: [PATCH 09/14] [PROD-871] connect keeps retrying while the org is in read-only mode Co-authored-by: Cursor --- src/gumloop/cli/commands/custom_proxy.py | 8 ++++++-- tests/cli/test_custom_proxy_command.py | 11 +++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index 024d615..818e772 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -74,11 +74,15 @@ "insufficient_permissions": _ROLE_DENIED, "tier_required_enterprise": "Personal proxies need an Enterprise plan.", "route_not_found": "Personal proxies aren't available for your organization yet.", + "feature_restricted": "Your organization is in read-only mode, so personal proxies are paused.", } # The only refusal that forgets the registration. _REMOVED = "personal_custom_proxy_not_found" # Also what the API answers when the rollout flag can't be read, so connect retries it. _NOT_RELEASED = "route_not_found" +# The org is in read-only mode, which lasts until an admin turns it off. +_READ_ONLY = "feature_restricted" +_RETRIED_CODES = frozenset({_NOT_RELEASED, _READ_ONLY}) _RETRIED_STATUSES = frozenset({408, 409, 429}) # Gumloop answered 401 to a login that can't be refreshed, such as a revoked API key. _LOGIN_REJECTED = "login_rejected" @@ -377,7 +381,7 @@ def _login_user_id(credentials: Credentials) -> str | None: def _gateway_token(host: str, registration: CustomProxyRegistration) -> CustomProxyGatewayToken: """A refusal stops the personal proxy, except the ones that can pass on their own: a timeout, - a conflict, rate limiting, and ``route_not_found``.""" + a conflict, rate limiting, ``route_not_found`` and read-only mode.""" # The service outlives logins, so each request uses the login stored now, not the one it started with. credentials = _owner_login(host, registration) if credentials is None: @@ -390,7 +394,7 @@ def _gateway_token(host: str, registration: CustomProxyRegistration) -> CustomPr code = error.code if isinstance(error.code, str) else None if error.status_code == 401: raise SignInRefused(_LOGIN_REJECTED) from error - if 400 <= error.status_code < 500 and error.status_code not in _RETRIED_STATUSES and code != _NOT_RELEASED: + if 400 <= error.status_code < 500 and error.status_code not in _RETRIED_STATUSES and code not in _RETRIED_CODES: raise SignInRefused(code or f"http_{error.status_code}") from error raise GatewayTokenUnavailable(f"Gumloop didn't give a gateway token (HTTP {error.status_code})") from error except (GumloopError, httpx.HTTPError) as error: diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index 146d450..f335722 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -291,6 +291,11 @@ async def run(self) -> None: ), (403, {"error": "tier_required_enterprise"}, "Personal proxies need an Enterprise plan."), (404, {"error": "route_not_found"}, "Personal proxies aren't available for your organization yet."), + ( + 403, + {"error": "feature_restricted", "denied_keys": ["organization:use_personal_proxies"]}, + "Your organization is in read-only mode, so personal proxies are paused.", + ), ], ) @respx.mock @@ -317,6 +322,12 @@ def test_link_says_why_personal_proxies_are_off(cli_runner, service, status, pay (404, {"error": "not_found"}, None, True), (401, {"error": "unauthorized"}, None, True), (404, {"error": "route_not_found"}, GatewayTokenUnavailable, True), + ( + 403, + {"error": "feature_restricted", "denied_keys": ["organization:use_personal_proxies"]}, + GatewayTokenUnavailable, + True, + ), (429, {"error": "rate_limited"}, GatewayTokenUnavailable, True), ], ) From 5f7635bb1bf41c680303ff734c70d8dfcd0ff265 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 01:35:28 +0000 Subject: [PATCH 10/14] [PROD-871] logout revokes the refresh token that unlinking replaced Co-authored-by: Cursor --- src/gumloop/cli/commands/auth.py | 4 +++- tests/cli/test_custom_proxy_command.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/gumloop/cli/commands/auth.py b/src/gumloop/cli/commands/auth.py index eb51dfb..f034a27 100644 --- a/src/gumloop/cli/commands/auth.py +++ b/src/gumloop/cli/commands/auth.py @@ -19,6 +19,7 @@ from gumloop.cli.credentials import Credentials from gumloop.cli.credentials import clear_credentials from gumloop.cli.credentials import keyring_backend_name +from gumloop.cli.credentials import load_credentials from gumloop.cli.credentials import save_credentials from gumloop.cli.errors import exit_with_error from gumloop.cli.oauth import DEFAULT_REDIRECT_PORT @@ -221,7 +222,8 @@ def logout( oauth_revoked = False revoke_failed = False if cli.effective_auth_method == METHOD_OAUTH: - token = cli.credentials.refresh_token or cli.credentials.access_token + # The unlink may have refreshed the stored login, which replaces its refresh token. + token = load_credentials().refresh_token or cli.credentials.refresh_token or cli.credentials.access_token if token: try: revoke_oauth_token(base_url=cli.effective_base_url, token=token) diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index f335722..57f4ed6 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -6,7 +6,9 @@ from datetime import datetime from datetime import timezone from pathlib import Path +from urllib.parse import parse_qs +import httpx import keyring import pytest import respx @@ -30,6 +32,7 @@ from gumloop.linked_proxy.sign_in import public_key_text from gumloop.types import CustomProxyGatewayToken from tests.sdk.helpers import API_BASE +from tests.sdk.helpers import OAUTH_BASE HOST = "api.gumloop.com" GATEWAY_URL = "wss://linked-proxy-gateway.gumloop.com/v1/cli/connect" @@ -574,6 +577,24 @@ def test_logout_unlinks_with_the_stored_login_not_a_credential_override(cli_runn assert load_registration(HOST) is None +@respx.mock +def test_logout_revokes_the_refresh_token_the_unlink_refresh_replaced(cli_runner, service): + save_credentials(Credentials(access_token=_access_token("actor"), refresh_token="orig_refresh")) + save_registration(HOST, _registration()) + respx.delete(f"{API_BASE}/custom-proxies/dp-1").mock( + side_effect=[httpx.Response(401, json={"error": {"code": "invalid_token"}}), httpx.Response(204)] + ) + respx.post(f"{OAUTH_BASE}/oauth/token").respond( + 200, json={"access_token": _access_token("actor"), "refresh_token": "fresh_refresh"} + ) + revoke = respx.post(f"{OAUTH_BASE}/oauth/revoke").respond(200) + + result = cli_runner.invoke(app, ["logout"]) + + assert result.exit_code == 0, result.output + assert parse_qs(revoke.calls.last.request.content.decode())["token"] == ["fresh_refresh"] + + @pytest.mark.parametrize(("login_has_custom_proxy", "kept"), [(True, True), (False, False)]) def test_removing_another_backends_custom_proxy_keeps_the_service_only_while_the_login_needs_it( cli_runner, service, login_has_custom_proxy, kept From 49dcdce2bb215f82dbe2f5ea368d2820cbffd45d Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 04:50:33 +0000 Subject: [PATCH 11/14] [PROD-871] logout revokes the stored refresh token at the backend it came from Co-authored-by: Cursor --- src/gumloop/cli/commands/auth.py | 12 +++++++++--- tests/cli/test_custom_proxy_command.py | 11 +++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/gumloop/cli/commands/auth.py b/src/gumloop/cli/commands/auth.py index f034a27..285a789 100644 --- a/src/gumloop/cli/commands/auth.py +++ b/src/gumloop/cli/commands/auth.py @@ -12,6 +12,7 @@ from gumloop import Gumloop from gumloop import GumloopError +from gumloop._client import DEFAULT_BASE_URL from gumloop.cli.commands.custom_proxy import remove_stored_login_custom_proxy from gumloop.cli.console import console from gumloop.cli.console import print_json @@ -222,11 +223,16 @@ def logout( oauth_revoked = False revoke_failed = False if cli.effective_auth_method == METHOD_OAUTH: - # The unlink may have refreshed the stored login, which replaces its refresh token. - token = load_credentials().refresh_token or cli.credentials.refresh_token or cli.credentials.access_token + if cli.credentials.refresh_token: + # The unlink may have refreshed the stored login, which replaces its refresh token. + token = load_credentials().refresh_token or cli.credentials.refresh_token + revoke_url = cli.credentials.base_url or DEFAULT_BASE_URL + else: + token = cli.credentials.access_token + revoke_url = cli.effective_base_url if token: try: - revoke_oauth_token(base_url=cli.effective_base_url, token=token) + revoke_oauth_token(base_url=revoke_url, token=token) oauth_revoked = True except Exception: revoke_failed = True diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index 57f4ed6..cdad9bb 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -595,6 +595,17 @@ def test_logout_revokes_the_refresh_token_the_unlink_refresh_replaced(cli_runner assert parse_qs(revoke.calls.last.request.content.decode())["token"] == ["fresh_refresh"] +@respx.mock +def test_logout_revokes_the_stored_refresh_token_at_the_backend_it_came_from(cli_runner, service): + save_credentials(Credentials(access_token=_access_token("actor"), refresh_token="stored_refresh")) + revoke = respx.post(f"{OAUTH_BASE}/oauth/revoke").respond(200) + + result = cli_runner.invoke(app, ["--base-url", "https://staging.api.gumloop.com/api/v1", "logout"]) + + assert result.exit_code == 0, result.output + assert parse_qs(revoke.calls.last.request.content.decode())["token"] == ["stored_refresh"] + + @pytest.mark.parametrize(("login_has_custom_proxy", "kept"), [(True, True), (False, False)]) def test_removing_another_backends_custom_proxy_keeps_the_service_only_while_the_login_needs_it( cli_runner, service, login_has_custom_proxy, kept From 0f41e0b865631a76de8f3f7eaa3602078ea2873a Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 05:09:18 +0000 Subject: [PATCH 12/14] [PROD-871] Trim the personal proxy command tests to the crucial cases Co-authored-by: Cursor --- tests/cli/test_custom_proxy_command.py | 368 ++++++------------------- tests/cli/test_custom_proxy_key.py | 41 +-- tests/cli/test_custom_proxy_service.py | 126 +++------ tests/linked_proxy/helpers.py | 19 +- tests/linked_proxy/test_connection.py | 171 ++++-------- tests/linked_proxy/test_tls_check.py | 9 +- 6 files changed, 211 insertions(+), 523 deletions(-) diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index cdad9bb..347ba56 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -3,9 +3,8 @@ import base64 import json from collections.abc import Callable -from datetime import datetime -from datetime import timezone from pathlib import Path +from types import ModuleType from urllib.parse import parse_qs import httpx @@ -17,18 +16,14 @@ from gumloop.cli.credentials import KEYRING_SERVICE from gumloop.cli.credentials import Credentials from gumloop.cli.credentials import save_credentials -from gumloop.cli.custom_proxy_key import CustomProxyConnectionStatus from gumloop.cli.custom_proxy_key import CustomProxyRegistration from gumloop.cli.custom_proxy_key import load_or_create_key from gumloop.cli.custom_proxy_key import load_registration -from gumloop.cli.custom_proxy_key import save_connection_status from gumloop.cli.custom_proxy_key import save_registration from gumloop.cli.custom_proxy_service import NoBackgroundService from gumloop.cli.main import app from gumloop.linked_proxy.connection import GatewayTokenUnavailable from gumloop.linked_proxy.connection import SignInRefused -from gumloop.linked_proxy.connection import UpgradeRequired -from gumloop.linked_proxy.destinations import Target from gumloop.linked_proxy.sign_in import public_key_text from gumloop.types import CustomProxyGatewayToken from tests.sdk.helpers import API_BASE @@ -58,6 +53,34 @@ def _access_token(user_id: str) -> str: return f"header.{claims}.signature" +class FixedHostname(ModuleType): + """Stands in for the command module's ``socket`` name.""" + + def __init__(self) -> None: + super().__init__("socket") + + def gethostname(self) -> str: + return "Ada's MacBook Pro" + + +def _no_background_service(fake: FakeService) -> FakeService: + raise NoBackgroundService("no systemd user session") + + +class RecordingConnections: + """Stands in for ``GatewayConnection``: records each construction and connects nowhere.""" + + def __init__(self) -> None: + self.constructed: list[dict[str, object]] = [] + + def __call__(self, **kwargs: object) -> RecordingConnections: + self.constructed.append(kwargs) + return self + + async def run(self) -> None: + pass + + class FakeService: def __init__(self, *, installed: bool = False) -> None: self.installed = installed @@ -80,64 +103,37 @@ def service(monkeypatch) -> FakeService: monkeypatch.setattr("gumloop.cli.commands.custom_proxy.service_for_current_platform", lambda: fake) monkeypatch.setattr("gumloop.cli.commands.custom_proxy.check_tls_not_inspected", lambda: None) monkeypatch.setattr("gumloop.cli.commands.custom_proxy.executable_version", lambda executable: __version__) + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.socket", FixedHostname()) save_credentials(Credentials(api_key="key", user_id="actor")) return fake +@pytest.mark.parametrize( + ("platform_service", "installed_executable"), + [(lambda fake: fake, lambda bin_dir: bin_dir / "gumloop"), (_no_background_service, lambda bin_dir: None)], + ids=["background service", "no background service"], +) @respx.mock -def test_add_registers_and_turns_on_the_service(cli_runner, service, fake_executable_path): - route = respx.post(f"{API_BASE}/custom-proxies").respond(201, json=REGISTERED) - - result = cli_runner.invoke(app, ["browser", "proxy", "link"]) - - assert result.exit_code == 0, result.output - assert json.loads(route.calls[0].request.content)["public_key"] == public_key_text(load_or_create_key(HOST)) - assert load_registration(HOST) == _registration() - assert service.executable == fake_executable_path / "gumloop" - assert "Linked this computer to Gumloop as 'Ada's laptop'." in " ".join(result.stdout.split()) - assert "Connected" not in result.stdout - - -@respx.mock -def test_link_warns_when_the_background_service_runs_another_cli_version( - cli_runner, service, monkeypatch, fake_executable_path +def test_add_registers_and_turns_on_the_service( + cli_runner, service, monkeypatch, fake_executable_path, platform_service, installed_executable ): - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.executable_version", lambda executable: "0.0.1") - respx.post(f"{API_BASE}/custom-proxies").respond(201, json=REGISTERED) - - result = cli_runner.invoke(app, ["browser", "proxy", "link"]) - - assert result.exit_code == 0, result.output - assert service.installed - assert f"which is Gumloop CLI 0.0.1, not {__version__}. Run `gumloop update`" in " ".join(result.stdout.split()) - - -@respx.mock -def test_link_registers_again_when_already_linked_and_saves_the_current_gateway(cli_runner, service): - save_registration(HOST, _registration(gateway_url="wss://old-gateway.gumloop.com/v1/cli/connect")) + monkeypatch.setattr( + "gumloop.cli.commands.custom_proxy.service_for_current_platform", lambda: platform_service(service) + ) route = respx.post(f"{API_BASE}/custom-proxies").respond(201, json=REGISTERED) result = cli_runner.invoke(app, ["browser", "proxy", "link"]) assert result.exit_code == 0, result.output - assert route.called - assert load_registration(HOST) == _registration() - - -@respx.mock -def test_link_without_a_background_service_registers_and_points_to_connect(cli_runner, service, monkeypatch): - def no_background_service() -> FakeService: - raise NoBackgroundService("no systemd user session") - - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.service_for_current_platform", no_background_service) - respx.post(f"{API_BASE}/custom-proxies").respond(201, json=REGISTERED) - - result = cli_runner.invoke(app, ["browser", "proxy", "link"]) - - assert result.exit_code == 0, result.output + assert json.loads(route.calls[0].request.content) == { + "kind": "cli", + "name": "Ada's MacBook Pro", + "public_key": public_key_text(load_or_create_key(HOST)), + "machine_name": "Ada's MacBook Pro", + "cli_version": __version__, + } assert load_registration(HOST) == _registration() - assert not service.installed - assert "Run `gumloop browser proxy connect`" in " ".join(result.output.split()) + assert service.executable == installed_executable(fake_executable_path) @respx.mock @@ -151,27 +147,6 @@ def test_add_refuses_a_temporary_credential_override(cli_runner, service): assert not service.installed -@respx.mock -def test_a_refused_custom_proxy_stays_down_after_a_restart(cli_runner, service, monkeypatch): - save_registration(HOST, _registration()) - - class RefusedConnection: - def __init__(self, **kwargs: object) -> None: - assert kwargs["linked_proxy_id"] == "dp-1" - - async def run(self) -> None: - raise SignInRefused("personal_custom_proxy_not_found") - - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", RefusedConnection) - - refused = cli_runner.invoke(app, ["browser", "proxy", "connect"]) - restarted = cli_runner.invoke(app, ["browser", "proxy", "connect"]) - - assert (refused.exit_code, restarted.exit_code) == (0, 0) - assert load_registration(HOST) is None - assert not respx.calls - - def test_a_refused_custom_proxy_keeps_a_registration_linked_while_it_was_connected(cli_runner, service, monkeypatch): save_registration(HOST, _registration()) relinked = _registration(custom_proxy_id="dp-2") @@ -192,151 +167,28 @@ async def run(self) -> None: assert load_registration(HOST) == relinked -def test_connect_says_it_connected_once_across_reconnects(cli_runner, service, monkeypatch): - save_registration(HOST, _registration()) - - class ReconnectingConnection: - def __init__(self, *, on_connected: Callable[[], None], **kwargs: object) -> None: - self._on_connected = on_connected - - async def run(self) -> None: - self._on_connected() - self._on_connected() - - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", ReconnectingConnection) - - result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) - - assert result.exit_code == 0, result.output - assert " ".join(result.stdout.split()).count("Connected. Agents can now send browser traffic") == 1 - - -@pytest.mark.parametrize(("flags", "printed"), [([], False), (["-v"], True)]) -def test_connect_prints_the_sites_agents_open_only_when_verbose(cli_runner, service, monkeypatch, flags, printed): - save_registration(HOST, _registration()) - - class OpeningConnection: - def __init__(self, *, on_open: Callable[[Target], None] | None, **kwargs: object) -> None: - self._on_open = on_open - - async def run(self) -> None: - if self._on_open is not None: - self._on_open(Target(host="example.com", port=443)) - - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", OpeningConnection) - - result = cli_runner.invoke(app, ["browser", "proxy", "connect", *flags]) - - assert result.exit_code == 0, result.output - assert ("example.com" in result.stdout) is printed - - -@pytest.mark.parametrize( - ("reason", "kept", "expected"), - [ - ("personal_custom_proxy_not_found", False, "This computer was unlinked from Gumloop."), - ( - "organization_permission_required", - True, - "Your organization's roles don't allow you to use personal proxies.", - ), - ("login_rejected", True, "Gumloop no longer accepts your login"), - ("paid_plan_required", True, "You can't use personal proxies right now."), - ], -) -def test_connect_keeps_the_registration_unless_the_custom_proxy_was_removed( - cli_runner, service, monkeypatch, reason, kept, expected -): - save_registration(HOST, _registration()) - - class RefusedConnection: - def __init__(self, **kwargs: object) -> None: - pass - - async def run(self) -> None: - raise SignInRefused(reason) - - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", RefusedConnection) - - result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) - - assert result.exit_code == 0, result.output - assert (load_registration(HOST) == _registration()) is kept - assert expected in " ".join(result.stderr.split()) - - -def test_connect_stops_when_the_gateway_needs_a_newer_cli(cli_runner, service, monkeypatch): - save_registration(HOST, _registration()) - - class OutdatedConnection: - def __init__(self, **kwargs: object) -> None: - pass - - async def run(self) -> None: - raise UpgradeRequired() - - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", OutdatedConnection) - - result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) - - assert result.exit_code == 0, result.output - assert load_registration(HOST) == _registration() - assert "Run `gumloop update`, then `gumloop browser proxy link`." in " ".join(result.stderr.split()) - - @pytest.mark.parametrize( - ("status", "payload", "expected"), + ("status", "payload", "expected_fetched", "kept"), [ - ( - 403, - {"error": "policy_denied", "denied_keys": ["organization:use_personal_proxies"]}, - "Your organization's roles don't allow you to use personal proxies. Ask an admin to turn them on.", - ), - (403, {"error": "tier_required_enterprise"}, "Personal proxies need an Enterprise plan."), - (404, {"error": "route_not_found"}, "Personal proxies aren't available for your organization yet."), + (200, {"gateway_token": "token-1"}, ["token-1"], True), + (503, {"error": "unavailable"}, [GatewayTokenUnavailable], True), + (404, {"error": {"code": "personal_custom_proxy_not_found"}}, [], False), + (403, {"error": {"code": "not_a_code_the_cli_knows"}}, [], True), + (404, {"error": "not_found"}, [], True), + (401, {"error": "unauthorized"}, [], True), + (404, {"error": "route_not_found"}, [GatewayTokenUnavailable], True), ( 403, {"error": "feature_restricted", "denied_keys": ["organization:use_personal_proxies"]}, - "Your organization is in read-only mode, so personal proxies are paused.", - ), - ], -) -@respx.mock -def test_link_says_why_personal_proxies_are_off(cli_runner, service, status, payload, expected): - respx.post(f"{API_BASE}/custom-proxies").respond(status, json=payload) - - result = cli_runner.invoke(app, ["browser", "proxy", "link"]) - - assert result.exit_code == 1 - assert expected in " ".join(result.stderr.split()) - assert load_registration(HOST) is None - assert not service.installed - - -@pytest.mark.parametrize( - ("status", "payload", "expected_token", "kept"), - [ - (200, {"gateway_token": "token-1"}, "token-1", True), - (503, {"error": "unavailable"}, GatewayTokenUnavailable, True), - (404, {"error": {"code": "personal_custom_proxy_not_found"}}, None, False), - (403, {"error": "policy_denied", "denied_keys": ["organization:use_personal_proxies"]}, None, True), - (403, {"error": {"code": "organization_permission_required"}}, None, True), - (403, {"error": {"code": "not_a_code_the_cli_knows"}}, None, True), - (404, {"error": "not_found"}, None, True), - (401, {"error": "unauthorized"}, None, True), - (404, {"error": "route_not_found"}, GatewayTokenUnavailable, True), - ( - 403, - {"error": "feature_restricted", "denied_keys": ["organization:use_personal_proxies"]}, - GatewayTokenUnavailable, + [GatewayTokenUnavailable], True, ), - (429, {"error": "rate_limited"}, GatewayTokenUnavailable, True), + (429, {"error": "rate_limited"}, [GatewayTokenUnavailable], True), ], ) @respx.mock def test_connect_signs_in_with_a_gateway_token_and_stops_when_gumloop_refuses_one( - cli_runner, service, monkeypatch, status, payload, expected_token, kept + cli_runner, service, monkeypatch, status, payload, expected_fetched, kept ): save_registration(HOST, _registration()) respx.post(f"{API_BASE}/custom-proxies/dp-1/gateway-token").respond(status, json=payload) @@ -357,7 +209,7 @@ async def run(self) -> None: result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) assert result.exit_code == 0, result.output - assert fetched == ([expected_token] if expected_token is not None else []) + assert fetched == expected_fetched assert (load_registration(HOST) == _registration()) is kept @@ -407,30 +259,32 @@ async def run(self) -> None: assert result.exit_code == 0, result.output assert not route.called assert load_registration(HOST) == _registration() - assert "You logged in to Gumloop as someone else" in " ".join(result.stderr.split()) -@pytest.mark.parametrize("keychain", ["changed", "empty"]) +def _forget_key() -> None: + keyring.delete_password(KEYRING_SERVICE, f"custom-proxy:{HOST}") + + +@pytest.mark.parametrize( + ("reset_keychain", "key_kept"), + [(lambda: None, True), (_forget_key, False)], + ids=["changed", "empty"], +) def test_connect_with_a_lost_key_stops_without_making_one_and_keeps_the_registration( - cli_runner, service, monkeypatch, keychain + cli_runner, service, monkeypatch, reset_keychain, key_kept ): lost = _registration(public_key="a key the keychain no longer has") save_registration(HOST, lost) - if keychain == "empty": - keyring.delete_password(KEYRING_SERVICE, f"custom-proxy:{HOST}") - - class UnusedConnection: - def __init__(self, **kwargs: object) -> None: - pytest.fail("connected with a key Gumloop doesn't know") - - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", UnusedConnection) + reset_keychain() + connections = RecordingConnections() + monkeypatch.setattr("gumloop.cli.commands.custom_proxy.GatewayConnection", connections) result = cli_runner.invoke(app, ["browser", "proxy", "connect"]) assert result.exit_code == 0, result.output + assert connections.constructed == [] assert load_registration(HOST) == lost - assert (keyring.get_password(KEYRING_SERVICE, f"custom-proxy:{HOST}") is None) is (keychain == "empty") - assert "key is gone from the OS keychain" in " ".join(result.stderr.split()) + assert (keyring.get_password(KEYRING_SERVICE, f"custom-proxy:{HOST}") is not None) is key_kept @pytest.mark.parametrize(("was_default", "default_route_called"), [(True, True), (False, False)]) @@ -470,29 +324,10 @@ def test_link_with_a_lost_key_keeps_its_custom_proxy_when_registering_fails(cli_ result = cli_runner.invoke(app, ["browser", "proxy", "link"]) - assert result.exit_code != 0 + assert result.exit_code == 1 assert not deleted.called assert load_registration(HOST) == lost - - -@respx.mock -def test_link_with_a_lost_key_registers_when_gumloop_already_removed_its_custom_proxy(cli_runner, service): - save_registration(HOST, _registration(public_key="a key the keychain no longer has")) - respx.get(f"{API_BASE}/custom-proxies").respond(200, json={"custom_proxies": [], "limit": 5}) - deleted = respx.delete(f"{API_BASE}/custom-proxies/dp-1") - respx.post(f"{API_BASE}/custom-proxies").respond( - 201, - json={ - "custom_proxy": {"id": "dp-2", "name": "Ada's laptop", "kind": "cli", "is_default": True}, - "gateway_url": GATEWAY_URL, - }, - ) - - result = cli_runner.invoke(app, ["browser", "proxy", "link"]) - - assert result.exit_code == 0, result.output - assert not deleted.called - assert load_registration(HOST) == _registration(custom_proxy_id="dp-2") + assert not service.installed @respx.mock @@ -505,44 +340,6 @@ def test_link_refuses_a_computer_linked_to_someone_else(cli_runner, service): assert result.exit_code == 1 assert not route.called assert not service.installed - assert "linked to another Gumloop user" in " ".join(result.stderr.split()) - - -@pytest.mark.parametrize( - ("running", "connected", "last_error", "expected"), - [ - (False, True, None, "not running. Run `gumloop browser proxy link` to start."), - (True, False, "can't reach the gateway (connection refused)", "connecting. Last attempt failed: can't reach"), - (True, True, None, "connected since"), - ], -) -def test_status_reads_the_running_custom_proxy_connection( - cli_runner, service, monkeypatch, running, connected, last_error, expected -): - save_registration(HOST, _registration()) - save_connection_status( - HOST, - CustomProxyConnectionStatus(connected=connected, since=datetime.now(timezone.utc), last_error=last_error), - ) - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.is_running", lambda host: running) - - result = cli_runner.invoke(app, ["browser", "proxy", "status"]) - - assert result.exit_code == 0, result.output - assert f'"Ada\'s laptop": {expected}' in " ".join(result.output.split()) - - -def test_status_without_a_background_service_points_to_connect(cli_runner, service, monkeypatch): - def no_background_service() -> FakeService: - raise NoBackgroundService("no systemd user session") - - monkeypatch.setattr("gumloop.cli.commands.custom_proxy.service_for_current_platform", no_background_service) - save_registration(HOST, _registration()) - - result = cli_runner.invoke(app, ["browser", "proxy", "status"]) - - assert result.exit_code == 0, result.output - assert "not running. Run `gumloop browser proxy connect` to start." in " ".join(result.output.split()) @pytest.mark.parametrize("command", [["browser", "proxy", "unlink"], ["logout"]]) @@ -606,13 +403,16 @@ def test_logout_revokes_the_stored_refresh_token_at_the_backend_it_came_from(cli assert parse_qs(revoke.calls.last.request.content.decode())["token"] == ["stored_refresh"] -@pytest.mark.parametrize(("login_has_custom_proxy", "kept"), [(True, True), (False, False)]) +@pytest.mark.parametrize( + ("link_this_backend", "kept"), + [(lambda: save_registration(HOST, _registration()), True), (lambda: None, False)], + ids=["login has a personal proxy", "login has none"], +) def test_removing_another_backends_custom_proxy_keeps_the_service_only_while_the_login_needs_it( - cli_runner, service, login_has_custom_proxy, kept + cli_runner, service, link_this_backend, kept ): service.installed = True - if login_has_custom_proxy: - save_registration(HOST, _registration()) + link_this_backend() result = cli_runner.invoke( app, ["browser", "proxy", "unlink"], env={"GUMLOOP_BASE_URL": "https://staging.api.gumloop.com"} diff --git a/tests/cli/test_custom_proxy_key.py b/tests/cli/test_custom_proxy_key.py index e5c2de7..f8a047f 100644 --- a/tests/cli/test_custom_proxy_key.py +++ b/tests/cli/test_custom_proxy_key.py @@ -4,46 +4,29 @@ from pydantic import ValidationError from gumloop.cli.custom_proxy_key import CustomProxyRegistration -from gumloop.cli.custom_proxy_key import load_or_create_key -from gumloop.cli.custom_proxy_key import load_registration -from gumloop.cli.custom_proxy_key import save_registration -from gumloop.linked_proxy.sign_in import public_key_text -def test_key_and_registration_persist(temporary_home): - host = "api.gumloop.com" - first = public_key_text(load_or_create_key(host)) +def test_registration_accepts_an_unencrypted_gateway_on_this_computer(): registration = CustomProxyRegistration( - custom_proxy_id="dp-1", - name="Ada's laptop", - gateway_url="wss://linked-proxy-gateway.gumloop.com/v1/cli/connect", - public_key=first, - user_id="ada", + custom_proxy_id="dp-1", name="Ada's laptop", gateway_url="ws://localhost:8443/v1/cli/connect", public_key="key" ) - save_registration(host, registration) - - assert public_key_text(load_or_create_key(host)) == first - assert load_registration(host) == registration - - -@pytest.mark.parametrize( - "gateway_url", - ["wss://linked-proxy-gateway.gumloop.com/v1/cli/connect", "ws://localhost:8443/v1/cli/connect"], -) -def test_registration_accepts_an_encrypted_or_local_gateway(gateway_url): - registration = CustomProxyRegistration( - custom_proxy_id="dp-1", name="Ada's laptop", gateway_url=gateway_url, public_key="key" - ) - - assert registration.gateway_url == gateway_url + assert registration.gateway_url == "ws://localhost:8443/v1/cli/connect" def test_registration_refuses_an_unencrypted_remote_gateway(): - with pytest.raises(ValidationError): + with pytest.raises(ValidationError) as refused: CustomProxyRegistration( custom_proxy_id="dp-1", name="Ada's laptop", gateway_url="ws://linked-proxy-gateway.gumloop.com/v1/cli/connect", public_key="key", ) + + assert [(error["loc"], error["type"], error["msg"]) for error in refused.value.errors()] == [ + ( + ("gateway_url",), + "value_error", + "Value error, the linked proxy gateway must use wss:// unless it runs on this computer", + ) + ] diff --git a/tests/cli/test_custom_proxy_service.py b/tests/cli/test_custom_proxy_service.py index 500561d..25ef3c9 100644 --- a/tests/cli/test_custom_proxy_service.py +++ b/tests/cli/test_custom_proxy_service.py @@ -2,20 +2,20 @@ import plistlib import subprocess -import sys from collections.abc import Sequence from pathlib import Path -import pytest - -from gumloop import GumloopError from gumloop.cli.custom_proxy_service import LaunchAgentService -from gumloop.cli.custom_proxy_service import NoBackgroundService from gumloop.cli.custom_proxy_service import SystemdUserService -from gumloop.cli.custom_proxy_service import executable_version -from gumloop.cli.custom_proxy_service import service_for_current_platform EXECUTABLE = Path("/opt/gumloop bin/gumloop") +CLEARED_ENVIRONMENT = [ + "GUMLOOP_ACCESS_TOKEN", + "GUMLOOP_API_KEY", + "GUMLOOP_BASE_URL", + "GUMLOOP_TEAM_ID", + "GUMLOOP_USER_ID", +] class RecordingRunner: @@ -33,89 +33,47 @@ def test_launch_agent_runs_the_custom_proxy_at_login_and_after_failures(tmp_path service.install(EXECUTABLE) - plist = plistlib.loads(service.plist_path.read_bytes()) - assert plist["ProgramArguments"] == [str(EXECUTABLE), "browser", "proxy", "connect"] - assert plist["RunAtLoad"] is True - assert plist["KeepAlive"] == {"SuccessfulExit": False} - assert ["launchctl", "bootstrap", "gui/501", str(service.plist_path)] in runner.calls - - service.remove() - - assert not service.is_installed() - assert runner.calls[-1] == ["launchctl", "bootout", "gui/501/com.gumloop.custom-proxy"] + assert plistlib.loads(service.plist_path.read_bytes()) == { + "EnvironmentVariables": { + **dict.fromkeys(CLEARED_ENVIRONMENT, ""), + "HOME": str(tmp_path), + "PATH": "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", + }, + "KeepAlive": {"SuccessfulExit": False}, + "Label": "com.gumloop.custom-proxy", + "ProgramArguments": [str(EXECUTABLE), "browser", "proxy", "connect"], + "RunAtLoad": True, + "StandardErrorPath": str(tmp_path / ".gumloop" / "custom-proxy" / "service.log"), + "ThrottleInterval": 30, + } + assert runner.calls == [ + ["launchctl", "bootout", "gui/501/com.gumloop.custom-proxy"], + ["launchctl", "bootstrap", "gui/501", str(service.plist_path)], + ] -def test_systemd_unit_runs_the_custom_proxy_at_login_and_after_failures(tmp_path): +def test_systemd_unit_runs_the_custom_proxy_as_written_at_login_and_after_failures(tmp_path): runner = RecordingRunner() service = SystemdUserService(config_home=tmp_path, run_command=runner) - service.install(EXECUTABLE) + service.install(Path('/home/a$b/100%/"q"\\gumloop')) - unit = service.unit_path.read_text() - assert 'ExecStart="/opt/gumloop bin/gumloop" "browser" "proxy" "connect"\n' in unit - assert "Restart=on-failure\n" in unit - assert "WantedBy=default.target\n" in unit - assert runner.calls[-2:] == [ + assert service.unit_path.read_text() == ( + "[Unit]\n" + "Description=Gumloop personal proxy\n" + "After=network-online.target\n" + "\n" + "[Service]\n" + 'ExecStart="/home/a$$b/100%%/\\"q\\"\\\\gumloop" "browser" "proxy" "connect"\n' + f"UnsetEnvironment={' '.join(CLEARED_ENVIRONMENT)}\n" + "Restart=on-failure\n" + "RestartSec=30\n" + "\n" + "[Install]\n" + "WantedBy=default.target\n" + ) + assert runner.calls == [ + ["systemctl", "--user", "daemon-reload"], ["systemctl", "--user", "enable", "gumloop-custom-proxy.service"], ["systemctl", "--user", "restart", "gumloop-custom-proxy.service"], ] - - service.remove() - - assert not service.is_installed() - assert ["systemctl", "--user", "disable", "--now", "gumloop-custom-proxy.service"] in runner.calls - - -def test_systemd_unit_runs_an_executable_path_with_special_characters_as_written(tmp_path): - service = SystemdUserService(config_home=tmp_path, run_command=RecordingRunner()) - - service.install(Path('/home/a$b/100%/"q"\\gumloop')) - - unit = service.unit_path.read_text() - assert 'ExecStart="/home/a$$b/100%%/\\"q\\"\\\\gumloop" "browser" "proxy" "connect"\n' in unit - - -def test_systemd_unit_goes_where_systemd_looks_for_user_units(tmp_path, monkeypatch): - monkeypatch.setattr(sys, "platform", "linux") - monkeypatch.setattr("gumloop.cli.custom_proxy_service._SYSTEMD_BOOTED_DIR", tmp_path) - monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path / "run")) - monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config")) - - service = service_for_current_platform(home=tmp_path) - - assert isinstance(service, SystemdUserService) - assert service.unit_path == tmp_path / "config" / "systemd" / "user" / "gumloop-custom-proxy.service" - - -@pytest.mark.parametrize(("systemd_booted", "runtime_dir"), [(False, "/run/user/1000"), (True, None)]) -def test_linux_without_a_systemd_user_session_has_no_background_service( - tmp_path, monkeypatch, systemd_booted, runtime_dir -): - monkeypatch.setattr(sys, "platform", "linux") - booted_dir = tmp_path if systemd_booted else tmp_path / "missing" - monkeypatch.setattr("gumloop.cli.custom_proxy_service._SYSTEMD_BOOTED_DIR", booted_dir) - if runtime_dir is None: - monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False) - else: - monkeypatch.setenv("XDG_RUNTIME_DIR", runtime_dir) - - with pytest.raises(NoBackgroundService): - service_for_current_platform(home=tmp_path) - - -@pytest.mark.parametrize( - ("outcome", "expected"), - [ - (subprocess.CompletedProcess([], 0, stdout="1.4.0\n", stderr=""), "1.4.0"), - (subprocess.CompletedProcess([], 2, stdout="", stderr="No such option: --version"), None), - (GumloopError("Could not run `gumloop`"), None), - ], -) -def test_executable_version_reads_what_the_service_executable_prints(outcome, expected): - def run_command(args: Sequence[str]) -> subprocess.CompletedProcess[str]: - assert list(args) == [str(EXECUTABLE), "--version"] - if isinstance(outcome, GumloopError): - raise outcome - return outcome - - assert executable_version(EXECUTABLE, run_command) == expected diff --git a/tests/linked_proxy/helpers.py b/tests/linked_proxy/helpers.py index 3781cd5..4527b9d 100644 --- a/tests/linked_proxy/helpers.py +++ b/tests/linked_proxy/helpers.py @@ -2,6 +2,9 @@ import asyncio from collections.abc import Callable +from datetime import datetime +from datetime import timezone +from datetime import tzinfo from types import ModuleType from gumloop.linked_proxy.destinations import Target @@ -10,6 +13,7 @@ from gumloop.linked_proxy.frames import Frame from gumloop.linked_proxy.frames import FrameType from gumloop.linked_proxy.tunnel import Tunnel +from gumloop.types import CustomProxyGatewayToken class FakeGateway: @@ -95,11 +99,11 @@ async def relay_through_stream(gateway: FakeGateway, sent: bytes) -> bytes: return bytes(received) -def tokens(*results: str | Exception) -> Callable[[], str]: +def tokens(*results: str | CustomProxyGatewayToken | Exception) -> Callable[[], str | CustomProxyGatewayToken]: """A gateway token fetch that returns, or raises, ``results`` in order.""" remaining = list(results) - def fetch() -> str: + def fetch() -> str | CustomProxyGatewayToken: result = remaining.pop(0) if isinstance(result, Exception): raise result @@ -132,6 +136,17 @@ def time(self) -> float: return self._now +FROZEN_NOW = datetime(2027, 1, 15, 12, 0, tzinfo=timezone.utc) + + +class FrozenDatetime(datetime): + """Stands in for a module's ``datetime`` name: ``now`` is always ``FROZEN_NOW``.""" + + @classmethod + def now(cls, tz: tzinfo | None = None) -> datetime: + return FROZEN_NOW + + class RecordingWriter: def __init__(self, local: str, remote: str) -> None: self._addresses = {"sockname": (local, 50000), "peername": (remote, 443)} diff --git a/tests/linked_proxy/test_connection.py b/tests/linked_proxy/test_connection.py index a2289a0..b59414f 100644 --- a/tests/linked_proxy/test_connection.py +++ b/tests/linked_proxy/test_connection.py @@ -8,9 +8,7 @@ from collections.abc import Awaitable from collections.abc import Callable from dataclasses import dataclass -from datetime import datetime from datetime import timedelta -from datetime import timezone import pytest from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey @@ -20,10 +18,9 @@ from websockets.frames import Close from websockets.http11 import Response +from gumloop.linked_proxy import connection from gumloop.linked_proxy.connection import ERROR_HEADER -from gumloop.linked_proxy.connection import FIRST_RETRY_SECONDS from gumloop.linked_proxy.connection import LOGIN_CHECK_SECONDS -from gumloop.linked_proxy.connection import MIN_REFRESH_SECONDS from gumloop.linked_proxy.connection import REFRESH_BEFORE_EXPIRY_SECONDS from gumloop.linked_proxy.connection import TUNNEL_VERSION from gumloop.linked_proxy.connection import TUNNEL_VERSION_HEADER @@ -35,6 +32,11 @@ from gumloop.linked_proxy.frames import Frame from gumloop.linked_proxy.frames import FrameType from gumloop.types import CustomProxyGatewayToken +from tests.linked_proxy.helpers import FROZEN_NOW +from tests.linked_proxy.helpers import FrozenDatetime +from tests.linked_proxy.helpers import FrozenTime +from tests.linked_proxy.helpers import UpperBoundRandom +from tests.linked_proxy.helpers import tokens GATEWAY_URL = "wss://linked-proxy-gateway.gumloop.com/v1/cli/connect" @@ -130,22 +132,6 @@ async def __call__(self, seconds: float) -> None: await asyncio.Event().wait() -def _tokens(*results: str | CustomProxyGatewayToken | Exception) -> Callable[[], str | CustomProxyGatewayToken]: - remaining = list(results) - - def fetch() -> str | CustomProxyGatewayToken: - result = remaining.pop(0) - if isinstance(result, Exception): - raise result - return result - - return fetch - - -def _expiring_in(minutes: float, utc_suffix: str = "+00:00") -> str: - return (datetime.now(timezone.utc) + timedelta(minutes=minutes)).isoformat().replace("+00:00", utc_suffix) - - def _refused_handshake(status: int, outcome: str) -> InvalidStatus: return InvalidStatus(Response(status, "", Headers({ERROR_HEADER: outcome}))) @@ -189,6 +175,12 @@ def fetch() -> CustomProxyGatewayToken: asyncio.run(connection.run()) +@pytest.fixture +def pinned_backoff(monkeypatch): + monkeypatch.setattr(connection, "random", UpperBoundRandom()) + monkeypatch.setattr(connection, "time", FrozenTime()) + + @pytest.mark.parametrize( ("refusal", "described"), [ @@ -202,7 +194,7 @@ def fetch() -> CustomProxyGatewayToken: ), ], ) -def test_a_gateway_refusal_reconnects_and_gumloop_decides_whether_to_stop(refusal, described): +def test_a_gateway_refusal_reconnects_and_gumloop_decides_whether_to_stop(pinned_backoff, refusal, described): gateway = ScriptedGateway([refusal]) events: list[str] = [] @@ -211,34 +203,54 @@ def test_a_gateway_refusal_reconnects_and_gumloop_decides_whether_to_stop(refusa gateway, [True, True], events, - gateway_token=_tokens("token-1", SignInRefused("personal_custom_proxy_not_found")), + gateway_token=tokens("token-1", SignInRefused("personal_custom_proxy_not_found")), ) assert refused.value.reason == "personal_custom_proxy_not_found" - assert described in events - assert len(gateway.waits) == 1 + assert events == [described] + assert gateway.waits == [5.0] -def test_other_failures_reconnect_with_a_growing_wait_until_signed_out(): +@pytest.mark.parametrize( + ("refused_token", "described"), + [ + ( + Outcome(ConnectionClosed(Close(4004, "bad_token"), None), opened=True), + "the gateway closed the connection (bad_token)", + ), + (Outcome(_refused_handshake(401, "gateway_token_refused")), "the gateway answered HTTP 401"), + ], +) +def test_other_failures_reconnect_with_a_fresh_gateway_token_and_a_growing_wait_until_signed_out( + pinned_backoff, refused_token, described +): gateway = ScriptedGateway( [ Outcome(ConnectionClosed(Close(4002, "already_connected"), None), opened=True), + refused_token, Outcome(OSError("unreachable")), ] ) events: list[str] = [] + gateway_token = tokens( + "token-1", "token-2", GatewayTokenUnavailable("Gumloop didn't give a gateway token (HTTP 503)"), "token-3" + ) with pytest.raises(SignedOut): - _run(gateway, [True, True, False], events) + _run(gateway, [True, True, True, True, False], events, gateway_token=gateway_token) assert events == [ "the gateway closed the connection (already_connected)", + described, + "Gumloop didn't give a gateway token (HTTP 503)", "can't reach the gateway (unreachable)", ] - assert len(gateway.waits) == 2 - for wait, cap in zip(gateway.waits, [5.0, 10.0], strict=True): - assert FIRST_RETRY_SECONDS <= wait <= cap - assert len(set(gateway.authorizations)) == 2 + assert gateway.waits == [5.0, 10.0, 20.0, 40.0] + assert [_gateway_token_claim(authorization) for authorization in gateway.authorizations] == [ + "token-1", + "token-2", + "token-3", + ] def test_it_is_connected_only_once_the_gateway_says_the_tunnel_is_ready(): @@ -270,7 +282,6 @@ def test_a_gateway_that_needs_a_newer_cli_stops_without_retrying(): assert gateway.waits == [] -@pytest.mark.timeout(10) def test_logging_out_ends_the_open_tunnel_before_the_next_refresh(): gateway = OpenGateway(OpenConnection(closes_after=1)) login_waits: list[float] = [] @@ -285,105 +296,33 @@ async def login_sleep(seconds: float) -> None: assert gateway.waits == [] -@pytest.mark.parametrize( - "refused_token", - [ - Outcome(ConnectionClosed(Close(4004, "bad_token"), None), opened=True), - Outcome(_refused_handshake(401, "gateway_token_refused")), - ], -) -def test_a_refused_gateway_token_reconnects_with_a_fresh_one(refused_token): - gateway = ScriptedGateway([refused_token, Outcome(OSError("unreachable"))]) - tokens = iter(["token-1", "token-2"]) - - with pytest.raises(SignedOut): - _run(gateway, [True, True, False], gateway_token=lambda: next(tokens)) - - assert [_gateway_token_claim(authorization) for authorization in gateway.authorizations] == ["token-1", "token-2"] - - -def test_a_gateway_token_gumloop_did_not_give_is_retried_before_connecting(): - gateway = ScriptedGateway([Outcome(OSError("unreachable"))]) - tokens: list[str | Exception] = [ - GatewayTokenUnavailable("Gumloop didn't give a gateway token (HTTP 503)"), - "token-1", - ] - events: list[str] = [] - - def gateway_token() -> str: - result = tokens.pop(0) - if isinstance(result, Exception): - raise result - return result - - with pytest.raises(SignedOut): - _run(gateway, [True, True, False], events, gateway_token=gateway_token) - - assert events == ["Gumloop didn't give a gateway token (HTTP 503)", "can't reach the gateway (unreachable)"] - assert [_gateway_token_claim(authorization) for authorization in gateway.authorizations] == ["token-1"] - - -def test_a_gateway_token_refused_by_gumloop_stops_without_connecting(): - gateway = ScriptedGateway([]) - - def gateway_token() -> str: - raise SignInRefused("removed") - - with pytest.raises(SignInRefused): - _run(gateway, [True], gateway_token=gateway_token) - - assert gateway.authorizations == [] - assert gateway.waits == [] - - @pytest.mark.parametrize("utc_suffix", ["+00:00", "Z"]) -def test_an_open_tunnel_sends_a_fresh_gateway_token_before_its_current_one_expires(utc_suffix): +def test_an_open_tunnel_sends_a_fresh_gateway_token_before_its_current_one_expires(monkeypatch, utc_suffix): + monkeypatch.setattr(connection, "datetime", FrozenDatetime) gateway = OpenGateway(OpenConnection(closes_after=1)) refresh_sleep = RefreshSleep(returns=1) - expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at=_expiring_in(20, utc_suffix)) + expires_at = (FROZEN_NOW + timedelta(minutes=20)).isoformat().replace("+00:00", utc_suffix) + expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at=expires_at) with pytest.raises(SignedOut): - _run(gateway, [True, False], gateway_token=_tokens(expiring, "token-2"), refresh_sleep=refresh_sleep) + _run(gateway, [True, False], gateway_token=tokens(expiring, "token-2"), refresh_sleep=refresh_sleep) - assert refresh_sleep.waits == [pytest.approx(20 * 60 - REFRESH_BEFORE_EXPIRY_SECONDS, abs=5)] + assert refresh_sleep.waits == [20 * 60 - REFRESH_BEFORE_EXPIRY_SECONDS] assert gateway.connection.sent == [Frame.gateway_token("token-2")] -def test_a_gateway_token_without_an_expiry_is_never_refreshed(): - gateway = ScriptedGateway([Outcome(OSError("closed"), opened=True)]) - refresh_sleep = RefreshSleep(returns=0) - - with pytest.raises(SignedOut): - _run(gateway, [True, False], refresh_sleep=refresh_sleep) - - assert refresh_sleep.waits == [] - - -def test_a_gateway_token_refresh_gumloop_did_not_give_is_retried(): +def test_a_refresh_after_unlinking_ends_the_open_tunnel(): gateway = OpenGateway(OpenConnection(closes_after=1)) - refresh_sleep = RefreshSleep(returns=2) - expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at=_expiring_in(10)) + expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at="2027-01-15T12:20:00Z") - with pytest.raises(SignedOut): + with pytest.raises(SignInRefused) as refused: _run( gateway, - [True, False], - gateway_token=_tokens(expiring, GatewayTokenUnavailable("HTTP 503"), "token-2"), - refresh_sleep=refresh_sleep, + [True], + gateway_token=tokens(expiring, SignInRefused("personal_custom_proxy_not_found")), + refresh_sleep=RefreshSleep(returns=1), ) - assert refresh_sleep.waits == [MIN_REFRESH_SECONDS, MIN_REFRESH_SECONDS] - assert gateway.connection.sent == [Frame.gateway_token("token-2")] - - -@pytest.mark.timeout(10) -@pytest.mark.parametrize("ended_by", [SignedOut(), SignInRefused("personal_custom_proxy_not_found")]) -def test_a_refresh_after_signing_out_or_unlinking_ends_the_open_tunnel(ended_by): - gateway = OpenGateway(OpenConnection(closes_after=1)) - expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at=_expiring_in(20)) - - with pytest.raises(type(ended_by)): - _run(gateway, [True], gateway_token=_tokens(expiring, ended_by), refresh_sleep=RefreshSleep(returns=1)) - + assert refused.value.reason == "personal_custom_proxy_not_found" assert gateway.connection.sent == [] assert gateway.waits == [] diff --git a/tests/linked_proxy/test_tls_check.py b/tests/linked_proxy/test_tls_check.py index 339362c..e1e8558 100644 --- a/tests/linked_proxy/test_tls_check.py +++ b/tests/linked_proxy/test_tls_check.py @@ -58,11 +58,4 @@ def serve() -> None: server.start() with listener, pytest.raises(TlsInspected): check_tls_not_inspected("localhost", listener.getsockname()[1]) - server.join(timeout=5) - - -def test_an_unreachable_site_is_not_inspection(): - with socket.create_server(("127.0.0.1", 0)) as closed: - port = closed.getsockname()[1] - - check_tls_not_inspected("127.0.0.1", port) + server.join() From 6166249dace3f7840c5a641bc9832758bc0698d4 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 17:53:21 +0000 Subject: [PATCH 13/14] [PROD-871] link deletes a lost key's personal proxy before registering, since a member can have one Co-authored-by: Cursor --- src/gumloop/cli/commands/custom_proxy.py | 21 ++++------------ tests/cli/test_custom_proxy_command.py | 31 +++++++----------------- 2 files changed, 14 insertions(+), 38 deletions(-) diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index 818e772..7c9c7b6 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -406,8 +406,11 @@ def _register( cli: CliContext, host: str, key: Ed25519PrivateKey, name: str | None, previous: CustomProxyRegistration | None ) -> None: """Registering this key again gets its personal proxy, or a new one if it was unlinked in Gumloop. A previous - registration of a key the keychain lost is unusable, so its personal proxy is replaced and its default kept.""" - replaced = previous if previous is not None and previous.public_key != public_key_text(key) else None + registration of a key the keychain lost is unusable, so its personal proxy is replaced.""" + if previous is not None and previous.public_key != public_key_text(key): + # Gumloop allows one personal proxy, so the lost key's goes before this key registers. + _delete_custom_proxy(cli, previous.custom_proxy_id) + forget_registration(host) machine_name = socket.gethostname() response = cli.call_with_refresh( lambda client: client.custom_proxies.register_cli( @@ -425,24 +428,10 @@ def _register( user_id=_login_user_id(_stored_credentials()), ) save_registration(host, registration) - # Deleted only now, so a failed registration leaves the lost key's personal proxy and its default in place. - keep_default = replaced is not None and _delete_lost_custom_proxy(cli, replaced.custom_proxy_id) - if keep_default and not response.custom_proxy.is_default: - cli.call_with_refresh(lambda client: client.custom_proxies.set_default(registration.custom_proxy_id)) added_name = escape_markup(response.custom_proxy.name) console.print(f"[green]Linked[/green] this computer to Gumloop as '{added_name}'.") -def _delete_lost_custom_proxy(cli: CliContext, custom_proxy_id: str) -> bool: - """Returns whether it was the default.""" - listed = cli.call_with_refresh(lambda client: client.custom_proxies.list()) - lost = next((custom_proxy for custom_proxy in listed.custom_proxies if custom_proxy.id == custom_proxy_id), None) - if lost is None: - return False - _delete_custom_proxy(cli, custom_proxy_id) - return lost.is_default - - def _delete_custom_proxy(cli: CliContext, custom_proxy_id: str) -> None: """One Gumloop no longer has counts as deleted.""" try: diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index 347ba56..0a0bf37 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -287,46 +287,33 @@ def test_connect_with_a_lost_key_stops_without_making_one_and_keeps_the_registra assert (keyring.get_password(KEYRING_SERVICE, f"custom-proxy:{HOST}") is not None) is key_kept -@pytest.mark.parametrize(("was_default", "default_route_called"), [(True, True), (False, False)]) @respx.mock -def test_link_replaces_the_custom_proxy_of_a_lost_key_and_keeps_its_default( - cli_runner, service, was_default, default_route_called -): +def test_link_deletes_the_custom_proxy_of_a_lost_key_before_registering(cli_runner, service): save_registration(HOST, _registration(public_key="a key the keychain no longer has")) - lost = {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": was_default} - replacement = {"id": "dp-2", "name": "Ada's laptop", "kind": "cli", "is_default": False} - respx.get(f"{API_BASE}/custom-proxies").respond(200, json={"custom_proxies": [lost], "limit": 5}) - deleted = respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(204) - registered = respx.post(f"{API_BASE}/custom-proxies").respond( + replacement = {"id": "dp-2", "name": "Ada's laptop", "kind": "cli", "is_default": True} + respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(204) + respx.post(f"{API_BASE}/custom-proxies").respond( 201, json={"custom_proxy": replacement, "gateway_url": GATEWAY_URL} ) - made_default = respx.post(f"{API_BASE}/custom-proxies/dp-2/default").respond( - 200, json={"custom_proxy": {**replacement, "is_default": True}} - ) result = cli_runner.invoke(app, ["browser", "proxy", "link"]) assert result.exit_code == 0, result.output - assert deleted.called - assert registered.called - assert made_default.called is default_route_called + assert [call.request.method for call in respx.calls] == ["DELETE", "POST"] assert load_registration(HOST) == _registration(custom_proxy_id="dp-2") @respx.mock -def test_link_with_a_lost_key_keeps_its_custom_proxy_when_registering_fails(cli_runner, service): - lost = _registration(public_key="a key the keychain no longer has") - save_registration(HOST, lost) - listed = {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": True} - respx.get(f"{API_BASE}/custom-proxies").respond(200, json={"custom_proxies": [listed], "limit": 5}) +def test_link_with_a_lost_key_forgets_its_deleted_custom_proxy_when_registering_fails(cli_runner, service): + save_registration(HOST, _registration(public_key="a key the keychain no longer has")) deleted = respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(204) respx.post(f"{API_BASE}/custom-proxies").respond(422, json={"error": "invalid_request"}) result = cli_runner.invoke(app, ["browser", "proxy", "link"]) assert result.exit_code == 1 - assert not deleted.called - assert load_registration(HOST) == lost + assert deleted.called + assert load_registration(HOST) is None assert not service.installed From 7bd8bec52f0c4a44a66406abfd58013f4d3d97e6 Mon Sep 17 00:00:00 2001 From: daniel-panhead Date: Thu, 26 Nov 2026 21:31:51 +0000 Subject: [PATCH 14/14] [PROD-871] unlink asks before deleting a linked computer's personal proxy Like the delete commands from PROD-1088, browser proxy unlink says what it removes and asks yes/no in a terminal, with no as the default. Without a terminal it is refused unless --yes is passed. It asks only when this computer is linked to the current backend. logout and link still remove a personal proxy without asking: that is a side effect of the command run. Co-authored-by: Cursor --- README.md | 2 +- src/gumloop/cli/commands/custom_proxy.py | 14 +++++- .../gumloop/skills/gumloop-cli/SKILL.md | 2 +- .../skills/gumloop-cli/references/commands.md | 2 +- tests/cli/test_custom_proxy_command.py | 44 ++++++++++++++++++- 5 files changed, 58 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4f8bf21..8f7f2fe 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ gumloop agents delete agent_abc --yes --json # no question; required with -- gumloop agents update agent_abc --inactive --yes ``` -Every other command that deletes something asks the same way and takes the same `--yes`: `agents triggers delete`, `artifacts delete`, `brain sources delete`, `brain files delete`, `browser profiles delete`, `evaluations delete`, `sessions queue delete` and `skills delete`. Scripts that call them need `--yes` from version 0.5.16 on too. `brain sync --prune` does not ask: passing `--prune` is the confirmation. +Every other command that deletes something asks the same way and takes the same `--yes`: `agents triggers delete`, `artifacts delete`, `brain sources delete`, `brain files delete`, `browser profiles delete`, `evaluations delete`, `sessions queue delete`, `skills delete` and, when this computer is linked, `browser proxy unlink`. Scripts that call them need `--yes` from version 0.5.16 on too. `brain sync --prune` does not ask: passing `--prune` is the confirmation. Agent session `create` and `send` accept `--stream`; combine with `--json` for NDJSON events, including cursors and terminal/error events. Reconnect with `gumloop sessions resume SESSION_ID --cursor LAST_STREAM_CURSOR --json` without resending a message. Human streams show text and resume cursors. `sessions create --metadata-json '{"source":"cli"}'` sets session metadata. Without `--stream`, create/send return the immediate session response and execution may continue asynchronously. Read the reply from `session.response` and `session.response_files`. Per message, `message.text` and `message.files` read a message's text and file parts. diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index 7c9c7b6..056d19e 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -21,6 +21,8 @@ from gumloop import GumloopError from gumloop._client import DEFAULT_BASE_URL from gumloop._version import __version__ +from gumloop.cli.commands._confirmation import Yes +from gumloop.cli.commands._confirmation import confirm_or_exit from gumloop.cli.console import console from gumloop.cli.console import error_console from gumloop.cli.console import print_json @@ -200,10 +202,20 @@ def status( @proxy_app.command("unlink") -def unlink(ctx: typer.Context) -> None: +def unlink(ctx: typer.Context, yes: Yes = False) -> None: """Unlink this computer from Gumloop, and delete its key from this computer.""" cli: CliContext = ctx.obj host = backend_host(cli.effective_base_url) + if load_registration(host) is not None: + confirm_or_exit( + warning=( + "This deletes this computer's personal proxy from Gumloop and its key from this computer. " + "Agents set to use it can no longer browse through it." + ), + question="Unlink this computer?", + yes=yes, + json_output=False, + ) try: removed = remove_custom_proxy(cli, host) except (GumloopError, httpx.HTTPError) as error: diff --git a/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/SKILL.md b/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/SKILL.md index e293506..1330ecd 100644 --- a/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/SKILL.md +++ b/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/SKILL.md @@ -100,7 +100,7 @@ Structured output: `--schema-file schema.json`. Stdin input: `--message-stdin -` - `gumloop agents delete` and `gumloop agents update --inactive` (or `is_active: false` in request JSON) both **remove** the agent (later `get`/`update` return 404). Neither can be undone from the CLI; only Gumloop support can restore the agent. `--inactive` is not a pause, and `--is-active` cannot bring the agent back. To stop autonomous runs, turn off the agent's triggers instead: `gumloop agents triggers update --args-json '{"enabled":false}'`, or in the app. - Both commands ask a yes/no question in a terminal. With `--json` or without a terminal they are refused unless `--yes` is passed. Pass `--yes` only after the person has confirmed, for that specific agent, that they want it removed. Never add `--yes` on your own to get past the refusal: show the person which agent will be removed and ask first. -- Every other command that deletes something is refused the same way and follows the same rule for `--yes`: `agents triggers delete`, `artifacts delete`, `brain sources delete`, `brain files delete`, `browser profiles delete`, `evaluations delete`, `sessions queue delete` and `skills delete`. +- Every other command that deletes something is refused the same way and follows the same rule for `--yes`: `agents triggers delete`, `artifacts delete`, `brain sources delete`, `brain files delete`, `browser profiles delete`, `evaluations delete`, `sessions queue delete`, `skills delete` and, when this computer is linked, `browser proxy unlink`. - `gumloop skills update` is a full replace, not a merge — pass every file the skill should keep. - `sessions create`/`send` return the final response only; there is no token streaming in the CLI (the Python SDK's `client.sessions.stream()` has it). - Company Brain requires the Pro plan and consumes credits per search. diff --git a/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md b/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md index debc5c4..1c5c7a1 100644 --- a/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md +++ b/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md @@ -158,7 +158,7 @@ gumloop sync --once --non-interactive # one-shot sync; requires GUMLOOP_API_KEY ```bash gumloop browser proxy link # automatically runs in the background on startup gumloop browser proxy status -gumloop browser proxy unlink +gumloop browser proxy unlink [--yes] ``` macOS and Linux only. Needs a stored `gumloop login`; logging out unlinks this computer. diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index 0a0bf37..26f4137 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -329,7 +329,7 @@ def test_link_refuses_a_computer_linked_to_someone_else(cli_runner, service): assert not service.installed -@pytest.mark.parametrize("command", [["browser", "proxy", "unlink"], ["logout"]]) +@pytest.mark.parametrize("command", [["browser", "proxy", "unlink", "--yes"], ["logout"]]) @pytest.mark.parametrize( ("status", "payload"), [(204, None), (404, {"error": {"code": "personal_custom_proxy_not_found"}})] ) @@ -416,8 +416,48 @@ def test_remove_keeps_the_key_when_gumloop_cannot_delete_the_custom_proxy(cli_ru key = public_key_text(load_or_create_key(HOST)) respx.delete(f"{API_BASE}/custom-proxies/dp-1").respond(status, json=payload) - result = cli_runner.invoke(app, ["browser", "proxy", "unlink"]) + result = cli_runner.invoke(app, ["browser", "proxy", "unlink", "--yes"]) assert result.exit_code == 1 assert public_key_text(load_or_create_key(HOST)) == key assert load_registration(HOST) == _registration() + + +@pytest.mark.parametrize("answer", [False, None]) +@respx.mock +def test_unlink_declined_in_a_terminal_keeps_the_personal_proxy_and_key( + cli_runner, service, answer_in_terminal, answer +): + asked = answer_in_terminal(answer) + save_registration(HOST, _registration()) + route = respx.delete(f"{API_BASE}/custom-proxies/dp-1") + + result = cli_runner.invoke(app, ["browser", "proxy", "unlink"]) + + assert result.exit_code == 1 + assert asked == [("Unlink this computer?", False)] + assert not route.called + assert load_registration(HOST) == _registration() + + +@respx.mock +def test_unlink_without_a_terminal_is_refused_unless_yes_is_passed(cli_runner, service): + save_registration(HOST, _registration()) + route = respx.delete(f"{API_BASE}/custom-proxies/dp-1") + + result = cli_runner.invoke(app, ["browser", "proxy", "unlink"]) + + assert result.exit_code == 1 + assert "Pass --yes to confirm." in " ".join(result.stderr.split()) + assert not route.called + assert load_registration(HOST) == _registration() + + +def test_unlink_asks_nothing_when_this_computer_is_not_linked(cli_runner, service, answer_in_terminal): + asked = answer_in_terminal(False) + + result = cli_runner.invoke(app, ["browser", "proxy", "unlink"]) + + assert result.exit_code == 0, result.output + assert asked == [] + assert "This computer is not linked." in result.output