Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

ci(cua-driver): prove jev-use on Windows with the default elevated autostart (#4251)

Francesco Bonacci1089d8ef6619
diff --git a/.github/scripts/tests/test_ci_jev_use_workflow.py b/.github/scripts/tests/test_ci_jev_use_workflow.py
index 60194b580b..d331484f53 100644
--- a/.github/scripts/tests/test_ci_jev_use_workflow.py
+++ b/.github/scripts/tests/test_ci_jev_use_workflow.py
@@ -7,10 +7,8 @@ import yaml
ROOT = Path(__file__).resolve().parents[3]
WORKFLOW = ROOT / ".github/workflows/ci-jev-use.yml"
-STANDARD_USER_SCRIPTS = (
- "scripts/ci/windows/invoke-standard-user-token.ps1",
- "scripts/ci/windows/run-jev-use-standard-user.ps1",
-)
+WINDOWS_PROOF_SCRIPT = "scripts/ci/windows/run-jev-use-elevated-autostart.ps1"
+MIN_RELEASED_DRIVER_VERSION = (0, 30, 1)
def load() -> dict:
@@ -47,37 +45,64 @@ def test_released_driver_jobs_use_the_canonical_installers() -> None:
assert "https://cua.ai/driver/install.sh" in macos
assert "cargo build" not in macos
assert "https://cua.ai/driver/install.ps1" in windows
- assert "-NoAutoStart" in windows
assert "cargo build" not in windows
+def test_released_driver_jobs_use_default_version_resolution_with_a_floor() -> None:
+ jobs = load()["jobs"]
+ for name in ("released-driver-macos", "released-driver-windows"):
+ text = job_text(name)
+ # No pin: the canonical installer's own resolution picks the release.
+ assert "CUA_DRIVER_RS_VERSION" not in text, name
+ assert "CUA_DRIVER_VERSION" not in text, name
+ assert "-Release" not in text, name
+ floor = jobs[name]["env"]["MIN_RELEASED_DRIVER_VERSION"]
+ assert tuple(int(part) for part in floor.split(".")) >= MIN_RELEASED_DRIVER_VERSION, name
+ assert "older than" in text, name
+ assert "sort -V" in job_text("released-driver-macos")
+ assert "[version]$env:MIN_RELEASED_DRIVER_VERSION" in job_text("released-driver-windows")
+
+
+def test_windows_proves_the_default_elevated_autostart_path() -> None:
+ windows = job_text("released-driver-windows")
+ assert "-NoAutoStart" not in windows
+ assert "-AutoStart:$false" not in windows
+ assert "invoke-standard-user-token.ps1" not in windows
+ assert "run-jev-use-standard-user.ps1" not in windows
+ assert not (ROOT / "scripts/ci/windows/invoke-standard-user-token.ps1").exists()
+ assert "verify-user-session.ps1" in windows
+ assert WINDOWS_PROOF_SCRIPT.replace("/", "\\") in windows
+ script = (ROOT / WINDOWS_PROOF_SCRIPT).read_text(encoding="utf-8")
+ # The default task, started the way the installer tells users to.
+ assert 'Get-ScheduledTask -TaskName "cua-driver-serve"' in script
+ assert '-ne "Highest"' in script
+ assert "autostart kick" in script
+ assert "Start-Process" not in script
+ # Independent token oracle: elevated daemon, de-elevated browsers it launched.
+ assert "TokenIntegrityLevel" in script
+ assert "S-1-5-32-544" in script
+ assert "the autostart daemon must be elevated" in script
+ assert "ran with a privileged token" in script
+ assert "was not launched by a readable cua-driver.exe" in script
+ assert "does not prove the elevated path" in script
+ assert "is not below its launching Driver" in script
+
+
def test_released_driver_jobs_run_both_languages_and_audit_the_state_oracle() -> None:
for name in ("released-driver-macos", "released-driver-windows"):
text = job_text(name)
assert '"observed"] == {"submitted": "jev-guide-mock"}' in text, name
assert '("typescript", "mock", "verified")' in text, name
assert "verify_setup.py --typescript" in job_text("released-driver-macos")
- inner = (ROOT / STANDARD_USER_SCRIPTS[1]).read_text(encoding="utf-8")
+ inner = (ROOT / WINDOWS_PROOF_SCRIPT).read_text(encoding="utf-8")
assert "verify_setup.py --typescript" in inner
-def test_windows_proof_runs_from_a_standard_user_token() -> None:
- windows = job_text("released-driver-windows")
- assert "verify-user-session.ps1" in windows
- assert "invoke-standard-user-token.ps1" in windows
- assert "run-jev-use-standard-user.ps1" in windows
- helper = (ROOT / STANDARD_USER_SCRIPTS[0]).read_text(encoding="utf-8")
- assert "SAFER_LEVELID_NORMALUSER = 0x20000" in helper
- inner = (ROOT / STANDARD_USER_SCRIPTS[1]).read_text(encoding="utf-8")
- assert "WindowsBuiltInRole]::Administrator" in inner
- assert "deny only" in inner
-
-
-def test_helper_scripts_trigger_the_workflow() -> None:
+def test_windows_proof_script_triggers_the_workflow() -> None:
triggers = load()[True]
for event in ("pull_request", "push"):
- for path in STANDARD_USER_SCRIPTS:
- assert path in triggers[event]["paths"], (event, path)
+ assert WINDOWS_PROOF_SCRIPT in triggers[event]["paths"], event
+ assert not any("standard-user" in path for path in triggers[event]["paths"]), event
def test_macos_seeds_tcc_only_for_the_released_app_identity() -> None:
diff --git a/.github/workflows/ci-jev-use.yml b/.github/workflows/ci-jev-use.yml
index 3788e5ccf2..30bce99ab2 100644
--- a/.github/workflows/ci-jev-use.yml
+++ b/.github/workflows/ci-jev-use.yml
@@ -11,8 +11,7 @@ on:
- ".github/workflows/ci-jev-use.yml"
- ".github/workflows/authorized-live-jev-use.yml"
- ".github/workflows/authorized-live-jev-use-demo.yml"
- - "scripts/ci/windows/invoke-standard-user-token.ps1"
- - "scripts/ci/windows/run-jev-use-standard-user.ps1"
+ - "scripts/ci/windows/run-jev-use-elevated-autostart.ps1"
push:
branches: [main]
paths:
@@ -24,8 +23,7 @@ on:
- ".github/workflows/ci-jev-use.yml"
- ".github/workflows/authorized-live-jev-use.yml"
- ".github/workflows/authorized-live-jev-use-demo.yml"
- - "scripts/ci/windows/invoke-standard-user-token.ps1"
- - "scripts/ci/windows/run-jev-use-standard-user.ps1"
+ - "scripts/ci/windows/run-jev-use-elevated-autostart.ps1"
workflow_dispatch:
# Pull request code runs only on disposable GitHub-hosted runners. No job in
@@ -295,14 +293,18 @@ jobs:
retention-days: 14
# macOS and Windows prove the example against the released Driver, installed
- # through the canonical installers exactly as the guide tells users to. The
- # candidate-source build above stays Linux-only.
+ # through the canonical installers with their default version resolution,
+ # exactly as the guide tells users to. Each job fails if that resolution
+ # yields a Driver older than MIN_RELEASED_DRIVER_VERSION, so the proof never
+ # silently tests an older release. The candidate-source build above stays
+ # Linux-only.
released-driver-macos:
name: macOS released Driver mock E2E
runs-on: macos-26
timeout-minutes: 45
env:
CUA_DRIVER_BIN: /Applications/CuaDriver.app/Contents/MacOS/cua-driver
+ MIN_RELEASED_DRIVER_VERSION: "0.30.1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
@@ -327,7 +329,16 @@ jobs:
CUA_DRIVER_NO_MODIFY_PATH: "1"
run: |
/bin/bash -c "$(curl -fsSL https://cua.ai/driver/install.sh)"
- "$CUA_DRIVER_BIN" --version
+ version_output="$("$CUA_DRIVER_BIN" --version)"
+ echo "$version_output"
+ resolved="$(grep -Eo '[0-9]+\.[0-9]+\.[0-9]+' <<< "$version_output" | head -n 1)"
+ test -n "$resolved"
+ lowest="$(printf '%s\n%s\n' "$MIN_RELEASED_DRIVER_VERSION" "$resolved" | sort -V | head -n 1)"
+ if [ "$lowest" != "$MIN_RELEASED_DRIVER_VERSION" ]; then
+ echo "::error::canonical installer resolved Cua Driver $resolved, older than $MIN_RELEASED_DRIVER_VERSION"
+ exit 1
+ fi
+ echo "Released Cua Driver under test: $resolved"
codesign --verify --strict /Applications/CuaDriver.app
test -x "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
- name: Install locked example dependencies
@@ -402,6 +413,8 @@ jobs:
name: Windows released Driver mock E2E
runs-on: windows-latest
timeout-minutes: 45
+ env:
+ MIN_RELEASED_DRIVER_VERSION: "0.30.1"
defaults:
run:
shell: pwsh
@@ -427,15 +440,24 @@ jobs:
- name: Verify the interactive desktop session
working-directory: ${{ github.workspace }}
run: .\scripts\ci\windows\verify-user-session.ps1
- - name: Install the released Driver with the canonical installer
+ - name: Install the released Driver with the canonical installer defaults
run: |
- # -NoAutoStart: the logon task runs at the account's highest token,
- # which on this administrator account is elevated. The proof starts
- # the daemon itself from a standard-user token instead.
- & ([scriptblock]::Create((irm https://cua.ai/driver/install.ps1))) -NoAutoStart -NoPathUpdate
+ # Default install, as a user runs it: the installer also registers
+ # the cua-driver-serve autostart task at RunLevel=Highest. This job
+ # token is an administrator's, so both that daemon and the
+ # in-process runtime of `cua-driver mcp` are elevated, and the
+ # Driver must launch its isolated browsers de-elevated (#4234).
+ & ([scriptblock]::Create((irm https://cua.ai/driver/install.ps1))) -NoPathUpdate
$driver = Join-Path $env:LOCALAPPDATA "Programs\Cua\cua-driver\bin\cua-driver.exe"
if (-not (Test-Path -LiteralPath $driver -PathType Leaf)) { throw "installer did not create $driver" }
- & $driver --version
+ $versionOutput = (& $driver --version | Out-String).Trim()
+ Write-Host $versionOutput
+ if ($versionOutput -notmatch '(\d+\.\d+\.\d+)') { throw "cannot parse the Driver version from: $versionOutput" }
+ $resolved = [version]$Matches[1]
+ if ($resolved -lt [version]$env:MIN_RELEASED_DRIVER_VERSION) {
+ throw "canonical installer resolved Cua Driver $resolved, older than $env:MIN_RELEASED_DRIVER_VERSION"
+ }
+ Write-Host "Released Cua Driver under test: $resolved"
$chrome = Join-Path ${env:ProgramFiles} "Google\Chrome\Application\chrome.exe"
if ((Get-AuthenticodeSignature -FilePath $chrome).Status -ne "Valid") { throw "Chrome is not vendor-signed: $chrome" }
"CUA_DRIVER_BIN=$driver" >> $env:GITHUB_ENV
@@ -445,29 +467,16 @@ jobs:
if ($LASTEXITCODE -ne 0) { throw "uv sync failed" }
npm.cmd ci --ignore-scripts
if ($LASTEXITCODE -ne 0) { throw "npm ci failed" }
- - name: Run both mock agents through MCP from a standard-user token
+ - name: Run both mock agents through MCP with the default elevated autostart
working-directory: ${{ github.workspace }}
run: |
- # The proof and its evidence live in the user profile, which the
- # standard-user token can write.
- $root = Join-Path $env:USERPROFILE "jev-use-ci"
+ $root = Join-Path $env:RUNNER_TEMP "jev-use-ci"
$env:JEV_USE_PROOF_DIR = Join-Path $root "proof"
$env:JEV_USE_LOG_DIR = Join-Path $root "logs"
New-Item -ItemType Directory -Force $env:JEV_USE_LOG_DIR | Out-Null
"JEV_USE_PROOF_DIR=$env:JEV_USE_PROOF_DIR" >> $env:GITHUB_ENV
"JEV_USE_LOG_DIR=$env:JEV_USE_LOG_DIR" >> $env:GITHUB_ENV
- $inner = Join-Path $PWD "scripts\ci\windows\run-jev-use-standard-user.ps1"
- $pwshExe = (Get-Process -Id $PID).Path
- $transcript = Join-Path $env:JEV_USE_LOG_DIR "proof.log"
- $command = "cmd.exe /d /s /c `"`"$pwshExe`" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$inner`" > `"$transcript`" 2>&1`""
- $status = 1
- try {
- & .\scripts\ci\windows\invoke-standard-user-token.ps1 -CommandLine $command -WorkingDirectory $PWD -TimeoutSeconds 900
- $status = $LASTEXITCODE
- } finally {
- if (Test-Path $transcript) { Get-Content $transcript }
- }
- if ($status -ne 0) { throw "standard-user proof failed with exit code $status" }
+ .\scripts\ci\windows\run-jev-use-elevated-autostart.ps1
- name: Audit redacted E2E evidence
run: |
@'
@@ -504,6 +513,5 @@ jobs:
${{ env.JEV_USE_PROOF_DIR }}/summary.json
${{ env.JEV_USE_PROOF_DIR }}/*.jsonl
${{ env.JEV_USE_LOG_DIR }}/*.txt
- ${{ env.JEV_USE_LOG_DIR }}/*.log
if-no-files-found: error
retention-days: 14
diff --git a/scripts/ci/windows/invoke-standard-user-token.ps1 b/scripts/ci/windows/invoke-standard-user-token.ps1
deleted file mode 100644
index 2d5766bebd..0000000000
--- a/scripts/ci/windows/invoke-standard-user-token.ps1
+++ /dev/null
@@ -1,132 +0,0 @@
-# Run a command line in the current interactive session with a standard-user
-# token derived from the caller's token.
-#
-# GitHub-hosted Windows runs jobs as an administrator with a full token. Cua
-# Driver refuses to launch an isolated browser from an installation the
-# current token can modify, which any administrator token can do for Program
-# Files. This helper asks Windows for the SAFER "Normal User" level of the
-# caller's own token (the same level `runas /trustlevel:0x20000` uses): the
-# Administrators group becomes deny-only and administrative privileges are
-# removed, while the user, session, and desktop stay the same. It is a CI
-# stand-in for a standard user's logged-in desktop, not a sandbox.
-param(
- [Parameter(Mandatory = $true)]
- [string]$CommandLine,
- [Parameter(Mandatory = $true)]
- [string]$WorkingDirectory,
- [int]$TimeoutSeconds = 900
-)
-
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-
-Add-Type -TypeDefinition @"
-using System;
-using System.ComponentModel;
-using System.Runtime.InteropServices;
-using System.Text;
-
-public static class CuaStandardUserToken {
- const uint SAFER_SCOPEID_USER = 2;
- const uint SAFER_LEVELID_NORMALUSER = 0x20000;
- const uint SAFER_LEVEL_OPEN = 1;
- const uint CREATE_NO_WINDOW = 0x08000000;
- const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
- const uint WAIT_OBJECT_0 = 0;
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- struct STARTUPINFO {
- public int cb;
- public string lpReserved;
- public string lpDesktop;
- public string lpTitle;
- public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
- public short wShowWindow, cbReserved2;
- public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- struct PROCESS_INFORMATION {
- public IntPtr hProcess, hThread;
- public int dwProcessId, dwThreadId;
- }
-
- [DllImport("advapi32.dll", SetLastError = true)]
- static extern bool SaferCreateLevel(uint scopeId, uint levelId, uint openFlags, out IntPtr level, IntPtr reserved);
-
- [DllImport("advapi32.dll", SetLastError = true)]
- static extern bool SaferComputeTokenFromLevel(IntPtr level, IntPtr inToken, out IntPtr outToken, uint flags, IntPtr reserved);
-
- [DllImport("advapi32.dll", SetLastError = true)]
- static extern bool SaferCloseLevel(IntPtr level);
-
- [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- static extern bool CreateProcessAsUser(
- IntPtr token, string application, StringBuilder commandLine, IntPtr processAttributes,
- IntPtr threadAttributes, bool inheritHandles, uint creationFlags, IntPtr environment,
- string currentDirectory, ref STARTUPINFO startupInfo, out PROCESS_INFORMATION processInformation);
-
- [DllImport("kernel32.dll", SetLastError = true)]
- static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
-
- [DllImport("kernel32.dll", SetLastError = true)]
- static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
-
- [DllImport("kernel32.dll", SetLastError = true)]
- static extern bool TerminateProcess(IntPtr process, uint exitCode);
-
- [DllImport("kernel32.dll")]
- static extern bool CloseHandle(IntPtr handle);
-
- // Returns the child's exit code, or -1 after terminating it on timeout.
- public static int Run(string commandLine, string workingDirectory, uint timeoutMilliseconds) {
- IntPtr level;
- if (!SaferCreateLevel(SAFER_SCOPEID_USER, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN, out level, IntPtr.Zero)) {
- throw new Win32Exception(Marshal.GetLastWin32Error(), "SaferCreateLevel failed");
- }
- IntPtr token = IntPtr.Zero;
- try {
- if (!SaferComputeTokenFromLevel(level, IntPtr.Zero, out token, 0, IntPtr.Zero)) {
- throw new Win32Exception(Marshal.GetLastWin32Error(), "SaferComputeTokenFromLevel failed");
- }
- } finally {
- SaferCloseLevel(level);
- }
- try {
- var startup = new STARTUPINFO();
- startup.cb = Marshal.SizeOf(typeof(STARTUPINFO));
- startup.lpDesktop = "winsta0\\default";
- PROCESS_INFORMATION process;
- // A null environment inherits this process's environment block.
- if (!CreateProcessAsUser(token, null, new StringBuilder(commandLine), IntPtr.Zero, IntPtr.Zero,
- false, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT, IntPtr.Zero,
- workingDirectory, ref startup, out process)) {
- throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateProcessAsUser failed");
- }
- try {
- if (WaitForSingleObject(process.hProcess, timeoutMilliseconds) != WAIT_OBJECT_0) {
- TerminateProcess(process.hProcess, 124);
- WaitForSingleObject(process.hProcess, 10000);
- return -1;
- }
- uint exitCode;
- if (!GetExitCodeProcess(process.hProcess, out exitCode)) {
- throw new Win32Exception(Marshal.GetLastWin32Error(), "GetExitCodeProcess failed");
- }
- return unchecked((int)exitCode);
- } finally {
- CloseHandle(process.hThread);
- CloseHandle(process.hProcess);
- }
- } finally {
- CloseHandle(token);
- }
- }
-}
-"@
-
-$exitCode = [CuaStandardUserToken]::Run($CommandLine, $WorkingDirectory, [uint32]($TimeoutSeconds * 1000))
-if ($exitCode -eq -1) {
- throw "standard-user command timed out after $TimeoutSeconds seconds"
-}
-exit $exitCode
diff --git a/scripts/ci/windows/run-jev-use-elevated-autostart.ps1 b/scripts/ci/windows/run-jev-use-elevated-autostart.ps1
new file mode 100644
index 0000000000..777e756dc0
--- /dev/null
+++ b/scripts/ci/windows/run-jev-use-elevated-autostart.ps1
@@ -0,0 +1,289 @@
+# Run the jev-use deterministic proof on the default Windows user install:
+# install.ps1 registers the cua-driver-serve autostart task at
+# RunLevel=Highest, so on an administrator account the resident daemon is
+# elevated. MCP clients such as the jev-use runners spawn `cua-driver mcp`,
+# which on Windows hosts its own in-process runtime at the client's token; on
+# this administrator runner that runtime is elevated too. Either elevated
+# Driver must launch its isolated browser with a derived standard-user token
+# (#4234). This script checks that posture from outside the Driver before
+# trusting the proof result:
+#
+# - the autostart task is registered at RunLevel=Highest and every
+# `cua-driver serve` daemon it starts runs at High (or higher) integrity;
+# - the process that launched each isolated browser is an elevated
+# cua-driver.exe (read while the browser is alive); and
+# - every isolated browser process runs at Medium (or lower) integrity,
+# below its launching Driver, with Administrators not enabled.
+#
+# Inputs (environment):
+# CUA_DRIVER_BIN installed cua-driver.exe
+# JEV_USE_PROOF_DIR new evidence directory for verify_setup.py
+# JEV_USE_LOG_DIR existing directory for daemon and token diagnostics
+Set-StrictMode -Version Latest
+$ErrorActionPreference = "Stop"
+
+foreach ($name in @("CUA_DRIVER_BIN", "JEV_USE_PROOF_DIR", "JEV_USE_LOG_DIR")) {
+ if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) {
+ throw "$name is required"
+ }
+}
+$driver = $env:CUA_DRIVER_BIN
+$proofDir = $env:JEV_USE_PROOF_DIR
+$logDir = $env:JEV_USE_LOG_DIR
+if (-not (Test-Path -LiteralPath $driver -PathType Leaf)) {
+ throw "installed Driver not found: $driver"
+}
+
+$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..\..")).Path
+$exampleDir = Join-Path $repoRoot "libs\cua-driver\examples\jev-use"
+$python = Join-Path $exampleDir ".venv\Scripts\python.exe"
+if (-not (Test-Path -LiteralPath $python -PathType Leaf)) {
+ throw "locked example environment not found: $python"
+}
+
+Add-Type -TypeDefinition @"
+using System;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Security.Principal;
+
+public sealed class CuaTokenPosture {
+ public int Pid;
+ public bool Elevated;
+ public int ElevationType;
+ public bool AdministratorsEnabled;
+ public uint IntegrityRid;
+
+ const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
+ const uint TOKEN_QUERY = 0x0008;
+ const int TokenGroups = 2;
+ const int TokenElevationType = 18;
+ const int TokenElevation = 20;
+ const int TokenIntegrityLevel = 25;
+ const uint SE_GROUP_ENABLED = 0x4;
+ const uint SE_GROUP_USE_FOR_DENY_ONLY = 0x10;
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ static extern bool CloseHandle(IntPtr handle);
+ [DllImport("advapi32.dll", SetLastError = true)]
+ static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
+ [DllImport("advapi32.dll", SetLastError = true)]
+ static extern bool GetTokenInformation(IntPtr token, int cls, IntPtr info, int length, out int needed);
+ [DllImport("advapi32.dll")]
+ static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
+ [DllImport("advapi32.dll")]
+ static extern IntPtr GetSidSubAuthority(IntPtr sid, uint index);
+
+ static IntPtr Information(IntPtr token, int cls) {
+ int needed;
+ GetTokenInformation(token, cls, IntPtr.Zero, 0, out needed);
+ if (needed <= 0) {
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetTokenInformation size " + cls);
+ }
+ IntPtr buffer = Marshal.AllocHGlobal(needed);
+ if (!GetTokenInformation(token, cls, buffer, needed, out needed)) {
+ int error = Marshal.GetLastWin32Error();
+ Marshal.FreeHGlobal(buffer);
+ throw new Win32Exception(error, "GetTokenInformation " + cls);
+ }
+ return buffer;
+ }
+
+ public static CuaTokenPosture Read(int pid) {
+ IntPtr process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
+ if (process == IntPtr.Zero) {
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "OpenProcess " + pid);
+ }
+ IntPtr token;
+ try {
+ if (!OpenProcessToken(process, TOKEN_QUERY, out token)) {
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "OpenProcessToken " + pid);
+ }
+ } finally {
+ CloseHandle(process);
+ }
+ var posture = new CuaTokenPosture { Pid = pid };
+ try {
+ IntPtr buffer = Information(token, TokenElevation);
+ try { posture.Elevated = Marshal.ReadInt32(buffer) != 0; } finally { Marshal.FreeHGlobal(buffer); }
+
+ buffer = Information(token, TokenElevationType);
+ try { posture.ElevationType = Marshal.ReadInt32(buffer); } finally { Marshal.FreeHGlobal(buffer); }
+
+ buffer = Information(token, TokenIntegrityLevel);
+ try {
+ IntPtr sid = Marshal.ReadIntPtr(buffer);
+ byte count = Marshal.ReadByte(GetSidSubAuthorityCount(sid));
+ posture.IntegrityRid = (uint)Marshal.ReadInt32(GetSidSubAuthority(sid, (uint)(count - 1)));
+ } finally { Marshal.FreeHGlobal(buffer); }
+
+ buffer = Information(token, TokenGroups);
+ try {
+ int groupCount = Marshal.ReadInt32(buffer);
+ int entrySize = IntPtr.Size * 2;
+ for (int index = 0; index < groupCount; index++) {
+ IntPtr entry = IntPtr.Add(buffer, IntPtr.Size + index * entrySize);
+ var sid = new SecurityIdentifier(Marshal.ReadIntPtr(entry));
+ uint attributes = (uint)Marshal.ReadInt32(IntPtr.Add(entry, IntPtr.Size));
+ if (sid.Value == "S-1-5-32-544"
+ && (attributes & SE_GROUP_USE_FOR_DENY_ONLY) == 0
+ && (attributes & SE_GROUP_ENABLED) != 0) {
+ posture.AdministratorsEnabled = true;
+ }
+ }
+ } finally { Marshal.FreeHGlobal(buffer); }
+ } finally {
+ CloseHandle(token);
+ }
+ return posture;
+ }
+
+ public override string ToString() {
+ return String.Format(
+ "pid={0} integrity=0x{1:x4} elevated={2} elevation_type={3} administrators_enabled={4}",
+ Pid, IntegrityRid, Elevated, ElevationType, AdministratorsEnabled);
+ }
+}
+"@
+
+$HighIntegrity = [uint32]0x3000
+$MediumIntegrity = [uint32]0x2000
+$postureLog = Join-Path $logDir "token-posture.txt"
+function Write-Posture([string]$line) {
+ Write-Host $line
+ Add-Content -Encoding utf8 -LiteralPath $postureLog -Value $line
+}
+
+# 1. The installer registered the default autostart task at RunLevel=Highest.
+# install.ps1 reports a registration failure without failing the install,
+# so assert the task itself.
+$task = Get-ScheduledTask -TaskName "cua-driver-serve" -ErrorAction SilentlyContinue
+if ($null -eq $task) { throw "install.ps1 did not register the cua-driver-serve autostart task" }
+Write-Posture "[task] cua-driver-serve run_level=$($task.Principal.RunLevel) logon_type=$($task.Principal.LogonType) user=$($task.Principal.UserId)"
+if ([string]$task.Principal.RunLevel -ne "Highest") {
+ throw "the autostart task must run at RunLevel=Highest, got $($task.Principal.RunLevel)"
+}
+
+$sampler = $null
+$state = [hashtable]::Synchronized(@{ Stop = $false; Browsers = [System.Collections.ArrayList]::Synchronized([System.Collections.ArrayList]::new()) })
+try {
+ Write-Host "[driver] $(& $driver --version)"
+ # 2. Start the daemon exactly as the installer's hint tells users to
+ # without logging on again, then wait until it answers.
+ & $driver autostart kick
+ if ($LASTEXITCODE -ne 0) { throw "cua-driver autostart kick failed with exit code $LASTEXITCODE" }
+ $deadline = (Get-Date).AddSeconds(90)
+ while ($true) {
+ & $driver status *> (Join-Path $logDir "daemon-status.txt")
+ if ($LASTEXITCODE -eq 0) { break }
+ if ((Get-Date) -gt $deadline) {
+ Get-Content (Join-Path $logDir "daemon-status.txt") -ErrorAction SilentlyContinue
+ throw "the autostart daemon did not become ready within 90 seconds"
+ }
+ Start-Sleep -Milliseconds 500
+ }
+ Get-Content (Join-Path $logDir "daemon-status.txt")
+ & $driver autostart status *>> (Join-Path $logDir "daemon-status.txt")
+
+ # 3. The daemon is elevated: this is the default posture on an
+ # administrator account, and the reason this job exists.
+ $daemons = @(Get-CimInstance Win32_Process -Filter "Name='cua-driver.exe'" |
+ Where-Object { $_.CommandLine -match '\sserve(\s|$)' })
+ if ($daemons.Count -eq 0) { throw "no cua-driver serve daemon is running after autostart kick" }
+ $daemonPostures = @{}
+ foreach ($daemon in $daemons) {
+ $posture = [CuaTokenPosture]::Read([int]$daemon.ProcessId)
+ $daemonPostures[[int]$daemon.ProcessId] = $posture
+ Write-Posture "[daemon] $posture session=$($daemon.SessionId) command=$($daemon.CommandLine)"
+ if ($posture.IntegrityRid -lt $HighIntegrity) {
+ throw "the autostart daemon must be elevated on this administrator account: $posture"
+ }
+ }
+
+ # 4. Sample every isolated browser process while the proof runs; the
+ # Driver closes its isolated browser when each agent's session ends.
+ $sampler = Start-ThreadJob -ArgumentList $state -ScriptBlock {
+ param($state)
+ $seen = @{}
+ while (-not $state.Stop) {
+ foreach ($process in @(Get-CimInstance Win32_Process -Filter "Name='chrome.exe' OR Name='msedge.exe'" -ErrorAction SilentlyContinue)) {
+ $processId = [int]$process.ProcessId
+ if ($seen.ContainsKey($processId) -or [string]::IsNullOrEmpty($process.CommandLine)) { continue }
+ if ($process.CommandLine -notmatch '--user-data-dir') { continue }
+ $seen[$processId] = $true
+ $record = [ordered]@{
+ Pid = $processId
+ ParentPid = [int]$process.ParentProcessId
+ Main = ($process.CommandLine -notmatch '\s--type=')
+ Name = $process.Name
+ Parent = $null
+ ParentName = $null
+ ParentPosture = $null
+ Posture = $null
+ Error = $null
+ }
+ try { $record.Posture = [CuaTokenPosture]::Read($processId) } catch { $record.Error = $_.Exception.Message }
+ if ($record.Main) {
+ $parent = Get-CimInstance Win32_Process -Filter "ProcessId=$($record.ParentPid)" -ErrorAction SilentlyContinue
+ $record.Parent = if ($parent) { "$($parent.Name) $($parent.CommandLine)" } else { "exited" }
+ if ($parent) {
+ $record.ParentName = $parent.Name
+ try { $record.ParentPosture = [CuaTokenPosture]::Read($record.ParentPid) } catch { }
+ }
+ }
+ [void]$state.Browsers.Add([pscustomobject]$record)
+ }
+ Start-Sleep -Milliseconds 200
+ }
+ }
+
+ Push-Location $exampleDir
+ try {
+ & $python verify_mcp_tools.py
+ if ($LASTEXITCODE -ne 0) { throw "verify_mcp_tools.py failed with exit code $LASTEXITCODE" }
+ & $python verify_setup.py --typescript --output-dir $proofDir
+ if ($LASTEXITCODE -ne 0) { throw "verify_setup.py failed with exit code $LASTEXITCODE" }
+ } finally {
+ Pop-Location
+ }
+
+ $state.Stop = $true
+ $sampler | Wait-Job -Timeout 30 | Out-Null
+ $sampler | Receive-Job -ErrorAction Continue
+
+ # 5. Elevated Drivers launched the isolated browsers with standard-user
+ # tokens.
+ $browsers = @($state.Browsers)
+ foreach ($browser in $browsers) {
+ Write-Posture "[browser] name=$($browser.Name) main=$($browser.Main) parent=$($browser.ParentPid)$(if ($browser.Parent) { " parent_process=[$($browser.Parent)] parent_token=[$($browser.ParentPosture)]" }) $(if ($browser.Posture) { $browser.Posture } else { "pid=$($browser.Pid) unreadable: $($browser.Error)" })"
+ }
+ $mains = @($browsers | Where-Object { $_.Main -and $null -ne $_.Posture })
+ if ($mains.Count -lt 2) {
+ throw "expected an isolated browser main process for each of the two agents, observed $($mains.Count)"
+ }
+ foreach ($browser in $browsers | Where-Object { $null -ne $_.Posture }) {
+ $posture = $browser.Posture
+ if ($posture.AdministratorsEnabled -or $posture.IntegrityRid -gt $MediumIntegrity) {
+ throw "an isolated browser process ran with a privileged token: $posture"
+ }
+ }
+ foreach ($browser in $mains) {
+ $launcher = $browser.ParentPosture
+ if ($browser.ParentName -ne "cua-driver.exe" -or $null -eq $launcher) {
+ throw "isolated browser $($browser.Pid) was not launched by a readable cua-driver.exe: [$($browser.Parent)]"
+ }
+ if ($launcher.IntegrityRid -lt $HighIntegrity) {
+ throw "the Driver that launched isolated browser $($browser.Pid) is not elevated, so this run does not prove the elevated path: $launcher"
+ }
+ if ($browser.Posture.IntegrityRid -ge $launcher.IntegrityRid) {
+ throw "isolated browser $($browser.Posture) is not below its launching Driver $launcher"
+ }
+ }
+ Write-Posture "[verdict] elevated Driver launched $($mains.Count) isolated browsers at Medium integrity or lower; autostart daemon elevated"
+} finally {
+ $state.Stop = $true
+ if ($null -ne $sampler) { $sampler | Remove-Job -Force -ErrorAction SilentlyContinue }
+ & $driver stop *> $null
+}
diff --git a/scripts/ci/windows/run-jev-use-standard-user.ps1 b/scripts/ci/windows/run-jev-use-standard-user.ps1
deleted file mode 100644
index 7f60eafb26..0000000000
--- a/scripts/ci/windows/run-jev-use-standard-user.ps1
+++ /dev/null
@@ -1,80 +0,0 @@
-# Run the jev-use deterministic proof against the installed Cua Driver from a
-# standard-user token. Start this through invoke-standard-user-token.ps1; it
-# refuses to run with administrator rights, because Driver correctly refuses
-# isolated browser launch from an installation the current token can modify.
-#
-# Inputs (environment):
-# CUA_DRIVER_BIN installed cua-driver.exe
-# JEV_USE_PROOF_DIR new evidence directory for verify_setup.py
-# JEV_USE_LOG_DIR existing directory for daemon and token diagnostics
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-
-$driver = $env:CUA_DRIVER_BIN
-$proofDir = $env:JEV_USE_PROOF_DIR
-$logDir = $env:JEV_USE_LOG_DIR
-foreach ($name in @("CUA_DRIVER_BIN", "JEV_USE_PROOF_DIR", "JEV_USE_LOG_DIR")) {
- if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) {
- throw "$name is required"
- }
-}
-if (-not (Test-Path -LiteralPath $driver -PathType Leaf)) {
- throw "installed Driver not found: $driver"
-}
-
-$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..\..")).Path
-$exampleDir = Join-Path $repoRoot "libs\cua-driver\examples\jev-use"
-$python = Join-Path $exampleDir ".venv\Scripts\python.exe"
-if (-not (Test-Path -LiteralPath $python -PathType Leaf)) {
- throw "locked example environment not found: $python"
-}
-
-# Prove the token is a standard-user token before touching the Driver.
-$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
-$principal = [Security.Principal.WindowsPrincipal]::new($identity)
-$groups = (& whoami.exe /groups /fo csv | ConvertFrom-Csv)
-$groups | Format-Table -AutoSize | Out-String -Width 400 |
- Set-Content -Encoding utf8 (Join-Path $logDir "token-groups.txt")
-$administrators = @($groups | Where-Object { $_.SID -eq "S-1-5-32-544" })
-Write-Host "Token user: $($identity.Name); session: $((Get-Process -Id $PID).SessionId)"
-Write-Host "Administrators group: $(if ($administrators) { $administrators[0].Attributes } else { 'absent' })"
-if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
- throw "the proof must run from a standard-user token, but Administrators is enabled"
-}
-if ($administrators -and $administrators[0].Attributes -notmatch "deny only") {
- throw "Administrators is present without the deny-only attribute: $($administrators[0].Attributes)"
-}
-
-$daemon = $null
-try {
- Write-Host "[driver] $(& $driver --version)"
- # The installer ran with -NoAutoStart, so no elevated daemon exists. Start
- # the daemon from this token, as a standard user's logon task would.
- $daemon = Start-Process -FilePath $driver -ArgumentList "serve" -WindowStyle Hidden -PassThru `
- -RedirectStandardOutput (Join-Path $logDir "daemon.out.log") `
- -RedirectStandardError (Join-Path $logDir "daemon.err.log")
- $deadline = (Get-Date).AddSeconds(60)
- while ($true) {
- & $driver status *> (Join-Path $logDir "daemon-status.txt")
- if ($LASTEXITCODE -eq 0) { break }
- if ($daemon.HasExited) { throw "Driver daemon exited early with code $($daemon.ExitCode)" }
- if ((Get-Date) -gt $deadline) { throw "Driver daemon did not become ready within 60 seconds" }
- Start-Sleep -Milliseconds 500
- }
- Get-Content (Join-Path $logDir "daemon-status.txt")
-
- Push-Location $exampleDir
- try {
- & $python verify_mcp_tools.py
- if ($LASTEXITCODE -ne 0) { throw "verify_mcp_tools.py failed with exit code $LASTEXITCODE" }
- & $python verify_setup.py --typescript --output-dir $proofDir
- if ($LASTEXITCODE -ne 0) { throw "verify_setup.py failed with exit code $LASTEXITCODE" }
- } finally {
- Pop-Location
- }
-} finally {
- & $driver stop *> $null
- if ($null -ne $daemon -and -not $daemon.HasExited) {
- Stop-Process -Id $daemon.Id -Force -ErrorAction SilentlyContinue
- }
-}