You can close this tab and go back to the terminal.
" + b"" +) +_FAILED_HTML = ( + b"" + b"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" + )