diff --git a/src/agent_env/computers/vm_bundle/macos/lib.sh b/src/agent_env/computers/vm_bundle/macos/lib.sh index b4ed585f2..eac6fd197 100644 --- a/src/agent_env/computers/vm_bundle/macos/lib.sh +++ b/src/agent_env/computers/vm_bundle/macos/lib.sh @@ -48,10 +48,26 @@ grant_executable() { granted "$executable" 1 "$executable" "$@" } +# file_url PATH: the file URL of the folder PATH as Foundation writes a bundle's: letters, digits and "!$&'()*+,-./:=@_~" +# as they are, every other printable ASCII character percent-encoded. A path with any other byte fails, since Foundation +# decomposes such a character before encoding it. +file_url() { + local LC_ALL=C path=${1%/} url= char i + for ((i = 0; i < ${#path}; i++)); do + char=${path:i:1} + case "$char" in + [A-Za-z0-9/._~!\$\&\'\(\)\*+,:=@-]) url+=$char ;; + [[:print:]]) url+=$(printf '%%%02X' "'$char") ;; + *) fail "$1 isn't printable ASCII, so its file URL can't be written for its screen capture approval" ;; + esac + done + echo "file://$url/" +} + # granted CLIENT TYPE PROGRAM SERVICE...: the TCC rows of CLIENT, a bundle identifier (TYPE 0) or a path (TYPE 1), for # each SERVICE, bound to PROGRAM's designated requirement. granted() { - local client=$1 type=$2 program=$3 requirement hex service now csreq approvals quoted + local client=$1 type=$2 program=$3 requirement hex service now csreq approvals quoted keys key shift 3 quoted=${client//\'/\'\'} requirement=$(codesign -d -r- "$program" 2>&1 | sed -n 's/^\(# *\)\{0,1\}designated => //p') @@ -74,13 +90,21 @@ granted() { last_reminded) VALUES ('$service', '$quoted', $type, 2, 2, 1, X'$hex', NULL, 0, 'UNUSED', NULL, 0, $now, NULL, NULL, 'UNUSED', $now);" if [ "$service" = kTCCServiceScreenCapture ]; then - # macOS asks once a program, even granted, before its first direct capture, keyed by the identifier or the - # path TCC knows it by; an approval recorded ahead counts. + # macOS asks a program, even granted, before its first direct capture, keyed by the identifier or the path + # TCC knows it by, and an app by its bundle's file URL too, "to bypass the system private window picker", + # and again once its privacy hint's date passes; approvals recorded ahead under each, hinted at no sooner + # than they are, count. approvals="$HOME/Library/Group Containers/group.com.apple.replayd/ScreenCaptureApprovals.plist" mkdir -p "$(dirname "$approvals")" - defaults write "$approvals" "$client" -dict \ - kScreenCaptureApprovalLastAlerted -date "3024-01-01 00:00:00 +0000" \ - kScreenCaptureApprovalLastUsed -date "3024-01-01 00:00:00 +0000" + keys=("$client") + if ((type == 0)); then keys+=("$(file_url "$program")"); fi + for key in "${keys[@]}"; do + defaults write "$approvals" "$key" -dict \ + kScreenCaptureApprovalLastAlerted -date "3024-01-01 00:00:00 +0000" \ + kScreenCaptureApprovalLastUsed -date "3024-01-01 00:00:00 +0000" \ + kScreenCapturePrivacyHintDate -date "3024-01-01 00:00:00 +0000" \ + kScreenCapturePrivacyHintPolicy -int 3153600000 + done fi done for pid in $(pgrep -x tccd); do as_root kill "$pid" 2>/dev/null || true; done diff --git a/tst/unit/env/envs/test_computer_macos_grants.py b/tst/unit/env/envs/test_computer_macos_grants.py new file mode 100644 index 000000000..6ae515f43 --- /dev/null +++ b/tst/unit/env/envs/test_computer_macos_grants.py @@ -0,0 +1,77 @@ +"""The macOS VM bundle's grants, lib.sh sourced in bash with macOS's tools stood in for: a screen capture grant records +its approval ahead under the client TCC knows it by, and for an app under its bundle's file URL too, which macOS keys an +app's "bypass the system private window picker" approval by, each hinted at no sooner than it's approved; that URL is +written as Foundation writes it, for every printable ASCII character, and a path past ASCII fails.""" +import subprocess +from pathlib import Path + +import agent_env + +LIB = Path(agent_env.__file__).parent / "computers" / "vm_bundle" / "macos" / "lib.sh" +APPROVED = ["-dict", "kScreenCaptureApprovalLastAlerted", "-date", "3024-01-01 00:00:00 +0000", + "kScreenCaptureApprovalLastUsed", "-date", "3024-01-01 00:00:00 +0000", + "kScreenCapturePrivacyHintDate", "-date", "3024-01-01 00:00:00 +0000", + "kScreenCapturePrivacyHintPolicy", "-int", "3153600000"] +#: What Foundation's NSURL fileURLWithPath writes on macOS 26 for each printable ASCII character but "/" in a path: +#: these as they are, and the rest as their percent-encodings. +KEPT = "!$&'()*+,-.0123456789:=@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~" +ENCODED = {" ": "%20", '"': "%22", "#": "%23", "%": "%25", ";": "%3B", "<": "%3C", ">": "%3E", "?": "%3F", + "[": "%5B", "\\": "%5C", "]": "%5D", "^": "%5E", "`": "%60", "{": "%7B", "|": "%7C", "}": "%7D"} +STUBS = { + "sudo": 'shift 3; exec "$@"', + "sqlite3": 'printf "sqlite3\\n--\\n" >> "$LOG"', + "codesign": 'echo "designated => identifier \\"com.example.app\\""', + "csreq": 'cat > /dev/null; : > "$3"', + "xxd": "echo 00", + "pgrep": "exit 1", + "defaults": 'if [ "$1" = read ]; then echo com.example.app; else printf "%s\\n" "$@" "--" >> "$LOG"; fi', +} + + +def _granted(tmp_path, *commands): + stubs, home, log = tmp_path / "stubs", tmp_path / "home", tmp_path / "log" + stubs.mkdir() + for name, body in STUBS.items(): + (stubs / name).write_text(f"#!/bin/bash\n{body}\n") + (stubs / name).chmod(0o755) + (tmp_path / ".password").write_text("") + script = "\n".join(["set -euo pipefail", f'. "{LIB}"', f'export PATH="{stubs}:$PATH"', f'build="{tmp_path}"', + *commands]) + subprocess.run(["bash", "-c", script], check=True, + env={"HOME": str(home), "LOG": str(log), "PATH": "/usr/bin:/bin"}) + written = [call.strip("\n").split("\n") for call in log.read_text().split("--\n") if call.strip("\n")] + return [call for call in written if call != ["sqlite3"]], home + + +def test_an_apps_screen_capture_is_approved_ahead_by_its_identifier_and_its_bundles_file_url(tmp_path): + writes, home = _granted(tmp_path, 'grant "/opt/agentenv/codex/Codex Computer Use.app" accessibility screen_capture') + + approvals = f"{home}/Library/Group Containers/group.com.apple.replayd/ScreenCaptureApprovals.plist" + assert writes == [["write", approvals, "com.example.app", *APPROVED], + ["write", approvals, "file:///opt/agentenv/codex/Codex%20Computer%20Use.app/", *APPROVED]] + + +def test_an_executables_screen_capture_is_approved_ahead_by_its_path_alone_and_no_other_service_is(tmp_path): + tool = tmp_path / "tool" + tool.write_text("") + + writes, home = _granted(tmp_path, f'grant_executable "{tool}" screen_capture', + f'grant_executable "{tool}" post_event') + + approvals = f"{home}/Library/Group Containers/group.com.apple.replayd/ScreenCaptureApprovals.plist" + assert writes == [["write", approvals, str(tool), *APPROVED]] + + +def _file_url(path, **locale): + return subprocess.run(["bash", "-c", f'. "{LIB}"; file_url "$1"', "_", path], capture_output=True, text=True, + env={"PATH": "/usr/bin:/bin", **locale}) + + +def test_a_bundles_file_url_is_foundations_for_every_printable_ascii_character_and_a_path_past_ascii_fails(): + chars = KEPT + "".join(ENCODED) + written = _file_url(f"/opt/{chars}.app/") + beyond = [_file_url("/opt/Café.app"), _file_url("/opt/Café.app", LANG="C.UTF-8", LC_ALL="C.UTF-8")] + + assert sorted(chars) == sorted(chr(c) for c in range(32, 127) if chr(c) != "/") + assert written.returncode == 0 and written.stdout == f"file:///opt/{KEPT}{''.join(ENCODED.values())}.app/\n" + assert all(run.returncode != 0 and "isn't printable ASCII" in run.stderr for run in beyond)