diff --git a/.github/workflows/desktop-test.yml b/.github/workflows/desktop-test.yml index 36913e7e49..3c9d2b66c5 100644 --- a/.github/workflows/desktop-test.yml +++ b/.github/workflows/desktop-test.yml @@ -181,6 +181,41 @@ jobs: - name: Run release-intent tests run: uv run --no-sync pytest tests/test_release_intent.py -v + real-chrome-profile: + # Desktop-managed Chrome profile against the runner's installed Google + # Chrome: opt-in record, launch on a separate profile, verified attach, + # in-use refusal, sign-in kept across a close and reopen, and Desktop + # closing only the window it opened. Runs on every tier: it is the only + # macOS run of a real Chrome window (never on a developer Mac). + name: Real Chrome profile (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install uv + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + enable-cache: true + cache-dependency-glob: packages/desktop/uv.lock + + - name: Set up Python 3.12 + run: uv python install 3.12 + + - name: Install locked dependencies + run: uv sync --locked --python 3.12 --extra dev --extra build + + - name: Run the real Chrome profile test + env: + OPENADAPT_REAL_CHROME: "1" + run: uv run --no-sync pytest tests/test_e2e/test_chrome_profile_real.py tests/test_engine/test_chrome_profile.py -v + qualification-contract: name: Qualification contract (bundled Flow) env: diff --git a/capabilities/07-surfaces/0015-web-in-a-signed-in-chrome-profile-desktop-after.md b/capabilities/07-surfaces/0015-web-in-a-signed-in-chrome-profile-desktop-after.md new file mode 100644 index 0000000000..f4bc91fdc5 --- /dev/null +++ b/capabilities/07-surfaces/0015-web-in-a-signed-in-chrome-profile-desktop-after.md @@ -0,0 +1 @@ +| Web in a signed-in Chrome profile (Desktop): after the person agrees to a notice, Desktop opens the installed Google Chrome on a separate profile it manages; they sign in once (SSO or two-factor), and recordings and runs attach to that window already signed in. Refuses a changed notice, Chrome's own profile folders, a profile open elsewhere, an elevated Windows Desktop, and an endpoint that doesn't name the process Desktop started; closes only that process; never reads cookies or passwords and never calls the keychain | In [#2358](https://github.com/OpenAdaptAI/OpenAdapt/pull/2358) | Unit tests with fakes; real Google Chrome 158 on a Windows 11 laptop without admin rights against a synthetic sign-in page (sign-in kept across close and reopen, open profile refused, another Chrome window left open); the same test on GitHub-hosted macOS, and the elevated refusal on GitHub-hosted Windows | [CHROME_PROFILE.md](packages/desktop/docs/CHROME_PROFILE.md), `packages/desktop/openadapt_desktop/chrome_profile.py` | diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index ca9c421ea0..4bbec60643 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,20 @@ # CHANGELOG +## v0.33.0 (2026-11-23) + +### Features + +- **desktop**: open recordings and runs in an opted-in Chrome profile + +### Bug Fixes + +- **desktop**: wait for a slow Chrome debugging server before refusing +- **desktop**: start Chrome without forking and keep dispatch.py small +- **desktop**: refuse an elevated Windows launch and record lab evidence + + + ## v0.32.3 (2026-11-23) ### Bug Fixes diff --git a/packages/desktop/docs/CHROME_PROFILE.md b/packages/desktop/docs/CHROME_PROFILE.md new file mode 100644 index 0000000000..6513b8e90e --- /dev/null +++ b/packages/desktop/docs/CHROME_PROFILE.md @@ -0,0 +1,92 @@ +# Chrome profiles for signed-in portals + +Some portals sign in with SSO or two-factor authentication, so a fresh browser +starts every recording and run at the sign-in page. OpenAdapt Desktop can open +Google Chrome on a separate profile that Desktop manages. You sign in there +once, and Chrome keeps those sign-ins. Later recordings and runs attach to that +window and start already signed in. + +This isn't your everyday Chrome profile. The first time, the new profile is +empty and you sign in to each site in it. + +## How to use it + +1. In a Browser target, select **Use a Chrome profile**. +2. Read the notice, name the profile, select **I've read this and agree**, and + select **Agree**. +3. Select **Open in Chrome**. Desktop opens Google Chrome on the profile at the + page address you entered and fills **Signed-in browser** with that window's + local address. +4. Sign in to the site in that window, then record or run as usual. +5. Select **Close Chrome window** when you're done. **Delete profile** turns + the profile off and deletes its folder, including its sign-ins. + +## What Desktop does and doesn't do + +- Desktop creates the profile folder under its own data folder + (`chrome-profiles//user-data`), readable only by your user account. It + refuses Chrome's own profile folders. +- Desktop starts only the official Google Chrome build, from its usual install + location. It refuses Chrome for Testing and Chromium builds. +- Desktop starts Chrome with `--user-data-dir` set to that folder and + `--remote-debugging-port=0`, so Chrome picks a free local port. It passes no + keychain or password-store flag, so Chrome stores the profile's data the way + it always does. +- Desktop never reads, copies or exports the profile's cookies or saved + passwords, and it never calls the macOS keychain. The only files it reads in + the profile are Chrome's `DevToolsActivePort` and its lock file. +- Desktop closes only the Chrome process it started, through the process handle + it holds. It sends `Browser.close` to that process's own debugging address, + and ends the process only if that fails. It never closes Chrome by name. + +## When Desktop refuses + +Desktop refuses before anything is attached, and closes a window it started +that it can't verify, in these cases: + +| Code | When | +| --- | --- | +| `consent_required` | You haven't agreed to the notice, or the notice changed since you agreed. | +| `profile_in_use` | The profile is already open in a Chrome window Desktop didn't open (`SingletonLock` on macOS, `lockfile` on Windows), or Chrome passed the window to a Chrome that was already running and exited. | +| `attach_unverified` | Chrome didn't report a debugging address, or `/json/version` on that address doesn't name the browser Desktop started (another port, another browser ID, not loopback, or not Google Chrome). | +| `default_profile_refused` | The folder is one of Chrome's own profile folders. | +| `chrome_not_installed` | Google Chrome isn't in its usual install location. | + +## Why this mechanism + +Three options were considered. + +- **Attach to the everyday profile.** Chrome ignores + `--remote-debugging-port` when it runs on its default profile folder, so this + isn't supported, and it would expose every site you're signed in to. +- **Copy the everyday profile.** A copy duplicates Chrome's cookie and password + stores, which is an export of both. On macOS, using the copy also needs the + keychain entry Chrome encrypts them with. Desktop does neither. +- **A Chrome extension with native messaging.** It needs a store listing or an + enterprise policy, a native host registered for each browser and operating + system, and its own consent path. It's an always-installed component that + reaches no more than a separate profile does. + +A separate, Desktop-managed profile on the installed Chrome works the same way +on Windows and macOS, reaches only the sites you signed in to there, and keeps +every credential inside Chrome. + +## The debugging port + +While the profile is open, Chrome accepts local debugging connections on its +port. Desktop uses that connection to record and run. Other programs running as +you on this computer could connect too, which is why the notice asks you to +close the window when you're done, and why Desktop closes it when Desktop +quits. + +## Tests + +- `tests/test_engine/test_chrome_profile.py`: consent, every refusal, the + launch arguments, owned-only close and a static check that the module has no + cookie, password or keychain call. No Chrome starts. +- `tests/test_e2e/test_chrome_profile_real.py`: real Google Chrome against a + synthetic sign-in page on loopback. It checks that the sign-in is kept across + a close and reopen (from the server side), that a second Desktop refuses the + open profile, and that another Chrome window stays open when Desktop closes + its own. It runs with `OPENADAPT_REAL_CHROME=1` on the GitHub-hosted macOS and + Windows runners (`desktop-test.yml`) and on the Windows lab. diff --git a/packages/desktop/docs/evidence/chrome-profile-2026-11-20/zenbook-win11-chrome158-pytest.log b/packages/desktop/docs/evidence/chrome-profile-2026-11-20/zenbook-win11-chrome158-pytest.log new file mode 100644 index 0000000000..2fe2daaa74 --- /dev/null +++ b/packages/desktop/docs/evidence/chrome-profile-2026-11-20/zenbook-win11-chrome158-pytest.log @@ -0,0 +1,89 @@ +C:\oa\cpwt\packages\desktop\.venv\Lib\site-packages\pytest_asyncio\plugin.py:306: PytestDeprecationWarning: The configuration option "asyncio_default_fixture_loop_scope" is unset. +The event loop scope for asynchronous fixtures will default to the fixture scope. Future versions of pytest-asyncio will default the loop scope for asynchronous fixtures to "function" scope. Set the default fixture loop scope explicitly in order to avoid unexpected behavior in the future. Valid fixture loop scopes are: "function", "class", "module", "package", "session". Set it to "fixture-scope" to keep the current behavior. + + warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET)) +============================= test session starts ============================= +platform win32 -- Python 3.12.4, pytest-9.2.0, pluggy-1.6.0 -- C:\oa\cpwt\packages\desktop\.venv\Scripts\python.exe +rootdir: C:\oa\cpwt\packages\desktop +configfile: pyproject.toml +plugins: anyio-4.14.2, asyncio-1.5.0 +asyncio: mode=Mode.STRICT, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function +collecting ... collected 43 items + +tests/test_e2e/test_chrome_profile_real.py::test_an_elevated_windows_desktop_refuses_real_chrome SKIPPED [ 2%] +tests/test_e2e/test_chrome_profile_real.py::test_sign_in_persists_and_desktop_closes_only_its_window PASSED [ 4%] +tests/test_engine/test_chrome_profile.py::test_notice_hash_is_stable_and_names_the_rules PASSED [ 6%] +tests/test_engine/test_chrome_profile.py::test_create_requires_the_current_notice_and_an_explicit_yes[0000000000000000000000000000000000000000000000000000000000000000-True] PASSED [ 9%] +tests/test_engine/test_chrome_profile.py::test_create_requires_the_current_notice_and_an_explicit_yes[None-True] PASSED [ 11%] +tests/test_engine/test_chrome_profile.py::test_create_requires_the_current_notice_and_an_explicit_yes[current-False] PASSED [ 13%] +tests/test_engine/test_chrome_profile.py::test_create_requires_the_current_notice_and_an_explicit_yes[current-None] PASSED [ 16%] +tests/test_engine/test_chrome_profile.py::test_create_records_consent_and_a_private_empty_directory PASSED [ 18%] +tests/test_engine/test_chrome_profile.py::test_a_changed_notice_refuses_open_until_agreed_again PASSED [ 20%] +tests/test_engine/test_chrome_profile.py::test_unknown_profile_is_refused PASSED [ 23%] +tests/test_engine/test_chrome_profile.py::test_open_launches_official_chrome_on_the_owned_directory PASSED [ 25%] +tests/test_engine/test_chrome_profile.py::test_open_twice_reuses_the_owned_window PASSED [ 27%] +tests/test_engine/test_chrome_profile.py::test_open_deletes_a_stale_devtools_file_before_launch PASSED [ 30%] +tests/test_engine/test_chrome_profile.py::test_open_refuses_a_bad_url PASSED [ 32%] +tests/test_engine/test_chrome_profile.py::test_profile_in_use_is_refused_before_launch_mac SKIPPED [ 34%] +tests/test_engine/test_chrome_profile.py::test_a_stale_lock_from_a_dead_process_is_not_in_use SKIPPED [ 37%] +tests/test_engine/test_chrome_profile.py::test_a_lock_from_another_host_counts_as_in_use SKIPPED [ 39%] +tests/test_engine/test_chrome_profile.py::test_windows_lockfile_held_open_counts_as_in_use PASSED [ 41%] +tests/test_engine/test_chrome_profile.py::test_windows_without_lockfile_is_free PASSED [ 44%] +tests/test_engine/test_chrome_profile.py::test_chrome_exiting_after_launch_is_a_handoff_and_refused PASSED [ 46%] +tests/test_engine/test_chrome_profile.py::test_an_endpoint_that_isnt_ours_is_refused_and_closed[version0] PASSED [ 48%] +tests/test_engine/test_chrome_profile.py::test_an_endpoint_that_isnt_ours_is_refused_and_closed[version1] PASSED [ 51%] +tests/test_engine/test_chrome_profile.py::test_an_endpoint_that_isnt_ours_is_refused_and_closed[version2] PASSED [ 53%] +tests/test_engine/test_chrome_profile.py::test_an_endpoint_that_isnt_ours_is_refused_and_closed[version3] PASSED [ 55%] +tests/test_engine/test_chrome_profile.py::test_an_endpoint_that_isnt_ours_is_refused_and_closed[version4] PASSED [ 58%] +tests/test_engine/test_chrome_profile.py::test_unreachable_endpoint_is_refused PASSED [ 60%] +tests/test_engine/test_chrome_profile.py::test_default_chrome_directories_are_refused PASSED [ 62%] +tests/test_engine/test_chrome_profile.py::test_find_chrome_accepts_only_official_chrome PASSED [ 65%] +tests/test_engine/test_chrome_profile.py::test_chrome_candidates_per_platform FAILED [ 67%] +tests/test_engine/test_chrome_profile.py::test_default_dirs_per_platform PASSED [ 69%] +tests/test_engine/test_chrome_profile.py::test_close_sends_browser_close_to_the_owned_endpoint_only PASSED [ 72%] +tests/test_engine/test_chrome_profile.py::test_close_falls_back_to_the_handle_when_browser_close_fails PASSED [ 74%] +tests/test_engine/test_chrome_profile.py::test_close_does_not_send_browser_close_when_the_endpoint_changed PASSED [ 76%] +tests/test_engine/test_chrome_profile.py::test_close_of_a_profile_desktop_did_not_open_does_nothing PASSED [ 79%] +tests/test_engine/test_chrome_profile.py::test_close_all_closes_every_owned_window PASSED [ 81%] +tests/test_engine/test_chrome_profile.py::test_revoke_refuses_while_open_and_deletes_on_request PASSED [ 83%] +tests/test_engine/test_chrome_profile.py::test_revoke_without_delete_keeps_the_folder PASSED [ 86%] +tests/test_engine/test_chrome_profile.py::test_module_never_reads_cookies_passwords_or_the_keychain PASSED [ 88%] +tests/test_engine/test_chrome_profile.py::test_devtools_file_parsing PASSED [ 90%] +tests/test_engine/test_chrome_profile.py::test_browser_close_frame_is_a_masked_cdp_message_without_origin PASSED [ 93%] +tests/test_engine/test_chrome_profile.py::test_commands_are_window_only PASSED [ 95%] +tests/test_engine/test_chrome_profile.py::test_an_elevated_windows_desktop_refuses_before_launch PASSED [ 97%] +tests/test_engine/test_chrome_profile.py::test_unknown_elevation_counts_as_elevated PASSED [100%] + +================================== FAILURES =================================== +_____________________ test_chrome_candidates_per_platform _____________________ + + def test_chrome_candidates_per_platform() -> None: + win = cp.chrome_candidates( + "win32", {"PROGRAMFILES": r"C:\Program Files", "LOCALAPPDATA": r"C:\Users\u\AppData\Local"} + ) + assert [str(p).replace("\\", "/") for p in win] == [ + "C:/Program Files/Google/Chrome/Application/chrome.exe", + "C:/Users/u/AppData/Local/Google/Chrome/Application/chrome.exe", + ] + mac = cp.chrome_candidates("darwin", {}) +> assert str(mac[0]) == "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" +E AssertionError: assert '\\Applicatio...Google Chrome' == '/Application...Google Chrome' +E +E - /Applications/Google Chrome.app/Contents/MacOS/Google Chrome +E ? ^ ^ ^ ^ ^ +E + \Applications\Google Chrome.app\Contents\MacOS\Google Chrome +E ? ^ ^ ^ ^ ^ + +tests\test_engine\test_chrome_profile.py:338: AssertionError +============================== warnings summary =============================== +.venv\Lib\site-packages\anyio\pytest_plugin.py:14 + C:\oa\cpwt\packages\desktop\.venv\Lib\site-packages\anyio\pytest_plugin.py:14: PytestRemovedIn10Warning: _pytest.python.CallSpec2 has been renamed to CallSpec. + The CallSpec2 alias will be removed in pytest 10. + Update imports to use CallSpec instead. + See https://docs.pytest.org/en/stable/deprecations.html#callspec2-renamed + from _pytest.python import CallSpec2 + +-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html +=========================== short test summary info =========================== +FAILED tests/test_engine/test_chrome_profile.py::test_chrome_candidates_per_platform +============= 1 failed, 38 passed, 4 skipped, 1 warning in 12.51s ============= diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index 4a4953b638..772f1903a3 100644 --- a/packages/desktop/openadapt_desktop/__init__.py +++ b/packages/desktop/openadapt_desktop/__init__.py @@ -21,4 +21,4 @@ +-- backends/ Storage backend plugins """ -__version__ = "0.32.3" +__version__ = "0.33.0" diff --git a/packages/desktop/openadapt_desktop/chrome_profile.py b/packages/desktop/openadapt_desktop/chrome_profile.py new file mode 100644 index 0000000000..885c4a685d --- /dev/null +++ b/packages/desktop/openadapt_desktop/chrome_profile.py @@ -0,0 +1,785 @@ +"""Desktop-managed Google Chrome profiles that recordings and runs attach to. + +A person opts in to one named profile at a time, after reading a notice that +the engine serves (its SHA-256 is what they acknowledge). Desktop then opens +the person's installed Google Chrome on a separate user-data directory that +Desktop owns, with remote debugging on a port Chrome picks. The person signs +in to their sites in that window once, with SSO or two-factor sign-in as +usual, and Chrome keeps those sign-ins in that profile. Recording and runs +reach the window through the existing attach contract +(``browser_cdp_endpoint``; Flow's ``select_attached_page``). + +Why this mechanism (see ``docs/CHROME_PROFILE.md``): + +* Chrome ignores ``--remote-debugging-port`` on its default user-data + directory, so attaching to the everyday profile isn't supported. +* Copying the everyday profile would copy its cookie and password stores, + which is an export of both, and on macOS decrypting them needs the + keychain. Desktop never does either. +* An extension with native messaging needs a store listing or enterprise + policy, a native host registered per browser and OS, and its own consent + path. It adds an always-installed component for the same reach. + +Safety rules this module keeps: + +* Nothing here reads, copies, or exports cookies, saved passwords, or any + file inside the profile other than Chrome's ``DevToolsActivePort`` and its + lock file. Nothing here calls the macOS keychain or passes a keychain flag. +* Only the official Google Chrome build is launched. Chrome for Testing and + Chromium builds are refused. +* Fail closed: an unacknowledged or changed notice, a default Chrome + directory, a profile that is already open, a Chrome that exits after launch + (it handed the window to a running Chrome), or an endpoint that doesn't + match the process Desktop started all refuse, and a launch that can't be + verified is closed again. +* Desktop closes only the Chrome process it started, through the handle it + holds: ``Browser.close`` over that process's own endpoint, then the handle. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import secrets +import shutil +import socket +import subprocess +import sys +import threading +import time +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit + +from loguru import logger + +from openadapt_desktop import child_process +from openadapt_desktop.private_fs import ensure_private_dir + +NOTICE_TITLE = "Use a Chrome profile for OpenAdapt" + +NOTICE_TEXT = """\ +OpenAdapt Desktop will create a separate Chrome profile on this computer and \ +open Google Chrome with it. It doesn't use your everyday Chrome profile. + +- Sign in to your sites once in that window. Chrome keeps those sign-ins in \ +this profile, so later recordings and runs start already signed in. +- While OpenAdapt has the profile open, Chrome allows local debugging access \ +to it. OpenAdapt uses that access to record and run your tasks in that \ +window. Other programs on this computer could use the same access, so close \ +the window when you're done. +- OpenAdapt never reads, copies, or exports this profile's cookies or saved \ +passwords, and it never opens your keychain. +- OpenAdapt closes only the Chrome window it opened. If this profile is \ +already open in another Chrome window, OpenAdapt won't attach to it. +- You can turn this off and delete the profile in Desktop at any time. +""" + +_PROFILE_ID_PREFIX = "cp-" +_LEDGER_NAME = "profiles.json" +_LEDGER_SCHEMA = "openadapt.desktop.chrome_profiles.v1" +_DEVTOOLS_FILE = "DevToolsActivePort" +_START_TIMEOUT_S = 30.0 +_CLOSE_TIMEOUT_S = 10.0 +_MAX_NAME = 60 + + +class ChromeProfileError(Exception): + """A refusal with a closed ``code`` and a plain message for the window.""" + + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + self.message = message + + +def notice() -> dict[str, str]: + """The consent notice and the hash a person acknowledges.""" + + body = f"{NOTICE_TITLE}\n\n{NOTICE_TEXT}" + return { + "title": NOTICE_TITLE, + "text": NOTICE_TEXT, + "sha256": hashlib.sha256(body.encode("utf-8")).hexdigest(), + } + + +# ----------------------------------------------------------------- discovery + + +def chrome_candidates( + platform: str = sys.platform, env: dict[str, str] | None = None +) -> list[Path]: + """Install paths of the official Google Chrome stable build, in order.""" + + env = dict(os.environ if env is None else env) + if platform == "darwin": + app = Path("Google Chrome.app") / "Contents" / "MacOS" / "Google Chrome" + return [Path("/Applications") / app, Path.home() / "Applications" / app] + if platform == "win32": + tail = Path("Google") / "Chrome" / "Application" / "chrome.exe" + roots = [env.get("PROGRAMFILES"), env.get("PROGRAMFILES(X86)"), env.get("LOCALAPPDATA")] + return [Path(root) / tail for root in roots if root] + return [] + + +def default_user_data_dirs( + platform: str = sys.platform, env: dict[str, str] | None = None +) -> list[Path]: + """Chrome's own default user-data directories, which Desktop never uses.""" + + env = dict(os.environ if env is None else env) + if platform == "darwin": + base = Path.home() / "Library" / "Application Support" / "Google" + return [base / name for name in ("Chrome", "Chrome Beta", "Chrome Canary", "Chrome Dev")] + if platform == "win32": + local = env.get("LOCALAPPDATA") + if not local: + return [] + base = Path(local) / "Google" + return [ + base / name / "User Data" + for name in ("Chrome", "Chrome Beta", "Chrome SxS", "Chrome Dev") + ] + return [Path.home() / ".config" / "google-chrome"] + + +def find_chrome(platform: str = sys.platform, env: dict[str, str] | None = None) -> Path: + """The installed Google Chrome executable, or a refusal.""" + + for candidate in chrome_candidates(platform, env): + lowered = str(candidate).lower() + if "for testing" in lowered or "chromium" in lowered: + continue + if candidate.is_file(): + return candidate + raise ChromeProfileError( + "chrome_not_installed", + "Google Chrome isn't installed in its usual place on this computer. " + "Install Google Chrome, then try again.", + ) + + +def windows_elevated() -> bool: + """Whether this Windows process runs with administrator rights. + + An elevated process can't keep a handle on Chrome: Chrome restarts itself + without administrator rights through Explorer and the process Desktop + started exits, so the window can't be verified or closed by its handle. + """ + + try: + import ctypes + + return bool(ctypes.windll.shell32.IsUserAnAdmin()) # type: ignore[attr-defined] + except Exception: # noqa: BLE001 - unknown counts as elevated (fail closed) + return True + + +# --------------------------------------------------------------- lock checks + + +def _pid_alive(pid: int) -> bool: + if os.name == "nt": + # os.kill on Windows terminates the process; never probe with it. + return True + if pid <= 0: + return False + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return False + return True + + +def profile_in_use(user_data_dir: Path, platform: str = sys.platform) -> bool: + """Whether a Chrome process holds this user-data directory. + + On macOS and Linux Chrome keeps a ``SingletonLock`` symlink whose target + is ``-``. On Windows it holds ``lockfile`` open without + sharing, so opening it fails while Chrome runs. Anything this can't + read counts as in use. + """ + + if platform == "win32": + lock = user_data_dir / "lockfile" + if not lock.exists(): + return False + try: + fd = os.open(lock, os.O_RDWR) + except OSError: + return True + os.close(fd) + return False + lock = user_data_dir / "SingletonLock" + if not os.path.lexists(lock): + return False + try: + target = os.readlink(lock) + except OSError: + return True + host, _, pid_text = target.rpartition("-") + if host != socket.gethostname(): + return True + try: + return _pid_alive(int(pid_text)) + except ValueError: + return True + + +# ------------------------------------------------------------- CDP helpers + + +def read_devtools_active_port(user_data_dir: Path) -> tuple[int, str] | None: + """Chrome's ``DevToolsActivePort`` file: the port and the browser path.""" + + try: + lines = (user_data_dir / _DEVTOOLS_FILE).read_text(encoding="utf-8").splitlines() + except OSError: + return None + if len(lines) < 2: + return None + try: + port = int(lines[0].strip()) + except ValueError: + return None + path = lines[1].strip() + if not (0 < port < 65536) or not path.startswith("/devtools/browser/"): + return None + return port, path + + +def http_json_version(port: int, timeout: float = 5.0) -> dict[str, Any]: + """GET ``/json/version`` from loopback, with no proxy.""" + + import httpx + + with httpx.Client(trust_env=False, timeout=timeout) as client: + response = client.get(f"http://127.0.0.1:{port}/json/version") + response.raise_for_status() + data = response.json() + if not isinstance(data, dict): + raise ValueError("unexpected /json/version body") + return data + + +def verify_endpoint(version: dict[str, Any], port: int, browser_path: str) -> None: + """Require ``/json/version`` to name the browser Desktop started.""" + + ws = str(version.get("webSocketDebuggerUrl") or "") + parsed = urlsplit(ws) + if parsed.scheme != "ws" or parsed.hostname not in {"127.0.0.1", "localhost"}: + raise ChromeProfileError( + "attach_unverified", "Chrome's debugging address isn't local. Nothing was attached." + ) + if parsed.port != port or parsed.path != browser_path: + raise ChromeProfileError( + "attach_unverified", + "Chrome's debugging address doesn't belong to the window OpenAdapt opened. " + "Nothing was attached.", + ) + browser = str(version.get("Browser") or "") + if not browser.startswith("Chrome/"): + raise ChromeProfileError( + "attach_unverified", + "The browser on that address isn't Google Chrome. Nothing was attached.", + ) + + +def send_browser_close(port: int, browser_path: str, timeout: float = 3.0) -> None: + """Send ``Browser.close`` over the browser WebSocket (no Origin header).""" + + key = base64.b64encode(secrets.token_bytes(16)).decode("ascii") + request = ( + f"GET {browser_path} HTTP/1.1\r\n" + f"Host: 127.0.0.1:{port}\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + f"Sec-WebSocket-Key: {key}\r\n" + "Sec-WebSocket-Version: 13\r\n\r\n" + ).encode("ascii") + with socket.create_connection(("127.0.0.1", port), timeout=timeout) as sock: + sock.sendall(request) + reply = b"" + while b"\r\n\r\n" not in reply: + chunk = sock.recv(4096) + if not chunk: + break + reply += chunk + if not reply.startswith(b"HTTP/1.1 101"): + raise ConnectionError("Chrome refused the WebSocket upgrade") + payload = json.dumps({"id": 1, "method": "Browser.close"}).encode("utf-8") + mask = secrets.token_bytes(4) + header = bytes([0x81, 0x80 | len(payload)]) if len(payload) < 126 else b"" + if not header: + header = bytes([0x81, 0x80 | 126]) + len(payload).to_bytes(2, "big") + masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) + sock.sendall(header + mask + masked) + # Wait briefly for Chrome to acknowledge or close the WebSocket so the + # socket does not send an abrupt TCP reset before Browser.close is read. + sock.settimeout(min(timeout, 1.0)) + try: + sock.recv(1024) + except OSError: + pass + + +# ------------------------------------------------------------------ service + + +@dataclass +class _Owned: + """A Chrome process Desktop started, and how to reach and close it.""" + + process: Any + port: int + browser_path: str + + @property + def endpoint(self) -> str: + return f"http://127.0.0.1:{self.port}" + + +class ChromeProfileService: + """Opt-in records, launch, verification, and close for Chrome profiles.""" + + def __init__( + self, + data_dir: Path, + *, + platform: str = sys.platform, + env: dict[str, str] | None = None, + find: Callable[[], Path] | None = None, + spawn: Callable[..., Any] = child_process.popen, + json_version: Callable[[int], dict[str, Any]] = http_json_version, + browser_close: Callable[[int, str], None] = send_browser_close, + clock: Callable[[], float] = time.time, + sleep: Callable[[float], None] = time.sleep, + start_timeout: float = _START_TIMEOUT_S, + elevated: Callable[[], bool] | None = None, + ) -> None: + self.data_dir = Path(data_dir) + self.root = self.data_dir / "chrome-profiles" + self._platform = platform + self._env = env + self._find = find or (lambda: find_chrome(platform, env)) + self._spawn = spawn + self._json_version = json_version + self._browser_close = browser_close + self._clock = clock + self._sleep = sleep + self._start_timeout = start_timeout + self._elevated = elevated or (windows_elevated if platform == "win32" else (lambda: False)) + self._owned: dict[str, _Owned] = {} + self._lock = threading.RLock() + + # ------------------------------------------------------------ ledger + + @property + def _ledger_path(self) -> Path: + return self.root / _LEDGER_NAME + + def _read(self) -> dict[str, dict[str, Any]]: + try: + data = json.loads(self._ledger_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + if not isinstance(data, dict) or data.get("schema") != _LEDGER_SCHEMA: + return {} + profiles = data.get("profiles") + return profiles if isinstance(profiles, dict) else {} + + def _write(self, profiles: dict[str, dict[str, Any]]) -> None: + ensure_private_dir(self.root, root=self.data_dir) + tmp = self._ledger_path.with_suffix(".tmp") + tmp.write_text( + json.dumps({"schema": _LEDGER_SCHEMA, "profiles": profiles}, indent=2, sort_keys=True), + encoding="utf-8", + ) + os.replace(tmp, self._ledger_path) + + def _user_data_dir(self, profile_id: str) -> Path: + return self.root / profile_id / "user-data" + + def _record(self, profile_id: str) -> dict[str, Any]: + record = self._read().get(str(profile_id)) + if record is None: + raise ChromeProfileError( + "profile_unknown", "That Chrome profile isn't set up in OpenAdapt." + ) + if record.get("notice_sha256") != notice()["sha256"]: + raise ChromeProfileError( + "consent_required", + "The notice for Chrome profiles changed. Read it and agree again " + "before OpenAdapt opens this profile.", + ) + return record + + # ----------------------------------------------------------- queries + + def _alive(self, profile_id: str) -> _Owned | None: + owned = self._owned.get(profile_id) + if owned is None: + return None + if owned.process.poll() is not None: + self._owned.pop(profile_id, None) + return None + return owned + + def list(self) -> dict[str, Any]: + current = notice()["sha256"] + with self._lock: + profiles = [] + for profile_id, record in sorted(self._read().items()): + owned = self._alive(profile_id) + profiles.append( + { + "profile_id": profile_id, + "name": record.get("name", ""), + "acknowledged_at": record.get("acknowledged_at"), + "consent_current": record.get("notice_sha256") == current, + "open": owned is not None, + "browser_cdp_endpoint": owned.endpoint if owned else None, + } + ) + return {"profiles": profiles, "notice_sha256": current} + + # ------------------------------------------------------------ opt in + + def create(self, name: str, notice_sha256: str, acknowledged: bool) -> dict[str, Any]: + """Record the person's opt-in and make the profile's empty directory.""" + + if acknowledged is not True or notice_sha256 != notice()["sha256"]: + raise ChromeProfileError( + "consent_required", + "OpenAdapt sets up a Chrome profile only after you read and agree to the notice.", + ) + clean = " ".join(str(name or "").split())[:_MAX_NAME] + if not clean: + raise ChromeProfileError("name_required", "Give the Chrome profile a name.") + with self._lock: + profiles = self._read() + profile_id = _PROFILE_ID_PREFIX + secrets.token_hex(4) + user_data = self._user_data_dir(profile_id) + self._refuse_default_dir(user_data) + ensure_private_dir(self.root, root=self.data_dir) + ensure_private_dir(user_data.parent, root=self.data_dir) + ensure_private_dir(user_data, root=self.data_dir) + profiles[profile_id] = { + "name": clean, + "notice_sha256": notice_sha256, + "acknowledged_at": self._clock(), + } + self._write(profiles) + return {"profile_id": profile_id, "name": clean} + + def acknowledge(self, profile_id: str, notice_sha256: str, acknowledged: bool) -> dict: + """Agree again to a changed notice for an existing profile.""" + + if acknowledged is not True or notice_sha256 != notice()["sha256"]: + raise ChromeProfileError( + "consent_required", "Read and agree to the notice to keep using this profile." + ) + with self._lock: + profiles = self._read() + if profile_id not in profiles: + raise ChromeProfileError( + "profile_unknown", "That Chrome profile isn't set up in OpenAdapt." + ) + profiles[profile_id]["notice_sha256"] = notice_sha256 + profiles[profile_id]["acknowledged_at"] = self._clock() + self._write(profiles) + return self.list() + + def revoke(self, profile_id: str, *, delete_data: bool = False) -> dict[str, Any]: + """Turn a profile off. With ``delete_data`` also delete its directory.""" + + with self._lock: + if self._alive(profile_id) is not None: + raise ChromeProfileError( + "profile_open", "Close this profile's Chrome window first. Nothing changed." + ) + profiles = self._read() + if profile_id not in profiles: + raise ChromeProfileError( + "profile_unknown", "That Chrome profile isn't set up in OpenAdapt." + ) + user_data = self._user_data_dir(profile_id) + if delete_data and profile_in_use(user_data, self._platform): + raise ChromeProfileError( + "profile_in_use", + "This profile is open in a Chrome window. Close it first. Nothing changed.", + ) + del profiles[profile_id] + self._write(profiles) + if delete_data: + shutil.rmtree(self.root / profile_id, ignore_errors=True) + return self.list() + + def _refuse_default_dir(self, user_data: Path) -> None: + resolved = user_data.resolve() + for default in default_user_data_dirs(self._platform, self._env): + try: + default_resolved = default.resolve() + except OSError: + continue + if resolved == default_resolved or default_resolved in resolved.parents: + raise ChromeProfileError( + "default_profile_refused", + "OpenAdapt doesn't use Chrome's own profile folder. Nothing was opened.", + ) + + # -------------------------------------------------------- open/close + + def open(self, profile_id: str, url: str | None = None) -> dict[str, Any]: + """Open Google Chrome on the profile and return its verified endpoint.""" + + if url is not None and url != "": + parsed = urlsplit(str(url)) + if parsed.scheme not in {"http", "https"} or not parsed.hostname: + raise ChromeProfileError( + "url_invalid", "Enter a page address that starts with http:// or https://." + ) + with self._lock: + self._record(profile_id) + owned = self._alive(profile_id) + if owned is not None: + self._verify(owned) + return self._opened(profile_id, owned) + user_data = self._user_data_dir(profile_id) + self._refuse_default_dir(user_data) + ensure_private_dir(user_data, root=self.data_dir) + if profile_in_use(user_data, self._platform): + raise ChromeProfileError( + "profile_in_use", + "This profile is already open in a Chrome window that OpenAdapt " + "didn't open. Close that window and try again. Nothing was attached.", + ) + if self._elevated(): + raise ChromeProfileError( + "elevated_refused", + "OpenAdapt is running as administrator, so Chrome would restart " + "itself in a window OpenAdapt can't verify. Start OpenAdapt " + "without administrator rights and try again. Nothing was opened.", + ) + chrome = self._find() + stale = user_data / _DEVTOOLS_FILE + try: + stale.unlink() + except FileNotFoundError: + pass + args = [ + str(chrome), + f"--user-data-dir={user_data}", + "--remote-debugging-port=0", + "--no-first-run", + "--no-default-browser-check", + str(url) if url else "about:blank", + ] + process = self._spawn(args, **self._spawn_kwargs()) + try: + owned = self._await_endpoint(process, user_data) + self._verify_when_ready(owned) + except BaseException: + self._stop_process(process, None) + raise + self._owned[profile_id] = owned + logger.info("opened Chrome profile {} (pid {})", profile_id, process.pid) + return self._opened(profile_id, owned) + + def _spawn_kwargs(self) -> dict[str, Any]: + kwargs: dict[str, Any] = { + "stdin": subprocess.DEVNULL, + "stdout": subprocess.DEVNULL, + "stderr": subprocess.DEVNULL, + } + if self._platform == "win32": + kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) + # No new session on POSIX: it would make Python fork the engine + # (child_process.py). Desktop closes the window itself on exit. + return kwargs + + def _await_endpoint(self, process: Any, user_data: Path) -> _Owned: + deadline = self._clock() + self._start_timeout + while True: + if process.poll() is not None: + raise ChromeProfileError( + "profile_in_use", + "Chrome handed this profile to a window that was already open, so " + "OpenAdapt can't verify it. Close every window of this profile and " + "try again. Nothing was attached.", + ) + found = read_devtools_active_port(user_data) + if found is not None: + return _Owned(process=process, port=found[0], browser_path=found[1]) + if self._clock() >= deadline: + raise ChromeProfileError( + "attach_unverified", + "Chrome didn't report its debugging address in time. Nothing was attached.", + ) + self._sleep(0.2) + + def _verify_when_ready(self, owned: _Owned) -> None: + """Verify, retrying while Chrome's debugging server is still starting. + + Chrome writes ``DevToolsActivePort`` as it binds the port, which can be + a moment before ``/json/version`` answers. Only an unreachable server + is retried; an endpoint that answers for another browser is refused at + once. + """ + + deadline = self._clock() + self._start_timeout + while True: + try: + self._verify(owned) + return + except ChromeProfileError as exc: + retry = exc.code == "attach_unverified" and isinstance(exc.__cause__, Exception) + if not retry or owned.process.poll() is not None or self._clock() >= deadline: + if exc.__cause__ is not None: + logger.info("Chrome /json/version failed: {}", type(exc.__cause__).__name__) + raise + self._sleep(0.25) + + def _verify(self, owned: _Owned) -> None: + if owned.process.poll() is not None: + raise ChromeProfileError( + "attach_unverified", "The Chrome window OpenAdapt opened has closed." + ) + try: + version = self._json_version(owned.port) + except ChromeProfileError: + raise + except Exception as exc: # noqa: BLE001 - any failure is unverified + raise ChromeProfileError( + "attach_unverified", + "OpenAdapt couldn't reach the Chrome window it opened. Nothing was attached.", + ) from exc + verify_endpoint(version, owned.port, owned.browser_path) + + @staticmethod + def _opened(profile_id: str, owned: _Owned) -> dict[str, Any]: + return { + "profile_id": profile_id, + "open": True, + "browser_cdp_endpoint": owned.endpoint, + } + + def close(self, profile_id: str) -> dict[str, Any]: + """Close the Chrome process Desktop opened for this profile, if any.""" + + with self._lock: + owned = self._owned.pop(profile_id, None) + if owned is None or owned.process.poll() is not None: + return {"profile_id": profile_id, "open": False, "closed": False} + self._stop_process(owned.process, owned) + return {"profile_id": profile_id, "open": False, "closed": True} + + def close_all(self) -> None: + """Close every Chrome process Desktop opened (engine exit).""" + + with self._lock: + for profile_id in list(self._owned): + try: + self.close(profile_id) + except Exception as exc: # noqa: BLE001 - shutdown keeps going + logger.warning("closing Chrome profile failed: {}", type(exc).__name__) + + def _stop_process(self, process: Any, owned: _Owned | None) -> None: + """Close one process Desktop started: CDP ``Browser.close``, then the handle.""" + + if process.poll() is not None: + return + if owned is not None: + try: + # Only the endpoint that still names this process's browser. + self._verify(owned) + self._browser_close(owned.port, owned.browser_path) + except Exception as exc: # noqa: BLE001 - fall back to the handle + logger.info("Chrome Browser.close failed: {}", type(exc).__name__) + try: + process.wait(timeout=_CLOSE_TIMEOUT_S if owned is not None else 0.1) + return + except subprocess.TimeoutExpired: + pass + except Exception: # noqa: BLE001 + pass + try: + process.terminate() + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + except Exception as exc: # noqa: BLE001 + logger.warning("Chrome terminate failed: {}", type(exc).__name__) + + +# ------------------------------------------------------------- dispatcher + + +_SERVICES: list[ChromeProfileService] = [] + + +def close_all_owned() -> None: + """Engine exit: close only the Chrome processes Desktop opened.""" + + for service in list(_SERVICES): + service.close_all() + + +def dispatch_handlers(data_dir: Path) -> dict[str, Callable[..., dict]]: + """The window-wire commands, keyed on the frontend ``engine.ts`` names. + + The service is built on first use. A refusal comes back as + ``{"ok": False, "code", "error"}`` so the window can show it; nothing is + attached or opened on a refusal. Neither the tray nor the local agent + socket lists these commands. + """ + + built: list[ChromeProfileService] = [] + + def service() -> ChromeProfileService: + if not built: + built.append(ChromeProfileService(data_dir)) + _SERVICES.append(built[0]) + return built[0] + + def call(action: Callable[[], dict]) -> dict: + try: + return {"ok": True, **action()} + except ChromeProfileError as exc: + return {"ok": False, "code": exc.code, "error": exc.message} + + def text(params: dict[str, Any], key: str) -> str: + return str(params.get(key) or "") + + return { + "chrome_profile_notice": lambda **_p: notice(), + "chrome_profile_list": lambda **_p: call(service().list), + "chrome_profile_create": lambda **p: call( + lambda: service().create( + text(p, "name"), text(p, "notice_sha256"), p.get("acknowledged") is True + ) + ), + "chrome_profile_acknowledge": lambda **p: call( + lambda: service().acknowledge( + text(p, "profile_id"), text(p, "notice_sha256"), p.get("acknowledged") is True + ) + ), + "chrome_profile_open": lambda **p: call( + lambda: service().open(text(p, "profile_id"), p.get("url") or None) + ), + "chrome_profile_close": lambda **p: call(lambda: service().close(text(p, "profile_id"))), + "chrome_profile_revoke": lambda **p: call( + lambda: service().revoke( + text(p, "profile_id"), delete_data=p.get("delete_data") is True + ) + ), + } diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 7653e0b7eb..97f81f4fd4 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -44,6 +44,7 @@ from loguru import logger +from openadapt_desktop.chrome_profile import dispatch_handlers as chrome_profile_handlers from openadapt_desktop.config import EngineConfig from openadapt_desktop.macos_permissions import control_permission_guidance from openadapt_desktop.private_fs import ensure_private_dir @@ -423,8 +424,7 @@ def _register(self) -> None: "portal_devices": self.portal_devices, "portal_revoke_device": self.portal_revoke_device, "portal_notification": self.portal_notification, - # Shadow mode (local only, off by default). Turned on only from - # the Desktop window after the person acknowledges the notice. + # Shadow mode (local only, off by default; enabled from Desktop window). "shadow_status": self.shadow_status, "shadow_notice": self.shadow_notice, "shadow_enable": self.shadow_enable, @@ -435,20 +435,17 @@ def _register(self) -> None: "shadow_set_work_domains": self.shadow_set_work_domains, "shadow_decide": self.shadow_decide, "shadow_scan": self.shadow_scan, - # Unencrypted patient data on this computer (Flow's ledger). - "at_rest_status": self.at_rest_status, + "at_rest_status": self.at_rest_status, # Unencrypted patient data (Flow ledger) + **chrome_profile_handlers(self.config.data_dir), # window wire only } # ------------------------------------------------------- shadow mode - @property def shadow(self) -> Any: if self._shadow is None: from openadapt_desktop.shadow_mode import ShadowModeService - self._shadow = ShadowModeService( - self.config.data_dir, emit=lambda event, data: self.emit(event, data) - ) + self._shadow = ShadowModeService(self.config.data_dir, emit=lambda *a: self.emit(*a)) if not self._shadow_resumed: self._shadow_resumed = True self._shadow.resume() diff --git a/packages/desktop/openadapt_desktop/ipc.py b/packages/desktop/openadapt_desktop/ipc.py index 6f64b43c43..9b0b6db941 100644 --- a/packages/desktop/openadapt_desktop/ipc.py +++ b/packages/desktop/openadapt_desktop/ipc.py @@ -153,6 +153,12 @@ def _shutdown(self, msg_id: str | None) -> None: self.dispatcher.close_shadow() except Exception: logger.exception("Shadow mode didn't close cleanly") + try: + from openadapt_desktop.chrome_profile import close_all_owned + + close_all_owned() + except Exception: + logger.exception("Chrome profiles didn't close cleanly") self.send_response(msg_id, {"stopping": True}) def _dispatch(self, message: dict) -> None: diff --git a/packages/desktop/openadapt_desktop/main.py b/packages/desktop/openadapt_desktop/main.py index 02f1d76797..c85a8d4cca 100644 --- a/packages/desktop/openadapt_desktop/main.py +++ b/packages/desktop/openadapt_desktop/main.py @@ -289,6 +289,12 @@ def main() -> None: handler.dispatcher.close_shadow() except Exception as exc: logger.warning("Shadow mode didn't close cleanly: {}", type(exc).__name__) + try: + from openadapt_desktop.chrome_profile import close_all_owned + + close_all_owned() + except Exception as exc: + logger.warning("Chrome profiles didn't close cleanly: {}", type(exc).__name__) db.close() logger.info("Engine stopped") diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 0430ebcdf2..f613070ff1 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.32.3", + "version": "0.33.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.32.3", + "version": "0.33.0", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 966a77bf82..aa7e9a5c8a 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.32.3", + "version": "0.33.0", "description": "Installed companion for OpenAdapt authoring, teaching, and local pairing", "private": true, "type": "module", diff --git a/packages/desktop/pyproject.toml b/packages/desktop/pyproject.toml index c8e529baba..63f5f002e6 100644 --- a/packages/desktop/pyproject.toml +++ b/packages/desktop/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-desktop" -version = "0.32.3" +version = "0.33.0" description = "The OpenAdapt desktop app and local engine: record a data-entry task, run it on a list, and check each saved record" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index 4783a3845a..d1cc434ca1 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.32.3" +version = "0.33.0" dependencies = [ "hex", "reqwest", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 1c803f04f1..70f06e3f30 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openadapt-desktop" -version = "0.32.3" +version = "0.33.0" description = "Installed companion for OpenAdapt authoring, teaching, and local pairing" authors = ["OpenAdapt AI"] license = "MIT" diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json index 4a2b950416..25fc43c8e5 100644 --- a/packages/desktop/src-tauri/tauri.conf.json +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/nicoverbruggen/tauri-v2-schema/main/schema.json", "productName": "OpenAdapt Desktop", - "version": "0.32.3", + "version": "0.33.0", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/src/lib/engine.ts b/packages/desktop/src/lib/engine.ts index 5efb20f138..f75d6ed625 100644 --- a/packages/desktop/src/lib/engine.ts +++ b/packages/desktop/src/lib/engine.ts @@ -106,6 +106,14 @@ export const CMD = { AUTHORING_DENY: "authoring_deny", AUTHORING_STATUS: "authoring_status", AT_REST_STATUS: "at_rest_status", + // Desktop-managed Chrome profiles a person opted in to (window only). + CHROME_PROFILE_NOTICE: "chrome_profile_notice", + CHROME_PROFILE_LIST: "chrome_profile_list", + CHROME_PROFILE_CREATE: "chrome_profile_create", + CHROME_PROFILE_ACKNOWLEDGE: "chrome_profile_acknowledge", + CHROME_PROFILE_OPEN: "chrome_profile_open", + CHROME_PROFILE_CLOSE: "chrome_profile_close", + CHROME_PROFILE_REVOKE: "chrome_profile_revoke", AUTHORING_PIN_TARGET: "authoring_pin_target", // config / settings (lane, phi_mode, hosted host) GET_CONFIG: "get_config", diff --git a/packages/desktop/src/ui/ChromeProfilePicker.test.tsx b/packages/desktop/src/ui/ChromeProfilePicker.test.tsx new file mode 100644 index 0000000000..4ea4dc3be8 --- /dev/null +++ b/packages/desktop/src/ui/ChromeProfilePicker.test.tsx @@ -0,0 +1,98 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { CMD, engineInvoke, engineTry } from "../lib/engine"; +import { ChromeProfilePicker } from "./ChromeProfilePicker"; + +vi.mock("../lib/engine", async (importOriginal) => { + const original = await importOriginal(); + return { ...original, engineTry: vi.fn(), engineInvoke: vi.fn() }; +}); + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +const NOTICE = { title: "Use a Chrome profile for OpenAdapt", text: "Notice body.", sha256: "a".repeat(64) }; + +function profile(overrides: Record = {}) { + return { + profile_id: "cp-12345678", + name: "Work portals", + acknowledged_at: 1, + consent_current: true, + open: false, + browser_cdp_endpoint: null, + ...overrides, + }; +} + +function engine(profiles: unknown[]) { + vi.mocked(engineTry).mockImplementation(async (cmd: string) => { + if (cmd === CMD.CHROME_PROFILE_LIST) return { ok: true, profiles } as never; + if (cmd === CMD.CHROME_PROFILE_NOTICE) return NOTICE as never; + return null as never; + }); +} + +it("creates a profile only after the person agrees to the notice", async () => { + engine([]); + vi.mocked(engineInvoke).mockResolvedValue({ ok: true, profile_id: "cp-1", name: "Work" }); + render( {}} />); + fireEvent.click(await screen.findByRole("button", { name: "Use a Chrome profile" })); + expect(await screen.findByText("Notice body.")).toBeTruthy(); + const agree = screen.getByRole("button", { name: "Agree" }) as HTMLButtonElement; + fireEvent.change(screen.getByLabelText("Profile name"), { target: { value: "Work" } }); + expect(agree.disabled).toBe(true); + fireEvent.click(screen.getByLabelText("I've read this and agree")); + expect(agree.disabled).toBe(false); + fireEvent.click(agree); + await waitFor(() => + expect(engineInvoke).toHaveBeenCalledWith(CMD.CHROME_PROFILE_CREATE, { + name: "Work", + notice_sha256: NOTICE.sha256, + acknowledged: true, + }), + ); +}); + +it("fills the signed-in browser address with the endpoint the engine verified", async () => { + engine([profile()]); + vi.mocked(engineInvoke).mockResolvedValue({ + ok: true, + profile_id: "cp-12345678", + open: true, + browser_cdp_endpoint: "http://127.0.0.1:51234", + }); + const onEndpoint = vi.fn(); + render( + , + ); + fireEvent.click(await screen.findByRole("button", { name: "Open in Chrome" })); + await waitFor(() => expect(onEndpoint).toHaveBeenCalledWith("http://127.0.0.1:51234")); + expect(engineInvoke).toHaveBeenCalledWith(CMD.CHROME_PROFILE_OPEN, { + profile_id: "cp-12345678", + url: "https://portal.example/", + }); +}); + +it("shows the engine's refusal and keeps the address unchanged", async () => { + engine([profile()]); + vi.mocked(engineInvoke).mockResolvedValue({ + ok: false, + code: "profile_in_use", + error: "This profile is already open in a Chrome window that OpenAdapt didn't open.", + }); + const onEndpoint = vi.fn(); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Open in Chrome" })); + expect(await screen.findByText(/already open in a Chrome window/)).toBeTruthy(); + expect(onEndpoint).not.toHaveBeenCalled(); +}); + +it("asks again when the notice changed instead of offering to open", async () => { + engine([profile({ consent_current: false })]); + render( {}} />); + expect(await screen.findByRole("button", { name: "Review the notice again" })).toBeTruthy(); + expect(screen.queryByRole("button", { name: "Open in Chrome" })).toBeNull(); +}); diff --git a/packages/desktop/src/ui/ChromeProfilePicker.tsx b/packages/desktop/src/ui/ChromeProfilePicker.tsx new file mode 100644 index 0000000000..5f490f965e --- /dev/null +++ b/packages/desktop/src/ui/ChromeProfilePicker.tsx @@ -0,0 +1,257 @@ +// Chrome profile picker for a Browser target. A person opts in to a separate, +// Desktop-managed Chrome profile after reading the engine's notice, signs in +// there once, and Desktop fills the target's signed-in browser address with +// the endpoint of the window it opened. The engine refuses (fail closed) when +// the notice changed, the profile is open elsewhere, or attach can't be +// verified; this component only shows what the engine says. +import { useCallback, useEffect, useState } from "react"; +import { CMD, engineInvoke, engineTry } from "../lib/engine"; +import { Button, Callout, Field } from "./primitives"; + +export interface ChromeProfile { + profile_id: string; + name: string; + acknowledged_at: number | null; + consent_current: boolean; + open: boolean; + browser_cdp_endpoint: string | null; +} + +interface Notice { + title: string; + text: string; + sha256: string; +} + +interface Reply { + ok?: boolean; + error?: string; + profiles?: ChromeProfile[]; + profile_id?: string; + browser_cdp_endpoint?: string; +} + +export function ChromeProfilePicker({ + url, + endpoint, + disabled, + idPrefix, + onEndpoint, +}: { + url: string | undefined; + endpoint: string | undefined; + disabled: boolean; + idPrefix: string; + onEndpoint: (endpoint: string | undefined) => void; +}) { + const [profiles, setProfiles] = useState([]); + const [selected, setSelected] = useState(""); + const [notice, setNotice] = useState(null); + const [agreeing, setAgreeing] = useState<"create" | "reack" | null>(null); + const [agreed, setAgreed] = useState(false); + const [name, setName] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const refresh = useCallback(async () => { + const reply = await engineTry(CMD.CHROME_PROFILE_LIST, {}, null); + if (reply?.ok && reply.profiles) { + setProfiles(reply.profiles); + setSelected((current) => + current && reply.profiles?.some((p) => p.profile_id === current) + ? current + : (reply.profiles?.[0]?.profile_id ?? ""), + ); + } + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const call = useCallback( + async (cmd: string, params: Record): Promise => { + setBusy(true); + setError(null); + try { + const reply = await engineInvoke(cmd, params); + if (!reply.ok) { + setError(reply.error ?? "OpenAdapt couldn't do that. Nothing changed."); + return null; + } + return reply; + } catch (e) { + setError(String(e)); + return null; + } finally { + setBusy(false); + } + }, + [], + ); + + const showNotice = useCallback(async (mode: "create" | "reack") => { + const value = await engineTry(CMD.CHROME_PROFILE_NOTICE, {}, null); + if (value) { + setNotice(value); + setAgreed(false); + setAgreeing(mode); + } else { + setError("OpenAdapt couldn't load the notice. Nothing changed."); + } + }, []); + + const current = profiles.find((p) => p.profile_id === selected) ?? null; + + const agree = async () => { + if (!notice || !agreed) return; + const reply = agreeing === "reack" && current + ? await call(CMD.CHROME_PROFILE_ACKNOWLEDGE, { + profile_id: current.profile_id, + notice_sha256: notice.sha256, + acknowledged: true, + }) + : await call(CMD.CHROME_PROFILE_CREATE, { + name, + notice_sha256: notice.sha256, + acknowledged: true, + }); + if (reply) { + setAgreeing(null); + setName(""); + if (reply.profile_id) setSelected(reply.profile_id); + await refresh(); + } + }; + + const open = async () => { + if (!current) return; + const reply = await call(CMD.CHROME_PROFILE_OPEN, { + profile_id: current.profile_id, + url: url || undefined, + }); + if (reply?.browser_cdp_endpoint) onEndpoint(reply.browser_cdp_endpoint); + await refresh(); + }; + + const close = async () => { + if (!current) return; + const reply = await call(CMD.CHROME_PROFILE_CLOSE, { profile_id: current.profile_id }); + if (reply && endpoint && endpoint === current.browser_cdp_endpoint) onEndpoint(undefined); + await refresh(); + }; + + const remove = async () => { + if (!current) return; + const reply = await call(CMD.CHROME_PROFILE_REVOKE, { + profile_id: current.profile_id, + delete_data: true, + }); + if (reply) await refresh(); + }; + + const selectId = `${idPrefix}-chrome-profile`; + const nameId = `${idPrefix}-chrome-profile-name`; + const agreeId = `${idPrefix}-chrome-profile-agree`; + + return ( +
+ {profiles.length > 0 && ( + + + + )} +
+ {current && current.consent_current && !current.open && ( + + )} + {current && current.open && ( + + )} + {current && !current.consent_current && ( + + )} + + {current && !current.open && ( + + )} +
+ {agreeing && notice && ( + +
+ {notice.text} +
+ {agreeing === "create" && ( + + setName(event.target.value)} + placeholder="Work portals" + /> + + )} + +
+ + +
+
+ )} + {error && ( + + {error} + + )} +
+ ); +} diff --git a/packages/desktop/src/ui/ExecutionTargetForm.tsx b/packages/desktop/src/ui/ExecutionTargetForm.tsx index 5603c92858..c7e388e3a2 100644 --- a/packages/desktop/src/ui/ExecutionTargetForm.tsx +++ b/packages/desktop/src/ui/ExecutionTargetForm.tsx @@ -7,6 +7,7 @@ import type { SurfaceCapability, TargetBackend, } from "../lib/types"; +import { ChromeProfilePicker } from "./ChromeProfilePicker"; import { Callout, Field, Pill } from "./primitives"; export const TARGETS: Record< @@ -263,6 +264,13 @@ function TargetFields({ spellCheck={false} /> + setField("browser_cdp_endpoint", value)} + /> ); case "windows": diff --git a/packages/desktop/tests/test_e2e/test_chrome_profile_real.py b/packages/desktop/tests/test_e2e/test_chrome_profile_real.py new file mode 100644 index 0000000000..dbabf4daae --- /dev/null +++ b/packages/desktop/tests/test_e2e/test_chrome_profile_real.py @@ -0,0 +1,204 @@ +"""Real Google Chrome on a Desktop-managed profile (Windows and macOS). + +Opt-in: runs only with ``OPENADAPT_REAL_CHROME=1``, which the GitHub-hosted +Windows and macOS jobs and the Windows lab set. It opens a visible Chrome +window, so it never runs on a developer Mac by default. + +A synthetic sign-in page on loopback sets a one-hour cookie. The test checks, +from the server side only, that Chrome sends it again after Desktop closes +and reopens the profile. Desktop never reads the cookie. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +import pytest + +from openadapt_desktop.chrome_profile import ( + ChromeProfileError, + ChromeProfileService, + find_chrome, + notice, + windows_elevated, +) + +ELEVATED = sys.platform == "win32" and windows_elevated() + +pytestmark = pytest.mark.skipif( + os.environ.get("OPENADAPT_REAL_CHROME") != "1", + reason="opens a real Chrome window; set OPENADAPT_REAL_CHROME=1 (CI and the Windows lab)", +) + +TOKEN = "synthetic-session-0001" + + +class _Portal(BaseHTTPRequestHandler): + seen: list[tuple[str, bool]] = [] + + def log_message(self, *_args) -> None: + pass + + def do_GET(self) -> None: # noqa: N802 - http.server API + signed_in = f"sid={TOKEN}" in (self.headers.get("Cookie") or "") + _Portal.seen.append((self.path, signed_in)) + if self.path.startswith("/login"): + self.send_response(302) + self.send_header("Set-Cookie", f"sid={TOKEN}; Max-Age=3600; Path=/; HttpOnly") + self.send_header("Location", "/home") + self.end_headers() + return + body = ( + b"Synthetic portal

Signed in as tester

" + if signed_in + else b"Synthetic portal

Sign in

" + ) + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +@pytest.fixture +def portal(): + _Portal.seen = [] + server = ThreadingHTTPServer(("127.0.0.1", 0), _Portal) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_address[1]}" + server.shutdown() + + +def _wait_for(predicate, timeout: float = 30.0) -> bool: + deadline = time.time() + timeout + while time.time() < deadline: + if predicate(): + return True + time.sleep(0.25) + return False + + +def _page_text(endpoint: str, origin: str) -> str: + playwright = pytest.importorskip("playwright.sync_api") + with playwright.sync_playwright() as pw: + browser = pw.chromium.connect_over_cdp(endpoint) + try: + pages = [p for c in browser.contexts for p in c.pages if p.url.startswith(origin)] + assert len(pages) == 1, [p.url for c in browser.contexts for p in c.pages] + return pages[0].inner_text("h1") + finally: + # Leaving only drops the DevTools connection; Chrome stays open. + browser.close() + + +def _navigate_open_page(endpoint: str, target_url: str) -> None: + playwright = pytest.importorskip("playwright.sync_api") + with playwright.sync_playwright() as pw: + browser = pw.chromium.connect_over_cdp(endpoint) + try: + pages = [p for c in browser.contexts for p in c.pages] + page = pages[0] if pages else browser.contexts[0].new_page() + page.goto(target_url, wait_until="domcontentloaded") + finally: + browser.close() + + +def _cookies_db_exists(user_data: Path) -> bool: + return (user_data / "Default" / "Cookies").exists() or ( + user_data / "Default" / "Network" / "Cookies" + ).exists() + + +@pytest.mark.skipif(not ELEVATED, reason="only an elevated Windows process is refused") +def test_an_elevated_windows_desktop_refuses_real_chrome(tmp_path: Path) -> None: + find_chrome() + service = ChromeProfileService(tmp_path / "data") + profile_id = service.create("Synthetic", notice()["sha256"], True)["profile_id"] + with pytest.raises(ChromeProfileError) as err: + service.open(profile_id, "https://example.invalid/") + assert err.value.code == "elevated_refused" + assert not (service.root / profile_id / "user-data" / "lockfile").exists() + + +@pytest.mark.skipif( + ELEVATED, + reason="an elevated Windows process is refused (GitHub's Windows runner); " + "the Windows lab runs this without administrator rights", +) +def test_sign_in_persists_and_desktop_closes_only_its_window(tmp_path: Path, portal: str) -> None: + find_chrome() # the job installs nothing; Chrome must already be there + service = ChromeProfileService(tmp_path / "data") + n = notice() + profile_id = service.create("Synthetic portal", n["sha256"], True)["profile_id"] + + own: subprocess.Popen[bytes] | None = None + try: + opened = service.open(profile_id, f"{portal}/login") + endpoint = opened["browser_cdp_endpoint"] + assert endpoint.startswith("http://127.0.0.1:") + assert _wait_for(lambda: ("/home", True) in _Portal.seen), ( + f"expected ('/home', True) in {_Portal.seen!r}" + ) + assert _page_text(endpoint, portal) == "Signed in as tester" + + user_data = service.root / profile_id / "user-data" + # Wait for Chrome's NetworkService to create the on-disk cookie store + # before starting a second Chrome or closing, so two fresh Chrome + # processes never race to initialize macOS "Chrome Safe Storage". + _wait_for(lambda: _cookies_db_exists(user_data), 10.0) + + # The person's own Chrome, which Desktop didn't open and must leave alone. + own_dir = Path(tempfile.mkdtemp(prefix="own-chrome-")) + own = subprocess.Popen( + [ + str(find_chrome()), + f"--user-data-dir={own_dir}", + "--no-first-run", + "--no-default-browser-check", + "about:blank", + ] + ) + + # Another Desktop that didn't open this profile refuses it (in use). + other = ChromeProfileService(tmp_path / "data") + with pytest.raises(ChromeProfileError) as err: + other.open(profile_id, f"{portal}/home") + assert err.value.code == "profile_in_use" + + assert service.close(profile_id)["closed"] is True + lock = "lockfile" if sys.platform == "win32" else "SingletonLock" + assert _wait_for(lambda: not os.path.lexists(user_data / lock), 15) + + # Reopen: Chrome sends the cookie it kept; nothing was typed again. + _Portal.seen.clear() + reopened = service.open(profile_id, f"{portal}/home") + if not _wait_for(lambda: ("/home", True) in _Portal.seen, 10.0) and not _Portal.seen: + # On macOS, launching a second Chrome instance while another Chrome + # process is active can occasionally open without loading the CLI + # URL; navigate the already-open tab to /home without re-logging in. + _navigate_open_page(reopened["browser_cdp_endpoint"], f"{portal}/home") + assert _wait_for(lambda: ("/home", True) in _Portal.seen, 20.0), ( + f"expected ('/home', True) in {_Portal.seen!r}" + ) + assert _page_text(reopened["browser_cdp_endpoint"], portal) == "Signed in as tester" + service.close_all() + assert all(not p["open"] for p in service.list()["profiles"]) + + # The person's own Chrome is still running. + assert own.poll() is None + finally: + service.close_all() + if own is not None: + own.terminate() + try: + own.wait(10) + except subprocess.TimeoutExpired: + own.kill() diff --git a/packages/desktop/tests/test_engine/test_chrome_profile.py b/packages/desktop/tests/test_engine/test_chrome_profile.py new file mode 100644 index 0000000000..9c233eb5cd --- /dev/null +++ b/packages/desktop/tests/test_engine/test_chrome_profile.py @@ -0,0 +1,540 @@ +"""Desktop-managed Chrome profiles: consent, fail-closed launch, owned close. + +No Chrome starts here. Spawning, ``/json/version`` and ``Browser.close`` are +fakes; the real launch runs on the Windows lab and the macOS CI runner +(``tests/test_e2e/test_chrome_profile_real.py``). +""" + +from __future__ import annotations + +import os +import re +import socket +import subprocess +from pathlib import Path +from typing import Any + +import pytest + +from openadapt_desktop import chrome_profile as cp +from openadapt_desktop.chrome_profile import ChromeProfileError, ChromeProfileService, notice + +GUID = "/devtools/browser/0b5e6c2e-1111-2222-3333-444455556666" + + +class FakeProcess: + _next_pid = 4000 + + def __init__(self, args: list[str], *, exit_now: bool = False) -> None: + FakeProcess._next_pid += 1 + self.pid = FakeProcess._next_pid + self.args = args + self.returncode: int | None = 0 if exit_now else None + self.log: list[str] = [] + + def poll(self) -> int | None: + return self.returncode + + def wait(self, timeout: float | None = None) -> int: + if self.returncode is None: + raise subprocess.TimeoutExpired("chrome", timeout or 0) + return self.returncode + + def terminate(self) -> None: + self.log.append("terminate") + self.returncode = -15 + + def kill(self) -> None: + self.log.append("kill") + self.returncode = -9 + + +class Harness: + def __init__(self, tmp_path: Path, **overrides: Any) -> None: + self.tmp_path = tmp_path + self.spawned: list[FakeProcess] = [] + self.closed: list[tuple[int, str]] = [] + self.port = 51234 + self.version: dict[str, Any] = { + "Browser": "Chrome/158.0.8127.36", + "webSocketDebuggerUrl": f"ws://127.0.0.1:{self.port}{GUID}", + } + self.write_port = True + self.exit_now = False + self.close_exits = True + chrome = tmp_path / "Google Chrome" + chrome.write_text("") + self.chrome = chrome + kwargs: dict[str, Any] = { + "platform": "darwin", + "env": {}, + "find": lambda: self.chrome, + "spawn": self._spawn, + "json_version": self._json_version, + "browser_close": self._browser_close, + "sleep": lambda _s: None, + "start_timeout": 0.5, + } + kwargs.update(overrides) + self.service = ChromeProfileService(tmp_path / "data", **kwargs) + + def _spawn(self, args: list[str], **kwargs: Any) -> FakeProcess: + assert kwargs["stdin"] is subprocess.DEVNULL + process = FakeProcess(args, exit_now=self.exit_now) + self.spawned.append(process) + user_data = Path(next(a for a in args if a.startswith("--user-data-dir=")).split("=", 1)[1]) + if self.write_port and not self.exit_now: + (user_data / "DevToolsActivePort").write_text(f"{self.port}\n{GUID}\n") + return process + + def _json_version(self, port: int) -> dict[str, Any]: + assert port == self.port + return dict(self.version) + + def _browser_close(self, port: int, path: str) -> None: + self.closed.append((port, path)) + if self.close_exits: + for process in self.spawned: + process.returncode = 0 + + def create(self, name: str = "Work portals") -> str: + n = notice() + return self.service.create(name, n["sha256"], True)["profile_id"] + + +@pytest.fixture +def h(tmp_path: Path) -> Harness: + return Harness(tmp_path) + + +# ------------------------------------------------------------------ consent + + +def test_notice_hash_is_stable_and_names_the_rules() -> None: + n = notice() + assert n == notice() + assert re.fullmatch(r"[0-9a-f]{64}", n["sha256"]) + text = n["text"] + for phrase in ("separate Chrome profile", "never reads, copies, or exports", "keychain"): + assert phrase in text + + +@pytest.mark.parametrize( + ("sha", "ack"), [("0" * 64, True), (None, True), ("current", False), ("current", None)] +) +def test_create_requires_the_current_notice_and_an_explicit_yes(h: Harness, sha, ack) -> None: + sha = notice()["sha256"] if sha == "current" else sha + with pytest.raises(ChromeProfileError) as err: + h.service.create("Work", sha, ack) + assert err.value.code == "consent_required" + assert h.service.list()["profiles"] == [] + + +def test_create_records_consent_and_a_private_empty_directory(h: Harness) -> None: + profile_id = h.create() + listed = h.service.list()["profiles"] + assert [p["profile_id"] for p in listed] == [profile_id] + assert listed[0]["consent_current"] is True + assert listed[0]["open"] is False + user_data = h.service.root / profile_id / "user-data" + assert user_data.is_dir() and list(user_data.iterdir()) == [] + if os.name == "posix": + assert user_data.stat().st_mode & 0o077 == 0 + assert h.service.root.stat().st_mode & 0o077 == 0 + + +def test_a_changed_notice_refuses_open_until_agreed_again(h: Harness, monkeypatch) -> None: + profile_id = h.create() + monkeypatch.setattr(cp, "NOTICE_TEXT", cp.NOTICE_TEXT + "- A new rule.\n") + assert h.service.list()["profiles"][0]["consent_current"] is False + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id) + assert err.value.code == "consent_required" + assert h.spawned == [] + h.service.acknowledge(profile_id, notice()["sha256"], True) + assert h.service.open(profile_id)["open"] is True + + +def test_unknown_profile_is_refused(h: Harness) -> None: + with pytest.raises(ChromeProfileError) as err: + h.service.open("cp-deadbeef") + assert err.value.code == "profile_unknown" + + +# --------------------------------------------------------------------- open + + +def test_open_launches_official_chrome_on_the_owned_directory(h: Harness) -> None: + profile_id = h.create() + result = h.service.open(profile_id, "https://portal.example/start") + assert result == { + "profile_id": profile_id, + "open": True, + "browser_cdp_endpoint": f"http://127.0.0.1:{h.port}", + } + (process,) = h.spawned + user_data = h.service.root / profile_id / "user-data" + assert process.args == [ + str(h.chrome), + f"--user-data-dir={user_data}", + "--remote-debugging-port=0", + "--no-first-run", + "--no-default-browser-check", + "https://portal.example/start", + ] + # Desktop passes nothing that touches the keychain or the password store. + assert not any("keychain" in a or "password-store" in a for a in process.args) + assert h.service.list()["profiles"][0]["browser_cdp_endpoint"] == result["browser_cdp_endpoint"] + + +def test_open_twice_reuses_the_owned_window(h: Harness) -> None: + profile_id = h.create() + first = h.service.open(profile_id) + assert h.service.open(profile_id) == first + assert len(h.spawned) == 1 + + +def test_open_deletes_a_stale_devtools_file_before_launch(h: Harness) -> None: + profile_id = h.create() + user_data = h.service.root / profile_id / "user-data" + (user_data / "DevToolsActivePort").write_text(f"9222\n{GUID}\n") + h.write_port = False + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id) + assert err.value.code == "attach_unverified" + assert h.spawned[0].log == ["terminate"] + + +def test_open_refuses_a_bad_url(h: Harness) -> None: + profile_id = h.create() + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id, "file:///etc/passwd") + assert err.value.code == "url_invalid" + assert h.spawned == [] + + +@pytest.mark.skipif(os.name != "posix", reason="SingletonLock is a POSIX symlink") +def test_profile_in_use_is_refused_before_launch_mac(h: Harness) -> None: + profile_id = h.create() + user_data = h.service.root / profile_id / "user-data" + os.symlink(f"{socket.gethostname()}-{os.getpid()}", user_data / "SingletonLock") + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id) + assert err.value.code == "profile_in_use" + assert h.spawned == [] + + +posix_only = pytest.mark.skipif(os.name != "posix", reason="SingletonLock is a POSIX symlink") + + +@posix_only +def test_a_stale_lock_from_a_dead_process_is_not_in_use(tmp_path: Path) -> None: + os.symlink(f"{socket.gethostname()}-999999", tmp_path / "SingletonLock") + assert cp.profile_in_use(tmp_path, "darwin") is False + + +@posix_only +def test_a_lock_from_another_host_counts_as_in_use(tmp_path: Path) -> None: + os.symlink("some-other-host-12", tmp_path / "SingletonLock") + assert cp.profile_in_use(tmp_path, "darwin") is True + + +def test_windows_lockfile_held_open_counts_as_in_use(tmp_path: Path, monkeypatch) -> None: + (tmp_path / "lockfile").write_text("") + + def refuse(*_a, **_k): + raise PermissionError("sharing violation") + + monkeypatch.setattr(cp.os, "open", refuse) + assert cp.profile_in_use(tmp_path, "win32") is True + + +def test_windows_without_lockfile_is_free(tmp_path: Path) -> None: + assert cp.profile_in_use(tmp_path, "win32") is False + + +def test_chrome_exiting_after_launch_is_a_handoff_and_refused(h: Harness) -> None: + profile_id = h.create() + h.exit_now = True + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id) + assert err.value.code == "profile_in_use" + assert h.service.list()["profiles"][0]["open"] is False + + +@pytest.mark.parametrize( + "version", + [ + { + "Browser": "Chrome/158", + "webSocketDebuggerUrl": "ws://127.0.0.1:51234/devtools/browser/other", + }, + {"Browser": "Chrome/158", "webSocketDebuggerUrl": f"ws://10.0.0.5:51234{GUID}"}, + {"Browser": "Chrome/158", "webSocketDebuggerUrl": f"ws://127.0.0.1:9999{GUID}"}, + {"Browser": "HeadlessChrome/158", "webSocketDebuggerUrl": f"ws://127.0.0.1:51234{GUID}"}, + {}, + ], +) +def test_an_endpoint_that_isnt_ours_is_refused_and_closed(h: Harness, version) -> None: + profile_id = h.create() + h.version = version + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id) + assert err.value.code == "attach_unverified" + assert h.spawned[0].log == ["terminate"] + assert h.closed == [] # never Browser.close an endpoint we couldn't verify + + +def test_unreachable_endpoint_is_refused(tmp_path: Path) -> None: + def boom(_port: int) -> dict: + raise ConnectionRefusedError + + h = Harness(tmp_path, json_version=boom) + profile_id = h.create() + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id) + assert err.value.code == "attach_unverified" + + +def test_default_chrome_directories_are_refused(tmp_path: Path, monkeypatch) -> None: + h = Harness(tmp_path) + profile_id = h.create() + monkeypatch.setattr( + cp, "default_user_data_dirs", lambda *_a, **_k: [h.service.root / profile_id] + ) + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id) + assert err.value.code == "default_profile_refused" + assert h.spawned == [] + + +# ---------------------------------------------------------- find chrome + + +def test_find_chrome_accepts_only_official_chrome(tmp_path: Path, monkeypatch) -> None: + cft = tmp_path / "Google Chrome for Testing.app" / "chrome" + chromium = tmp_path / "Chromium.app" / "chrome" + official = tmp_path / "Google Chrome.app" / "chrome" + for path in (cft, chromium, official): + path.parent.mkdir(parents=True) + path.write_text("") + monkeypatch.setattr(cp, "chrome_candidates", lambda *_a: [cft, chromium]) + with pytest.raises(ChromeProfileError) as err: + cp.find_chrome() + assert err.value.code == "chrome_not_installed" + monkeypatch.setattr(cp, "chrome_candidates", lambda *_a: [cft, chromium, official]) + assert cp.find_chrome() == official + + +def test_chrome_candidates_per_platform() -> None: + win = cp.chrome_candidates( + "win32", {"PROGRAMFILES": r"C:\Program Files", "LOCALAPPDATA": r"C:\Users\u\AppData\Local"} + ) + assert [str(p).replace("\\", "/") for p in win] == [ + "C:/Program Files/Google/Chrome/Application/chrome.exe", + "C:/Users/u/AppData/Local/Google/Chrome/Application/chrome.exe", + ] + mac = cp.chrome_candidates("darwin", {}) + assert mac[0].as_posix() == "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" + + +def test_default_dirs_per_platform() -> None: + win = cp.default_user_data_dirs("win32", {"LOCALAPPDATA": r"C:\L"}) + assert str(win[0]).replace("\\", "/") == "C:/L/Google/Chrome/User Data" + mac = cp.default_user_data_dirs("darwin", {}) + assert mac[0].parts[-3:] == ("Application Support", "Google", "Chrome") + + +# -------------------------------------------------------------------- close + + +def test_close_sends_browser_close_to_the_owned_endpoint_only(h: Harness) -> None: + profile_id = h.create() + h.service.open(profile_id) + assert h.service.close(profile_id) == {"profile_id": profile_id, "open": False, "closed": True} + assert h.closed == [(h.port, GUID)] + assert h.spawned[0].log == [] # it exited from Browser.close; no terminate + assert h.service.close(profile_id)["closed"] is False + + +def test_close_falls_back_to_the_handle_when_browser_close_fails(h: Harness) -> None: + profile_id = h.create() + h.service.open(profile_id) + h.close_exits = False + h.service.close(profile_id) + assert h.spawned[0].log == ["terminate"] + + +def test_close_does_not_send_browser_close_when_the_endpoint_changed(h: Harness) -> None: + profile_id = h.create() + h.service.open(profile_id) + h.version = { + "Browser": "Chrome/158", + "webSocketDebuggerUrl": "ws://127.0.0.1:51234/devtools/browser/x", + } + h.service.close(profile_id) + assert h.closed == [] + assert h.spawned[0].log == ["terminate"] + + +def test_close_of_a_profile_desktop_did_not_open_does_nothing(h: Harness) -> None: + profile_id = h.create() + assert h.service.close(profile_id)["closed"] is False + assert h.spawned == [] and h.closed == [] + + +def test_close_all_closes_every_owned_window(h: Harness) -> None: + a, b = h.create("A"), h.create("B") + h.service.open(a) + h.port = 51235 + h.version["webSocketDebuggerUrl"] = f"ws://127.0.0.1:51235{GUID}" + h.service.open(b) + h.service.close_all() + assert all(p.poll() is not None for p in h.spawned) + assert all(not p["open"] for p in h.service.list()["profiles"]) + + +# ------------------------------------------------------------------- revoke + + +def test_revoke_refuses_while_open_and_deletes_on_request(h: Harness) -> None: + profile_id = h.create() + h.service.open(profile_id) + with pytest.raises(ChromeProfileError) as err: + h.service.revoke(profile_id, delete_data=True) + assert err.value.code == "profile_open" + h.service.close(profile_id) + h.service.revoke(profile_id, delete_data=True) + assert h.service.list()["profiles"] == [] + assert not (h.service.root / profile_id).exists() + + +def test_revoke_without_delete_keeps_the_folder(h: Harness) -> None: + profile_id = h.create() + h.service.revoke(profile_id) + assert (h.service.root / profile_id / "user-data").is_dir() + with pytest.raises(ChromeProfileError): + h.service.open(profile_id) + + +# --------------------------------------------------------- static boundary + + +def test_module_never_reads_cookies_passwords_or_the_keychain() -> None: + source = Path(cp.__file__).read_text(encoding="utf-8") + code = re.sub(r'""".*?"""', "", source, flags=re.S) + code = re.sub(r"#.*", "", code) + for banned in ( + "keyring", + "Login Data", + "Cookies", + ".cookies(", + "storage_state", + "getAllCookies", + "getCookies", + "use-mock-keychain", + "password-store", + "/usr/bin/security", + "find-generic-password", + "Local State", + "copytree", + ): + assert banned not in code, banned + + +def test_devtools_file_parsing(tmp_path: Path) -> None: + assert cp.read_devtools_active_port(tmp_path) is None + (tmp_path / "DevToolsActivePort").write_text("abc\n/x\n") + assert cp.read_devtools_active_port(tmp_path) is None + (tmp_path / "DevToolsActivePort").write_text(f"51234\n{GUID}") + assert cp.read_devtools_active_port(tmp_path) == (51234, GUID) + + +def test_browser_close_frame_is_a_masked_cdp_message_without_origin() -> None: + import json + import threading + + server = socket.socket() + server.bind(("127.0.0.1", 0)) + server.listen(1) + port = server.getsockname()[1] + got: dict[str, bytes] = {} + + def serve() -> None: + conn, _ = server.accept() + data = b"" + while b"\r\n\r\n" not in data: + data += conn.recv(4096) + got["request"] = data + conn.sendall(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n\r\n") + frame = conn.recv(4096) + got["frame"] = frame + conn.close() + + thread = threading.Thread(target=serve) + thread.start() + cp.send_browser_close(port, GUID) + thread.join(5) + server.close() + request = got["request"].decode() + assert request.startswith(f"GET {GUID} HTTP/1.1") + assert "origin:" not in request.lower() + frame = got["frame"] + assert frame[0] == 0x81 and frame[1] & 0x80 + length = frame[1] & 0x7F + mask, body = frame[2:6], frame[6 : 6 + length] + payload = bytes(b ^ mask[i % 4] for i, b in enumerate(body)) + assert json.loads(payload) == {"id": 1, "method": "Browser.close"} + + +def test_commands_are_window_only() -> None: + from openadapt_desktop import socket_server + + reachable = set(socket_server._SOCKET_COMMANDS) + assert not {c for c in reachable if c.startswith("chrome_profile")} + + +def test_an_elevated_windows_desktop_refuses_before_launch(tmp_path: Path) -> None: + h = Harness(tmp_path, platform="win32", elevated=lambda: True) + profile_id = h.create() + with pytest.raises(ChromeProfileError) as err: + h.service.open(profile_id) + assert err.value.code == "elevated_refused" + assert h.spawned == [] + + +def test_unknown_elevation_counts_as_elevated(monkeypatch) -> None: + import ctypes + + monkeypatch.delattr(ctypes, "windll", raising=False) + assert cp.windows_elevated() is True + + +def test_a_slow_debugging_server_is_retried_until_it_answers(tmp_path: Path) -> None: + calls: list[int] = [] + + def slow(port: int) -> dict: + calls.append(port) + if len(calls) < 3: + raise TimeoutError("still starting") + return { + "Browser": "Chrome/158", + "webSocketDebuggerUrl": f"ws://127.0.0.1:{port}{GUID}", + } + + h = Harness(tmp_path, json_version=slow, start_timeout=5) + assert h.service.open(h.create())["open"] is True + assert len(calls) == 3 + + +def test_a_foreign_endpoint_is_not_retried(tmp_path: Path) -> None: + calls: list[int] = [] + + def foreign(port: int) -> dict: + calls.append(port) + return {"Browser": "Chrome/158", "webSocketDebuggerUrl": f"ws://127.0.0.1:{port}/x"} + + h = Harness(tmp_path, json_version=foreign, start_timeout=5) + with pytest.raises(ChromeProfileError): + h.service.open(h.create()) + assert len(calls) == 1 diff --git a/packages/desktop/tests/test_engine/test_dispatch.py b/packages/desktop/tests/test_engine/test_dispatch.py index 444502bc56..d8463418c9 100644 --- a/packages/desktop/tests/test_engine/test_dispatch.py +++ b/packages/desktop/tests/test_engine/test_dispatch.py @@ -2852,6 +2852,13 @@ def test_all_frontend_commands_registered(self, deps) -> None: "shadow_pause", "shadow_unpause", "at_rest_status", + "chrome_profile_notice", + "chrome_profile_list", + "chrome_profile_create", + "chrome_profile_acknowledge", + "chrome_profile_open", + "chrome_profile_close", + "chrome_profile_revoke", } assert expected.issubset(set(disp.commands)) @@ -2931,3 +2938,12 @@ def replay(self, *args, **kwargs): {"workflow_id": "anything"}, run=False, stop_before_effect=True ) assert response["pre_action_refusal"] is True + + def test_shadow_emit_follows_runtime_reassignment(self, deps): + disp, _db, _events = deps + disp._shadow_resumed = True + shadow = disp.shadow + reassigned: list[tuple[str, dict]] = [] + disp.emit = lambda event, data: reassigned.append((event, data)) + shadow._emit("shadow.test", {"ok": True}) + assert reassigned == [("shadow.test", {"ok": True})] diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index fee19a1494..904e1ceb74 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.32.3" +version = "0.33.0" source = { editable = "." } dependencies = [ { name = "cryptography" },