diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index d70a1592b4..9e46aff839 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,16 @@ # CHANGELOG +## v0.31.1 (2026-11-22) + +### Bug Fixes + +- Exception cards are checked on Windows as on macOS and Linux: a link or junction is + refused, and a card must be private to this user by its access control list (only this + user, SYSTEM and Administrators). Answers are written only where they come out private, + and card and answer files are read and written as raw bytes. +- Update the `url` crate to 2.5.9 (RUSTSEC-2026-0592). + ## v0.31.0 (2026-11-21) ### Features diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index f30ef439c1..b084dd55e8 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.31.0" +__version__ = "0.31.1" diff --git a/packages/desktop/openadapt_desktop/approver_anchor.py b/packages/desktop/openadapt_desktop/approver_anchor.py index 7f3ec25bca..22a82b18d1 100644 --- a/packages/desktop/openadapt_desktop/approver_anchor.py +++ b/packages/desktop/openadapt_desktop/approver_anchor.py @@ -470,7 +470,13 @@ def _read_windows(path: Path) -> bytes: # pragma: no cover - Windows only return data -def _windows_security(target: Path) -> tuple[str | None, list[Ace] | None]: # pragma: no cover +def _windows_security( # pragma: no cover - Windows only + target: Path, *, handle: int | None = None +) -> tuple[str | None, list[Ace] | None]: + """The owner SID and DACL entries of ``target``, or of the open file + ``handle`` (a Win32 handle) when one is given, so the answer is about the + file already opened and not whatever the name points to now.""" + import ctypes from ctypes import wintypes @@ -480,16 +486,28 @@ def _windows_security(target: Path) -> tuple[str | None, list[Ace] | None]: # p dacl = ctypes.c_void_p() descriptor = ctypes.c_void_p() owner_info, dacl_info = 0x1, 0x4 - status = advapi.GetNamedSecurityInfoW( - wintypes.LPCWSTR(str(target)), - 1, # SE_FILE_OBJECT - owner_info | dacl_info, - ctypes.byref(owner), - None, - ctypes.byref(dacl), - None, - ctypes.byref(descriptor), - ) + if handle is None: + status = advapi.GetNamedSecurityInfoW( + wintypes.LPCWSTR(str(target)), + 1, # SE_FILE_OBJECT + owner_info | dacl_info, + ctypes.byref(owner), + None, + ctypes.byref(dacl), + None, + ctypes.byref(descriptor), + ) + else: + status = advapi.GetSecurityInfo( + wintypes.HANDLE(handle), + 1, # SE_FILE_OBJECT + owner_info | dacl_info, + ctypes.byref(owner), + None, + ctypes.byref(dacl), + None, + ctypes.byref(descriptor), + ) if status != 0: raise AnchorError( "approver_anchor_unreadable", f"Can't read the security of {target} ({status})." diff --git a/packages/desktop/openadapt_desktop/exception_queue.py b/packages/desktop/openadapt_desktop/exception_queue.py index 087715aa6b..f0fe863c55 100644 --- a/packages/desktop/openadapt_desktop/exception_queue.py +++ b/packages/desktop/openadapt_desktop/exception_queue.py @@ -15,6 +15,15 @@ this user, readable by no one else (no group or other permission bits), under the size cap. A card that fails any check isn't shown. +Windows has no permission bits or ``O_NOFOLLOW``, so there the same rules are +checked another way: a card that is a link or any other reparse point (a +symlink, a junction) is refused before it is opened, the opened file must be +the one that was checked, and its owner and access control list are read from +the open handle. The owner must be this user, and only this user, SYSTEM and +Administrators (what a user's profile folder grants by default) may hold any +right on it (OWNER RIGHTS, which means the owner, too). When that can't be +read, no card is shown. + An answer is the closed answer signed with the approver key Desktop already uses for the stop queue (Touch ID on a Mac, the portal's key for a phone). The waiting run checks the signature against its pinned approver roster, so @@ -61,6 +70,12 @@ _RUN_REF = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") _CARD_FILE = re.compile(r"^card-([0-9a-f]{64})\.json$") _SUMMARY_MAX = 200 +_FILE_ATTRIBUTE_REPARSE_POINT = 0x400 +#: Who besides this user may hold rights on a card on Windows: SYSTEM and +#: Administrators, which a user's profile folder grants by default, and OWNER +#: RIGHTS (S-1-3-4), which names the file's owner, already required to be +#: this user. +_WINDOWS_TRUSTED_SIDS = frozenset({"S-1-5-18", "S-1-5-32-544", "S-1-3-4"}) def _canonical(value: Any) -> bytes: @@ -72,8 +87,124 @@ def registry_root() -> Path: return (Path(home) if home else Path.home() / ".openadapt") / "exceptions" +def _binary(flags: int) -> int: + """Raw bytes on Windows too (no newline or Ctrl-Z translation).""" + + return flags | getattr(os, "O_BINARY", 0) + + +def _is_link(info: os.stat_result) -> bool: + """A symlink, or on Windows any reparse point (a junction too).""" + + reparse = getattr(info, "st_file_attributes", 0) & _FILE_ATTRIBUTE_REPARSE_POINT + return stat.S_ISLNK(info.st_mode) or bool(reparse) + + +def windows_private_reason( + owner_sid: str | None, aces: list[Any] | None, *, me: frozenset[str] +) -> str | None: + """Why a Windows file isn't private to this user, or ``None`` when it is. + + ``me`` is this user's SIDs: the process token's user and the owner it + gives new files. ``aces is None`` is a NULL DACL (everyone has full + control). Deny entries only take rights away; an entry of a type this + check doesn't know refuses the file. + """ + + from openadapt_desktop.approver_anchor import ( + _ALLOW_ACE_TYPES, + _DENY_ACE_TYPES, + _INHERIT_ONLY_ACE, + ) + + if owner_sid not in me: + return f"it is owned by {owner_sid}, not this user" + if aces is None: + return "it has no access control list, so everyone can open it" + allowed = me | _WINDOWS_TRUSTED_SIDS + for ace in aces: + if ace.ace_type in _DENY_ACE_TYPES: + continue + if ace.ace_type not in _ALLOW_ACE_TYPES: + return f"it has an access entry of a type this check doesn't know ({ace.ace_type})" + if ace.flags & _INHERIT_ONLY_ACE: + continue + if ace.mask and ace.sid not in allowed: + return f"{ace.sid} has access to it" + return None + + +def _windows_me() -> frozenset[str]: # pragma: no cover - Windows only + """This process's user SID and the owner SID it gives new files.""" + + import ctypes + from ctypes import wintypes + + from openadapt_desktop.approver_anchor import _sid_string, _windll + + advapi = _windll("advapi32", use_last_error=True) + kernel = _windll("kernel32", use_last_error=True) + kernel.GetCurrentProcess.restype = wintypes.HANDLE + advapi.OpenProcessToken.argtypes = [ + wintypes.HANDLE, + wintypes.DWORD, + ctypes.POINTER(wintypes.HANDLE), + ] + advapi.GetTokenInformation.argtypes = [ + wintypes.HANDLE, + ctypes.c_int, + ctypes.c_void_p, + wintypes.DWORD, + ctypes.POINTER(wintypes.DWORD), + ] + token = wintypes.HANDLE() + if not advapi.OpenProcessToken(kernel.GetCurrentProcess(), 0x0008, ctypes.byref(token)): + raise OSError("can't open this process's token") + try: + sids: set[str] = set() + for info_class in (1, 4): # TokenUser, TokenOwner: a SID pointer first + buffer = ctypes.create_string_buffer(1024) + needed = wintypes.DWORD() + if not advapi.GetTokenInformation( + token, info_class, buffer, len(buffer), ctypes.byref(needed) + ): + raise OSError("can't read this process's token") + sid = ctypes.c_void_p.from_buffer(buffer).value + if not sid: + raise OSError("this process's token has no SID") + sids.add(_sid_string(advapi, kernel, ctypes.c_void_p(sid))) + return frozenset(sids) + finally: + kernel.CloseHandle(token) + + +def _windows_private(fd: int, path: Path) -> bool: # pragma: no cover - Windows only + """The open file is private to this user. Any failure to tell is ``False``.""" + + try: + import msvcrt + + from openadapt_desktop.approver_anchor import _windows_security + + owner, aces = _windows_security(path, handle=msvcrt.get_osfhandle(fd)) + return windows_private_reason(owner, aces, me=_windows_me()) is None + except Exception: + return False + + def _read(path: Path) -> bytes | None: - flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + flags = _binary(os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)) + windows = os.name == "nt" + before = None + if windows: + # No O_NOFOLLOW here: refuse a link before opening, and below require + # that the file opened is the one checked. + try: + before = os.lstat(path) + except OSError: + return None + if _is_link(before) or not stat.S_ISREG(before.st_mode): + return None try: fd = os.open(path, flags) except OSError: @@ -86,6 +217,15 @@ def _read(path: Path) -> bytes | None: return None if os.name == "posix" and info.st_mode & 0o077: return None # another user could read or change it + if windows: + if ( + before is None + or not info.st_ino + or (info.st_dev, info.st_ino) != (before.st_dev, before.st_ino) + ): + return None # swapped between the check and the open + if not _windows_private(fd, path): + return None # another user could read or change it return os.read(fd, _MAX_BYTES + 1)[:_MAX_BYTES] finally: os.close(fd) @@ -138,7 +278,7 @@ def open_cards(root: Path | None = None) -> list[dict[str, Any]]: cards: list[dict[str, Any]] = [] for folder in folders: try: - if stat.S_ISLNK(os.lstat(folder).st_mode) or not folder.is_dir(): + if _is_link(os.lstat(folder)) or not folder.is_dir(): continue names = sorted(os.listdir(folder)) except OSError: @@ -205,16 +345,20 @@ def message(unsigned: dict[str, Any]) -> bytes: def _write_exclusive(path: Path, payload: bytes) -> None: tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") - flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) - fd = os.open(tmp, flags, 0o600) - try: - view = memoryview(payload) - while view: - view = view[os.write(fd, view) :] - os.fsync(fd) - finally: - os.close(fd) + flags = _binary(os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)) try: + fd = os.open(tmp, flags, 0o600) + try: + # 0o600 means nothing on Windows: the file takes its folder's ACL. + # Write the answer only where it comes out private, as a card must. + if os.name == "nt" and not _windows_private(fd, tmp): + raise PermissionError(f"{tmp} would not be private to this user") + view = memoryview(payload) + while view: + view = view[os.write(fd, view) :] + os.fsync(fd) + finally: + os.close(fd) os.link(tmp, path) finally: try: @@ -307,6 +451,7 @@ def _after(a: str, b: str) -> bool: "registry_root", "unsigned_answer", "valid_card", + "windows_private_reason", ] diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 88c85f2015..5ade03b0a4 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.31.0", + "version": "0.31.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.31.0", + "version": "0.31.1", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 1b92b8568c..832475d09c 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.31.0", + "version": "0.31.1", "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 84d122859c..d25e1f1b33 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.31.0" +version = "0.31.1" 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 98cf6ea65f..1696ab47ab 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -1117,9 +1117,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.31.0" +version = "0.31.1" dependencies = [ "hex", "reqwest", @@ -4588,9 +4588,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index e8c03f006a..8e9fc5320f 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.31.0" +version = "0.31.1" 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 aa17f4b35d..9d3b1204a8 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.31.0", + "version": "0.31.1", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py index ce88aedccb..cd053a173e 100644 --- a/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py +++ b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py @@ -12,6 +12,7 @@ import json import os import stat +import subprocess import threading from datetime import datetime, timedelta, timezone from pathlib import Path @@ -20,6 +21,7 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey from openadapt_desktop import exception_queue, stop_queue +from openadapt_desktop.approver_anchor import Ace from openadapt_desktop.portal.stops import DispatcherStopQueue from tests.test_engine.test_stop_queue import ( # noqa: F401 (fixtures) enclave, @@ -94,6 +96,25 @@ def _cards(disp) -> list[dict]: return [c for c in listed["cards"] if c["kind"] == stop_queue.EXCEPTION_KIND] +def _let_everyone_read(path: Path, allowed: bool) -> None: + """Grant or take back read access for every user, the platform's way: + mode bits on POSIX, an ACL entry for Everyone (S-1-1-0) on Windows, where + ``chmod`` only sets the read-only flag.""" + + if os.name == "nt": + change = ["/grant", "*S-1-1-0:(R)"] if allowed else ["/remove:g", "*S-1-1-0"] + subprocess.run(["icacls", str(path), *change], check=True, capture_output=True) + else: + path.chmod(0o644 if allowed else 0o600) + + +def _private_to_this_user(path: Path) -> bool: + if os.name == "nt": + with path.open("rb") as handle: + return exception_queue._windows_private(handle.fileno(), path) + return stat.S_IMODE(path.stat().st_mode) == 0o600 + + def _answer_file(card: dict) -> Path: return ( exception_queue.registry_root() @@ -241,7 +262,8 @@ def test_the_window_signs_and_writes_the_runs_answer(queue, enclave): # noqa: F assert result["ok"] is True and result["changed"] == 1 assert len(enclave.prompts) == 1 path = _answer_file(raw) - assert stat.S_IMODE(path.stat().st_mode) == 0o600 + assert _private_to_this_user(path) + assert b"\r\n" not in path.read_bytes() answer = json.loads(path.read_text()) assert answer["answer"] == "done_by_person" assert answer["approver_kind"] == "person" and answer["route"] == "desktop" @@ -392,12 +414,44 @@ def test_a_card_other_users_can_read_is_not_shown(queue): # noqa: F811 disp, _db, _keychain = queue raw = _write_card() path = exception_queue.registry_root() / raw["run_ref"] / f"card-{raw['card_id'][7:]}.json" - path.chmod(0o644) + _let_everyone_read(path, True) assert _cards(disp) == [] - path.chmod(0o600) + _let_everyone_read(path, False) assert [c["source"]["id"] for c in _cards(disp)] == [raw["card_id"]] +_ME = "S-1-5-21-1-2-3-1001" +_PROFILE_ACL = [ + Ace(0, 0x10, 0x1F01FF, "S-1-5-18"), + Ace(0, 0x10, 0x1F01FF, "S-1-5-32-544"), + Ace(0, 0x10, 0x1F01FF, _ME), +] + + +@pytest.mark.parametrize( + "owner,aces,refused", + [ + (_ME, _PROFILE_ACL, False), + ("S-1-5-32-544", _PROFILE_ACL, False), # an elevated process's default owner + # What an elevated process's temp files get: no entry for the user, OWNER RIGHTS. + ("S-1-5-32-544", [*_PROFILE_ACL[:2], Ace(0, 0x10, 0x1F01FF, "S-1-3-4")], False), + ("S-1-5-21-1-2-3-1002", [Ace(0, 0x10, 0x1F01FF, "S-1-3-4")], True), + ("S-1-5-21-1-2-3-1002", _PROFILE_ACL, True), # another user's file + (_ME, None, True), # a NULL DACL: everyone has full control + (_ME, [*_PROFILE_ACL, Ace(0, 0, 0x120089, "S-1-1-0")], True), # Everyone may read + (_ME, [*_PROFILE_ACL, Ace(0, 0, 0x120089, "S-1-5-32-545")], True), # Users may read + (_ME, [*_PROFILE_ACL, Ace(9, 0, 0x120089, "S-1-1-0")], True), # a callback allow + (_ME, [*_PROFILE_ACL, Ace(0, 0x08, 0x120089, "S-1-1-0")], False), # inherit-only + (_ME, [*_PROFILE_ACL, Ace(1, 0, 0x120089, "S-1-1-0")], False), # a deny entry + (_ME, [*_PROFILE_ACL, Ace(2, 0, 0x120089, "S-1-1-0")], True), # an audit entry type + ], +) +def test_the_windows_rule_allows_only_this_user_system_and_administrators(owner, aces, refused): + me = frozenset({_ME, "S-1-5-32-544"} if owner == "S-1-5-32-544" else {_ME}) + reason = exception_queue.windows_private_reason(owner, aces, me=me) + assert (reason is not None) is refused + + def test_the_scan_stops_at_the_cap_across_runs(monkeypatch): monkeypatch.setattr(exception_queue, "MAX_CARDS", 2) for run in ("run-a", "run-b", "run-c"): diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index 97ac5c27f7..77904b7a72 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.31.0" +version = "0.31.1" source = { editable = "." } dependencies = [ { name = "cryptography" },