From a194563b0d2e83286edcef3cf8b9ddf27b812cbe Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 21:18:03 -0500 Subject: [PATCH] feat(flow): sign in to Cloud from the terminal with the browser (openadapt login) --- CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/openadapt_flow/__main__.py | 18 +- packages/flow/openadapt_flow/browser_login.py | 338 ++++++++++++++++++ packages/flow/openadapt_flow/hosted.py | 15 +- packages/flow/tests/test_browser_login.py | 249 +++++++++++++ 6 files changed, 612 insertions(+), 10 deletions(-) create mode 100644 packages/flow/openadapt_flow/browser_login.py create mode 100644 packages/flow/tests/test_browser_login.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 7f7a85d526..1afaf0b031 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -353,6 +353,7 @@ improvising or retrying when something is off. | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](packages/flow/docs/WRITE_RECEIPTS.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](packages/seal-view/README.md) | +| Sign in to OpenAdapt Cloud from the terminal: `openadapt login` with no token prints a sign-in link (opened only with `--open`), listens on 127.0.0.1 for the browser's redirect, and redeems Cloud's one-use code with an S256 PKCE verifier that never leaves the process. A first-time user gets a workspace on the way. The credential goes to the OS keychain entry `push` and `report-run` read; a stored token is re-validated as before, and `--token` and `--no-browser` keep the token path | On main | Unit tests with a real loopback listener (state mismatch, refusal, malformed code, timeout, browser opened only on request); end to end against Cloud's `/auth/loopback` and pairing routes in mock mode, both Connect and Cancel | `openadapt login`; [browser_login.py](packages/flow/openadapt_flow/browser_login.py) | | Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | | Run authorizations signed with the authorizer's GitHub SSH key (`ssh-keygen -Y sign`, after a summary of what it allows), naming the signing key and bound to the bundle digest, items, profile and Seal keys, and referenced by each Seal; the identity checked against github.com (`--live`) or pinned allowed signers; a pseudonymous operator profile counted from anchored Seals only | Released ([#1401](https://github.com/OpenAdaptAI/OpenAdapt/pull/1401)) | Unit tests with synthetic data; signatures checked against OpenSSH's `ssh-keygen` both ways | `openadapt-flow local-seal authorize`, `local-seal run --authorization`, `local-seal profile`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#run-authorizations-who-authorized-the-runs) | | Run reports redacted before they are sealed: session and CSRF tokens, OAuth grants and credential headers become `` and are listed in `redactions`; a Seal refuses a report that still holds one; per-app policy | Released ([#1407](https://github.com/OpenAdaptAI/OpenAdapt/pull/1407)) | Unit tests with generated tokens; 7,773 local reports scanned, only OpenEMR `token_main` matched | `openadapt-flow redact-report`, `local-seal run --allow-unredacted`; [REPORT_REDACTION.md](packages/flow/docs/REPORT_REDACTION.md) | diff --git a/llms-full.txt b/llms-full.txt index c74a23a193..d43b1aea9e 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -787,6 +787,7 @@ improvising or retrying when something is off. | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRITE_RECEIPTS.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/seal-view/README.md) | +| Sign in to OpenAdapt Cloud from the terminal: `openadapt login` with no token prints a sign-in link (opened only with `--open`), listens on 127.0.0.1 for the browser's redirect, and redeems Cloud's one-use code with an S256 PKCE verifier that never leaves the process. A first-time user gets a workspace on the way. The credential goes to the OS keychain entry `push` and `report-run` read; a stored token is re-validated as before, and `--token` and `--no-browser` keep the token path | On main | Unit tests with a real loopback listener (state mismatch, refusal, malformed code, timeout, browser opened only on request); end to end against Cloud's `/auth/loopback` and pairing routes in mock mode, both Connect and Cancel | `openadapt login`; [browser_login.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/openadapt_flow/browser_login.py) | | Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | | Run authorizations signed with the authorizer's GitHub SSH key (`ssh-keygen -Y sign`, after a summary of what it allows), naming the signing key and bound to the bundle digest, items, profile and Seal keys, and referenced by each Seal; the identity checked against github.com (`--live`) or pinned allowed signers; a pseudonymous operator profile counted from anchored Seals only | Released ([#1401](https://github.com/OpenAdaptAI/OpenAdapt/pull/1401)) | Unit tests with synthetic data; signatures checked against OpenSSH's `ssh-keygen` both ways | `openadapt-flow local-seal authorize`, `local-seal run --authorization`, `local-seal profile`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#run-authorizations-who-authorized-the-runs) | | Run reports redacted before they are sealed: session and CSRF tokens, OAuth grants and credential headers become `` and are listed in `redactions`; a Seal refuses a report that still holds one; per-app policy | Released ([#1407](https://github.com/OpenAdaptAI/OpenAdapt/pull/1407)) | Unit tests with generated tokens; 7,773 local reports scanned, only OpenEMR `token_main` matched | `openadapt-flow redact-report`, `local-seal run --allow-unredacted`; [REPORT_REDACTION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/REPORT_REDACTION.md) | diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 8ba93ace19..931f0ee13a 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -7603,15 +7603,12 @@ def _cmd_emit_mcp(args: argparse.Namespace) -> int: def _cmd_login(args: argparse.Namespace) -> int: - """Validate an ingest token against the hosted control plane and store the - host in config and the token in the OS keychain when saving is enabled. - - Token resolution: ``--token`` -> ``OPENADAPT_INGEST_TOKEN`` env -> - OS keychain -> existing config migration token. Mint a - token in the dashboard at ``/dashboard/settings/ingest``. - """ + """Browser sign-in when no token is found, else validate the ingest token.""" + from openadapt_flow import browser_login from openadapt_flow.hosted import HostedError, login + if browser_login.uses_browser(args): + return browser_login.run_cli(args) try: result = login( token=args.token, @@ -12391,8 +12388,8 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: p = sub.add_parser( "login", help=( - "Validate an ingest token against the hosted control plane and " - "store it in the OS keychain" + "Sign in to OpenAdapt Cloud through the browser, or validate an " + "ingest token, and keep the credential in the OS keychain" ), allow_abbrev=False, ) @@ -12435,6 +12432,9 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: "is available (insecure fallback)" ), ) + from openadapt_flow.browser_login import add_cli_arguments + + add_cli_arguments(p) p.set_defaults(func=_cmd_login) p = sub.add_parser( diff --git a/packages/flow/openadapt_flow/browser_login.py b/packages/flow/openadapt_flow/browser_login.py new file mode 100644 index 0000000000..6433b7e2d5 --- /dev/null +++ b/packages/flow/openadapt_flow/browser_login.py @@ -0,0 +1,338 @@ +"""Sign in to OpenAdapt Cloud from the terminal with the system browser. + +``openadapt login`` with no token runs this. It is an RFC 8252 native-app +login, the same one OpenAdapt Desktop uses, and it needs no Cloud change: + +1. Make an S256 PKCE verifier and challenge, and listen on + ``127.0.0.1:/callback`` (loopback only, one path). +2. Print ``{host}/login?redirect_to=…&code_challenge=…&state=…``. The browser + is opened only when the caller passes ``open_browser`` (``--open``). +3. The person signs in (Google or a magic link). A first-time user gets a + workspace from onboarding on the way. Cloud's ``/auth/loopback`` page asks + them to approve this computer, mints a five-minute pairing code bound to + the challenge, and redirects to the listener with ``?code=oap_…&state=…``. +4. :func:`openadapt_flow.hosted.connect` redeems the code with the verifier. + It stages, validates, promotes and confirms the new ``oai_ingest_`` + credential in the OS keychain, the entry ``push`` and ``report-run`` read, + and rolls back on any failure. + +No secret is ever in a URL this module builds: the URL carries only the +challenge and an opaque state. The one-use code reaches only the loopback +listener, and it is worthless without the verifier, which never leaves this +process. +""" + +from __future__ import annotations + +import base64 +import hashlib +import secrets +import threading +import urllib.parse +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import Any, Callable, Optional + +from openadapt_flow.hosted import ( + PAIRING_SECRET_RE, + HostedError, + connect, + resolve_host, +) + +LOGIN_PATH = "/login" +CALLBACK_PATH = "/callback" +#: Long enough for a magic-link email and the approval click. +DEFAULT_TIMEOUT_S = 300.0 + +_DONE_HTML = ( + b"" + b"OpenAdapt sign-in" + b"" + b"

Signed in.

You can close this tab and go back to the terminal.

" + b"" +) +_FAILED_HTML = ( + b"" + b"OpenAdapt sign-in" + b"" + b"

Sign-in did not finish.

The terminal says why.

" + b"" +) + + +class BrowserLoginError(HostedError): + """Why the browser sign-in did not finish, in one plain line.""" + + +def pkce_pair() -> tuple[str, str]: + """Return ``(verifier, challenge)`` for the S256 method (RFC 7636).""" + + verifier = base64.urlsafe_b64encode(secrets.token_bytes(48)).rstrip(b"=").decode() + digest = hashlib.sha256(verifier.encode("ascii")).digest() + challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode() + return verifier, challenge + + +class LoopbackReceiver: + """A ``127.0.0.1`` listener that keeps the first callback it receives. + + It binds 127.0.0.1, never 0.0.0.0, on a port the OS picks, and serves only + ``/callback``. A callback must carry exactly ``code`` and ``state``, or + ``error`` (with an optional short ``error_description``) and ``state``; + anything else counts as malformed. A later request cannot replace the + first one. + """ + + def __init__(self) -> None: + self.code: Optional[str] = None + self.state: Optional[str] = None + self.error_code: Optional[str] = None + self.error: Optional[str] = None + self._received = threading.Event() + receiver = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args: Any) -> None: + pass + + def do_GET(self) -> None: # noqa: N802 - stdlib name + parsed = urllib.parse.urlparse(self.path) + if parsed.path != CALLBACK_PATH: + self.send_response(404) + self.end_headers() + return + if not receiver._received.is_set(): + receiver._take( + urllib.parse.parse_qs(parsed.query, keep_blank_values=True) + ) + failed = receiver.code is None + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.send_header("Referrer-Policy", "no-referrer") + self.end_headers() + try: + self.wfile.write(_FAILED_HTML if failed else _DONE_HTML) + finally: + receiver._received.set() + + self._server = HTTPServer(("127.0.0.1", 0), Handler) + self._thread: Optional[threading.Thread] = None + + def _take(self, params: dict[str, list[str]]) -> None: + if any(len(values) != 1 for values in params.values()): + self.error = "the sign-in callback was malformed" + return + flat = {key: values[0] for key, values in params.items()} + self.state = flat.get("state") + keys = set(flat) + if keys == {"code", "state"}: + self.code = flat["code"] + elif keys in ({"error", "state"}, {"error", "error_description", "state"}): + description = flat.get("error_description") or flat["error"] + if len(description) > 256 or any( + ord(char) < 32 or ord(char) == 127 for char in description + ): + self.error = "the sign-in callback was malformed" + else: + self.error_code = flat["error"] + self.error = description + else: + self.error = "the sign-in callback was malformed" + + @property + def redirect_uri(self) -> str: + return f"http://127.0.0.1:{self._server.server_address[1]}{CALLBACK_PATH}" + + def start(self) -> None: + self._thread = threading.Thread(target=self._server.serve_forever, daemon=True) + self._thread.start() + + def wait(self, timeout: float) -> bool: + return self._received.wait(timeout=timeout) + + def close(self) -> None: + if self._thread is not None: + self._server.shutdown() + self._thread.join(timeout=5.0) + self._thread = None + self._server.server_close() + + def __enter__(self) -> "LoopbackReceiver": + return self + + def __exit__(self, *exc_info: Any) -> None: + self.close() + + +def login_url(host: str, redirect_uri: str, challenge: str, state: str) -> str: + query = urllib.parse.urlencode( + { + "redirect_to": redirect_uri, + "code_challenge": challenge, + "code_challenge_method": "S256", + "state": state, + } + ) + return f"{host}{LOGIN_PATH}?{query}" + + +def browser_login( + host: Optional[str] = None, + *, + show_url: Callable[[str], None], + open_browser: Optional[Callable[[str], Any]] = None, + timeout: float = DEFAULT_TIMEOUT_S, + device_name: Optional[str] = None, + destination_kind: Optional[str] = None, + trusted_hosts: Optional[list[str]] = None, +) -> dict[str, Any]: + """Sign in through the browser and keep the credential in the OS keychain. + + ``show_url`` always receives the sign-in URL before anything waits. + ``open_browser``, when given, is then called with the same URL; without it + no window opens. Returns :func:`~openadapt_flow.hosted.connect`'s result. + + Raises: + BrowserLoginError: denied, timed out, a state mismatch, or a malformed + callback. + HostedError: the claim, validation or keychain step failed (nothing + is left half-stored; ``connect`` rolls back). + """ + + resolved_host = resolve_host(host) + verifier, challenge = pkce_pair() + state = secrets.token_urlsafe(24) + with LoopbackReceiver() as receiver: + url = login_url(resolved_host, receiver.redirect_uri, challenge, state) + receiver.start() + show_url(url) + if open_browser is not None: + try: + open_browser(url) + except Exception: # noqa: BLE001 - the URL is already printed + pass + receiver.wait(timeout) + code, received_state = receiver.code, receiver.state + error_code, error = receiver.error_code, receiver.error + + if code is None and error is None: + raise BrowserLoginError( + f"No sign-in arrived within {int(timeout)} seconds. Run the command again." + ) + if not secrets.compare_digest(received_state or "", state): + raise BrowserLoginError("The sign-in callback did not match this request.") + if error is not None: + if error_code == "access_denied": + raise BrowserLoginError(f"Sign-in was not approved: {error}") + raise BrowserLoginError(f"Sign-in failed: {error}") + if not PAIRING_SECRET_RE.fullmatch(code or ""): + raise BrowserLoginError("The sign-in callback carried a malformed code.") + return connect( + code or "", + host=resolved_host, + device_name=device_name, + destination_kind=destination_kind, + trusted_hosts=trusted_hosts, + code_verifier=verifier, + ) + + +# --------------------------------------------------------------------------- +# `openadapt-flow login` (and `openadapt login`) command-line wiring +# --------------------------------------------------------------------------- + + +def add_cli_arguments(parser: Any) -> None: + """Add ``--browser``/``--no-browser``, ``--open`` and ``--timeout`` to ``login``.""" + + choice = parser.add_mutually_exclusive_group() + choice.add_argument( + "--browser", + dest="browser", + action="store_true", + default=None, + help=( + "Sign in through the browser even when a token is stored. This is " + "the default when no token is given or stored" + ), + ) + choice.add_argument( + "--no-browser", + dest="browser", + action="store_false", + help="Use only --token, OPENADAPT_INGEST_TOKEN or the stored token", + ) + parser.add_argument( + "--open", + action="store_true", + help="Open the sign-in link in the default browser (it is printed either way)", + ) + parser.add_argument( + "--timeout", + type=float, + default=None, + help=f"Seconds to wait for the browser sign-in (default {int(DEFAULT_TIMEOUT_S)})", + ) + + +def uses_browser(args: Any) -> bool: + """Browser sign-in unless a token was given or one is already stored. + + ``--browser`` forces it and ``--no-browser`` keeps the token path, so + ``login`` with a stored token still re-validates it as before. + """ + + from openadapt_flow.hosted import resolve_token + + if getattr(args, "browser", None) is not None: + return bool(args.browser) + if args.token or args.no_save or args.allow_plaintext_token: + return False + try: + resolve_token(None, host=args.host) + except HostedError: + return True + return False + + +def run_cli(args: Any) -> int: + """``login`` with no token: print the sign-in link, wait, store the credential.""" + + def show(url: str) -> None: + print( + "Sign in to OpenAdapt Cloud. Open this link in a browser on this computer:" + ) + print(f" {url}") + if not args.open: + print("(Add --open to open it for you.)") + print( + "Waiting for you to approve this computer... (Ctrl-C to cancel)", flush=True + ) + + opener = None + if args.open: + import webbrowser + + opener = webbrowser.open + try: + result = browser_login( + args.host, + show_url=show, + open_browser=opener, + timeout=args.timeout or DEFAULT_TIMEOUT_S, + destination_kind=args.destination_kind, + trusted_hosts=args.trusted_host, + ) + except KeyboardInterrupt: + print("login cancelled; nothing was stored.") + return 130 + except HostedError as e: + print(f"login failed: {e}") + return 1 + print( + f"Signed in to {result['host']} as {result['device_name']}. " + "The credential is in the OS keychain." + ) + print(f"Manage or revoke it at {result['settings_url']}") + return 0 diff --git a/packages/flow/openadapt_flow/hosted.py b/packages/flow/openadapt_flow/hosted.py index 8ce65abd6c..4acdd590ba 100644 --- a/packages/flow/openadapt_flow/hosted.py +++ b/packages/flow/openadapt_flow/hosted.py @@ -87,6 +87,8 @@ TOKEN_ENV = "OPENADAPT_INGEST_TOKEN" KEYRING_SERVICE = "openadapt-flow" PAIRING_SECRET_RE = re.compile(r"^oap_[A-Za-z0-9_-]{43}$") +#: RFC 7636 section 4.1: 43 to 128 unreserved characters. +PKCE_VERIFIER_RE = re.compile(r"^[A-Za-z0-9\-._~]{43,128}$") #: Environment variable naming the deployment lane (``cloud`` | ``byoc`` | #: ``regulated``). Falls back to ``config.toml`` ``[hosted] deployment_lane``. @@ -726,9 +728,15 @@ def connect( device_name: Optional[str] = None, destination_kind: Optional[str] = None, trusted_hosts: Optional[list[str]] = None, + code_verifier: Optional[str] = None, ) -> dict[str, Any]: """Claim a five-minute browser pairing without clobbering a working token. + ``code_verifier`` is the RFC 7636 verifier for a pairing that a browser + login (:mod:`openadapt_flow.browser_login`) bound to an S256 challenge. + Cloud refuses such a pairing without it, so a code seen in transit is + useless on its own. + The one-time secret authorizes only ``POST /api/local-bridge/pairings/claim``. The previous canonical token is snapshotted before the claim. The returned token is staged under a pairing-specific keyring account, validated from @@ -759,11 +767,16 @@ def connect( clean_device = re.sub(r"[\x00-\x1f\x7f]", "", device_name or socket.gethostname()) clean_device = clean_device.strip()[:80] or "this computer" + if code_verifier is not None and not PKCE_VERIFIER_RE.fullmatch(code_verifier): + raise HostedError("Login proof is malformed") + claim_body: dict[str, str] = {"pairing_secret": secret, "device_name": clean_device} + if code_verifier is not None: + claim_body["code_verifier"] = code_verifier claim_url = f"{resolved_host}/api/local-bridge/pairings/claim" try: response = httpx.post( claim_url, - json={"pairing_secret": secret, "device_name": clean_device}, + json=claim_body, timeout=_API_TIMEOUT, follow_redirects=False, ) diff --git a/packages/flow/tests/test_browser_login.py b/packages/flow/tests/test_browser_login.py new file mode 100644 index 0000000000..a55fe59971 --- /dev/null +++ b/packages/flow/tests/test_browser_login.py @@ -0,0 +1,249 @@ +"""``openadapt login`` through the browser (RFC 8252 loopback with S256 PKCE). + +The "browser" here is a real HTTP request to the real loopback listener, made +from ``show_url`` after parsing the printed sign-in URL. Cloud's claim, +validation and confirmation calls are faked at ``httpx``; the keychain is +faked at the ``hosted`` seam, as in ``test_hosted.py``. +""" + +from __future__ import annotations + +import argparse +import base64 +import hashlib +import threading +import urllib.error +import urllib.parse +import urllib.request + +import httpx +import pytest + +from openadapt_flow import __main__ as cli +from openadapt_flow import browser_login as bl +from openadapt_flow import hosted + +PAIRING = "oap_" + "A" * 43 +PAIRING_ID = "11111111-1111-4111-8111-111111111111" +TOKEN = "oai_ingest_" + "b" * 40 +HOST = "https://app.openadapt.ai" # httpx is faked; nothing leaves the test + + +@pytest.fixture(autouse=True) +def _isolated(monkeypatch, tmp_path): + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path)) + monkeypatch.delenv(hosted.TOKEN_ENV, raising=False) + store: dict[str, str | None] = {"canonical": None} + monkeypatch.setattr(hosted, "_keyring_available", lambda: True) + monkeypatch.setattr(hosted, "_keyring_token", lambda host: store["canonical"]) + monkeypatch.setattr( + hosted, "_snapshot_keyring_token", lambda host: (True, store["canonical"]) + ) + monkeypatch.setattr(hosted, "_store_staged_keyring_token", lambda h, p, t: True) + monkeypatch.setattr(hosted, "_delete_staged_keyring_token", lambda h, p: True) + + def keep(host, token): + store["canonical"] = token + return True + + monkeypatch.setattr(hosted, "_store_keyring_token", keep) + return store + + +@pytest.fixture() +def cloud(monkeypatch): + """Fake Cloud: records claim bodies and enforces the PKCE binding.""" + + seen: dict = {"claims": [], "challenge": None} + + def post(url, **kwargs): + if url.endswith("/pairings/claim"): + body = kwargs["json"] + seen["claims"].append(body) + verifier = body.get("code_verifier") + if verifier is None: + return httpx.Response(410, json={"error": "proof required"}) + digest = hashlib.sha256(verifier.encode()).digest() + if ( + base64.urlsafe_b64encode(digest).rstrip(b"=").decode() + != seen["challenge"] + ): + return httpx.Response(410, json={"error": "proof mismatch"}) + return httpx.Response( + 201, + json={"paired": True, "pairing_id": PAIRING_ID, "ingest_token": TOKEN}, + ) + if url.endswith("/pairings/confirm"): + return httpx.Response(200, json={"connected": True}) + raise AssertionError(f"unexpected POST {url}") + + def get(url, **kwargs): + assert kwargs["headers"]["Authorization"] == f"Bearer {TOKEN}" + return httpx.Response(200, json={"count": 0}) + + monkeypatch.setattr(httpx, "post", post) + monkeypatch.setattr(httpx, "get", get) + return seen + + +def _browser(cloud, *, reply=None, state_override=None): + """A ``show_url`` that plays the browser: sign in, approve, redirect.""" + + printed: list[str] = [] + + def show(url: str) -> None: + printed.append(url) + parsed = urllib.parse.urlparse(url) + query = dict(urllib.parse.parse_qsl(parsed.query)) + cloud["challenge"] = query["code_challenge"] + params = reply if reply is not None else {"code": PAIRING} + params = {**params, "state": state_override or query["state"]} + target = f"{query['redirect_to']}?{urllib.parse.urlencode(params)}" + + def visit() -> None: + with urllib.request.urlopen(target, timeout=5) as response: # noqa: S310 + response.read() + + threading.Thread(target=visit, daemon=True).start() + + return show, printed + + +def test_signs_in_and_keeps_the_credential_in_the_keychain(cloud, _isolated): + show, printed = _browser(cloud) + result = bl.browser_login(HOST, show_url=show, timeout=5) + + assert result["paired"] is True and result["token_storage"] == "keyring" + assert _isolated["canonical"] == TOKEN + (url,) = printed + parsed = urllib.parse.urlparse(url) + query = dict(urllib.parse.parse_qsl(parsed.query)) + assert f"{parsed.scheme}://{parsed.netloc}{parsed.path}" == f"{HOST}/login" + assert set(query) == { + "redirect_to", + "code_challenge", + "code_challenge_method", + "state", + } + assert query["code_challenge_method"] == "S256" + assert query["redirect_to"].startswith("http://127.0.0.1:") + assert query["redirect_to"].endswith("/callback") + # The verifier went only to the claim; nothing secret was in the URL. + (claim,) = cloud["claims"] + assert claim["pairing_secret"] == PAIRING + assert claim["code_verifier"] not in url + assert TOKEN not in url + + +def test_opens_a_browser_only_when_asked(cloud): + opened: list[str] = [] + show, printed = _browser(cloud) + bl.browser_login(HOST, show_url=show, timeout=5) + assert opened == [] + + show, printed = _browser(cloud) + bl.browser_login(HOST, show_url=show, open_browser=opened.append, timeout=5) + assert opened == printed + + +def test_a_mismatched_state_spends_nothing(cloud): + show, _ = _browser(cloud, state_override="someone-else") + with pytest.raises(bl.BrowserLoginError, match="did not match"): + bl.browser_login(HOST, show_url=show, timeout=5) + assert cloud["claims"] == [] + + +def test_a_refusal_is_reported_and_nothing_is_stored(cloud, _isolated): + show, _ = _browser( + cloud, reply={"error": "access_denied", "error_description": "Not approved"} + ) + with pytest.raises(bl.BrowserLoginError, match="not approved"): + bl.browser_login(HOST, show_url=show, timeout=5) + assert cloud["claims"] == [] and _isolated["canonical"] is None + + +def test_a_malformed_code_is_refused_before_any_claim(cloud): + show, _ = _browser(cloud, reply={"code": "not-a-pairing"}) + with pytest.raises(bl.BrowserLoginError, match="malformed"): + bl.browser_login(HOST, show_url=show, timeout=5) + assert cloud["claims"] == [] + + +def test_times_out_plainly_when_no_one_signs_in(cloud): + with pytest.raises(bl.BrowserLoginError, match="No sign-in arrived"): + bl.browser_login(HOST, show_url=lambda url: None, timeout=0.2) + assert cloud["claims"] == [] + + +def test_the_listener_serves_only_the_callback_on_loopback(): + with bl.LoopbackReceiver() as receiver: + receiver.start() + assert receiver.redirect_uri.startswith("http://127.0.0.1:") + other = receiver.redirect_uri.replace("/callback", "/anything") + with pytest.raises(urllib.error.HTTPError) as caught: + urllib.request.urlopen(other, timeout=5) # noqa: S310 + assert caught.value.code == 404 + assert receiver.code is None + + +def test_connect_sends_the_verifier_only_when_given(cloud): + verifier, challenge = bl.pkce_pair() + cloud["challenge"] = challenge + hosted.connect(PAIRING, host=HOST, code_verifier=verifier) + assert cloud["claims"][-1]["code_verifier"] == verifier + with pytest.raises(hosted.HostedError, match="proof is malformed"): + hosted.connect(PAIRING, host=HOST, code_verifier="short") + + +def _login_args(**overrides): + values = dict( + token=None, + host=HOST, + destination_kind=None, + trusted_host=None, + no_save=False, + allow_plaintext_token=False, + browser=None, + open=False, + timeout=None, + ) + values.update(overrides) + return argparse.Namespace(**values) + + +def test_login_picks_the_browser_only_without_a_token(monkeypatch, _isolated): + assert bl.uses_browser(_login_args()) is True + assert bl.uses_browser(_login_args(token=TOKEN)) is False + assert bl.uses_browser(_login_args(browser=False)) is False + monkeypatch.setenv(hosted.TOKEN_ENV, TOKEN) + assert bl.uses_browser(_login_args()) is False + assert bl.uses_browser(_login_args(browser=True)) is True + monkeypatch.delenv(hosted.TOKEN_ENV) + _isolated["canonical"] = TOKEN + # A stored token is re-validated, as before this change. + assert bl.uses_browser(_login_args()) is False + + +def test_login_command_prints_the_link_and_never_the_secret(cloud, monkeypatch, capsys): + def fake_login(host, *, show_url, open_browser, timeout, **kwargs): + assert open_browser is None and timeout == bl.DEFAULT_TIMEOUT_S + show_url(f"{HOST}/login?state=x") + return {"host": HOST, "device_name": "laptop", "settings_url": f"{HOST}/s"} + + monkeypatch.setattr(bl, "browser_login", fake_login) + assert cli._cmd_login(_login_args()) == 0 + out = capsys.readouterr().out + assert f"{HOST}/login?state=x" in out + assert "Add --open" in out + assert "Signed in to" in out and TOKEN not in out + + +def test_login_command_reports_a_failure_in_one_line(monkeypatch, capsys): + def fail(host, **kwargs): + raise bl.BrowserLoginError("Sign-in was not approved: Not approved") + + monkeypatch.setattr(bl, "browser_login", fail) + assert cli._cmd_login(_login_args()) == 1 + assert capsys.readouterr().out.strip() == ( + "login failed: Sign-in was not approved: Not approved" + )