diff --git a/README.md b/README.md index 8aa43fa..8f7f2fe 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. @@ -66,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/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..285a789 100644 --- a/src/gumloop/cli/commands/auth.py +++ b/src/gumloop/cli/commands/auth.py @@ -4,18 +4,23 @@ 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._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 from gumloop.cli.context import CliContext 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 @@ -202,27 +207,47 @@ 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_stored_login_custom_proxy() + 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 revoke_failed = False if cli.effective_auth_method == METHOD_OAUTH: - token = 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 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 +259,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..056d19e --- /dev/null +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -0,0 +1,493 @@ +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.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 +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_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 +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 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 +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.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.", + "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" + + +@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." + ) + _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, httpx.HTTPError) as error: + exit_with_error(_explained(error)) + + 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 + 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") +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, 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: + 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: + _delete_custom_proxy(cli, registration.custom_proxy_id) + forget(host) + 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, + 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) + 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 + # 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." + ) + 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: + # `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." + ) + 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( + 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 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: + 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: + """A refusal stops the personal proxy, except the ones that can pass on their own: a timeout, + 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: + 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 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 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: + 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, 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.""" + 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( + 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"[green]Linked[/green] this computer to Gumloop as '{added_name}'.") + + +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: + 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..89f91aa 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,23 +50,44 @@ 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 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: @@ -75,18 +102,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..6c1bb11 --- /dev/null +++ b/src/gumloop/cli/custom_proxy_service.py @@ -0,0 +1,211 @@ +"""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 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}"' + + +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/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 249b5d8..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 @@ -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 [--yes] +``` + +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..40d15e4 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 -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 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,40 @@ 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" +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. +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 +# 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]] 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) @@ -58,6 +72,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, @@ -66,10 +84,14 @@ 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, + login_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, ) -> None: self._gateway_url = gateway_url self._linked_proxy_id = linked_proxy_id @@ -77,15 +99,21 @@ 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 + self._login_sleep = login_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 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 +121,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 +134,77 @@ 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() - + 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()), 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: + 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 _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() -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 + 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``.""" + 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 + 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 +212,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..26f4137 --- /dev/null +++ b/tests/cli/test_custom_proxy_command.py @@ -0,0 +1,463 @@ +from __future__ import annotations + +import base64 +import json +from collections.abc import Callable +from pathlib import Path +from types import ModuleType +from urllib.parse import parse_qs + +import httpx +import keyring +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 +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.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.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" +REGISTERED = { + "custom_proxy": {"id": "dp-1", "name": "Ada's laptop", "kind": "cli", "is_default": True}, + "gateway_url": GATEWAY_URL, +} + + +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 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 + 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) + 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, monkeypatch, fake_executable_path, platform_service, installed_executable +): + 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 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 service.executable == installed_executable(fake_executable_path) + + +@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 + + +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 + + +@pytest.mark.parametrize( + ("status", "payload", "expected_fetched", "kept"), + [ + (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"]}, + [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_fetched, 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_fetched + 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() + + +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, reset_keychain, key_kept +): + lost = _registration(public_key="a key the keychain no longer has") + save_registration(HOST, lost) + 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 not None) is key_kept + + +@respx.mock +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")) + 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} + ) + + result = cli_runner.invoke(app, ["browser", "proxy", "link"]) + + assert result.exit_code == 0, result.output + 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_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 deleted.called + assert load_registration(HOST) is None + assert not service.installed + + +@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 + + +@pytest.mark.parametrize("command", [["browser", "proxy", "unlink", "--yes"], ["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, 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(status, json=payload) + + 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 + + +@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 + + +@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"] + + +@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( + ("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, link_this_backend, kept +): + service.installed = True + link_this_backend() + + 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 + + +@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, 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(status, json=payload) + + 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 diff --git a/tests/cli/test_custom_proxy_key.py b/tests/cli/test_custom_proxy_key.py index de9d146..f8a047f 100644 --- a/tests/cli/test_custom_proxy_key.py +++ b/tests/cli/test_custom_proxy_key.py @@ -7,7 +7,9 @@ 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") + registration = CustomProxyRegistration( + custom_proxy_id="dp-1", name="Ada's laptop", gateway_url="ws://localhost:8443/v1/cli/connect", public_key="key" + ) assert registration.gateway_url == "ws://localhost:8443/v1/cli/connect" @@ -15,7 +17,10 @@ def test_registration_accepts_an_unencrypted_gateway_on_this_computer(): def test_registration_refuses_an_unencrypted_remote_gateway(): with pytest.raises(ValidationError) as refused: CustomProxyRegistration( - custom_proxy_id="dp-1", gateway_url="ws://linked-proxy-gateway.gumloop.com/v1/cli/connect" + 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()] == [ diff --git a/tests/cli/test_custom_proxy_service.py b/tests/cli/test_custom_proxy_service.py new file mode 100644 index 0000000..25ef3c9 --- /dev/null +++ b/tests/cli/test_custom_proxy_service.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import plistlib +import subprocess +from collections.abc import Sequence +from pathlib import Path + +from gumloop.cli.custom_proxy_service import LaunchAgentService +from gumloop.cli.custom_proxy_service import SystemdUserService + +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: + 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) + + 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_as_written_at_login_and_after_failures(tmp_path): + runner = RecordingRunner() + service = SystemdUserService(config_home=tmp_path, run_command=runner) + + service.install(Path('/home/a$b/100%/"q"\\gumloop')) + + 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"], + ] 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 154ff17..b59414f 100644 --- a/tests/linked_proxy/test_connection.py +++ b/tests/linked_proxy/test_connection.py @@ -5,8 +5,10 @@ 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 timedelta import pytest from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey @@ -18,10 +20,20 @@ from gumloop.linked_proxy import connection from gumloop.linked_proxy.connection import ERROR_HEADER +from gumloop.linked_proxy.connection import LOGIN_CHECK_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 +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 @@ -32,20 +44,27 @@ @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 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 @@ -53,20 +72,66 @@ 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) +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 _refused_handshake(status: int, outcome: str) -> InvalidStatus: return InvalidStatus(Response(status, "", Headers({ERROR_HEADER: outcome}))) @@ -76,52 +141,89 @@ 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, + 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, + login_sleep: Callable[[float], Awaitable[None]] = _never, ) -> 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, + login_sleep=login_sleep, ) asyncio.run(connection.run()) +@pytest.fixture +def pinned_backoff(monkeypatch): + monkeypatch.setattr(connection, "random", UpperBoundRandom()) + monkeypatch.setattr(connection, "time", FrozenTime()) + + @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(pinned_backoff, 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 events == [described] + assert gateway.waits == [5.0] @pytest.mark.parametrize( - "refused_token", + ("refused_token", "described"), [ - Outcome(ConnectionClosed(Close(4004, "bad_token"), None), opened=True), - Outcome(_refused_handshake(401, "gateway_token_refused")), + ( + 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( - monkeypatch, refused_token + pinned_backoff, refused_token, described ): - monkeypatch.setattr(connection, "random", UpperBoundRandom()) - monkeypatch.setattr(connection, "time", FrozenTime()) gateway = ScriptedGateway( [ Outcome(ConnectionClosed(Close(4002, "already_connected"), None), opened=True), @@ -129,12 +231,21 @@ def test_other_failures_reconnect_with_a_fresh_gateway_token_and_a_growing_wait_ Outcome(OSError("unreachable")), ] ) - gateway_token = tokens("token-1", "token-2", GatewayTokenUnavailable("HTTP 503"), "token-3") + 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, True, True, False], gateway_token=gateway_token) + _run(gateway, [True, True, True, True, False], events, gateway_token=gateway_token) - assert gateway.waits == [1.0, 2.0, 4.0, 8.0] + 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 gateway.waits == [5.0, 10.0, 20.0, 40.0] assert [_gateway_token_claim(authorization) for authorization in gateway.authorizations] == [ "token-1", "token-2", @@ -142,14 +253,76 @@ def test_other_failures_reconnect_with_a_fresh_gateway_token_and_a_growing_wait_ ] -def test_a_gateway_token_refused_by_gumloop_stops_without_connecting(): - gateway = ScriptedGateway([]) +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"))]) - def gateway_token() -> str: - raise SignInRefused("removed") + with pytest.raises(UpgradeRequired): + _run(gateway, [True]) - with pytest.raises(SignInRefused): - _run(gateway, [True], gateway_token=gateway_token) + assert gateway.waits == [] - assert gateway.authorizations == [] + +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("utc_suffix", ["+00:00", "Z"]) +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) + 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) + + assert refresh_sleep.waits == [20 * 60 - REFRESH_BEFORE_EXPIRY_SECONDS] + assert gateway.connection.sent == [Frame.gateway_token("token-2")] + + +def test_a_refresh_after_unlinking_ends_the_open_tunnel(): + gateway = OpenGateway(OpenConnection(closes_after=1)) + expiring = CustomProxyGatewayToken(gateway_token="token-1", expires_at="2027-01-15T12:20:00Z") + + with pytest.raises(SignInRefused) as refused: + _run( + gateway, + [True], + gateway_token=tokens(expiring, SignInRefused("personal_custom_proxy_not_found")), + 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 new file mode 100644 index 0000000..e1e8558 --- /dev/null +++ b/tests/linked_proxy/test_tls_check.py @@ -0,0 +1,61 @@ +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()