fix(cua): remove the standalone helper copy
This commit is contained in:
1 parent
e87a535d57
commit
4d4a7e5859
10 files changed
+15
-317
No files matched your search
@@ -12,8 +12,8 @@
|
||||
en: 4549f02fc53854a5
|
||||
zh: 6f74f1130b6623a8
|
||||
/deepseek-ai-dsh-experimental-cua-macos/table-of-contents:
|
||||
en: d473fa94a4488852
|
||||
zh: 43f0265a97820f64
|
||||
en: 395f2a62b2ce6b4a
|
||||
zh: 67912bb946c78837
|
||||
/deepseek-ai-dsh-experimental-cua-macos/use-this-package:
|
||||
en: d7e50cc9e3ad4137
|
||||
zh: a65cfb7e4688d159
|
||||
|
||||
@@ -22,7 +22,7 @@ Inspect macOS permissions, select running applications and windows, read accessi
|
||||
|
||||
The helper supplies bounded 64-pixel PNG application icons for permission prompts and saved-application lists. Icon reads do not launch an application or inspect its windows; icons do not determine reusable consent.
|
||||
|
||||
The helper runs through LaunchServices as the independent background application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. The permission page uses its system-reported name and icon; when attribution is unavailable, the system prompt identifies the application. When the helper is nested inside another `.app`, its launcher copies the complete signed bundle to `~/Library/Application Support/DeepSeek Harness/Computer Use/<runtime-key>/` before starting it. Each immutable generation is verified against the executable hash and application signature; earlier generations remain available for running installations. This keeps both macOS permission services attributed to the helper. A failed verification stops startup; remove the named cached generation before retrying.
|
||||
The helper runs through LaunchServices as the independent background application `DSH Computer Use.app`. Accessibility and Screen Recording permissions belong to this application. The permission page uses its system-reported name and icon; when attribution is unavailable, the system prompt identifies the application.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ kind: "package-reference"
|
||||
|
||||
helper 为授权提示和已授权应用列表提供 64 像素 PNG 图标。读取图标不会启动应用或检查窗口,图标不决定可复用授权。
|
||||
|
||||
helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行,辅助功能和屏幕录制权限归属于这个应用。权限页使用系统返回的应用名称和图标;无法查询归属时,以系统授权提示为准。 helper 嵌套在另一个 `.app` 内时,启动器先把完整的已签名应用复制到 `~/Library/Application Support/DeepSeek Harness/Computer Use/<runtime-key>/`,再启动它。每个不可变目录都校验可执行文件哈希和应用签名,旧目录保留给仍在运行的安装版本使用,使两项 macOS 权限都归属于 helper。校验失败会中止启动;删除报错中指定的缓存目录后再重试。
|
||||
helper 通过 LaunchServices 以独立的 `DSH Computer Use.app` 后台运行,辅助功能和屏幕录制权限归属于这个应用。权限页使用系统返回的应用名称和图标;无法查询归属时,以系统授权提示为准。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: e8cbc43d38786c40
|
||||
zh: 52b3ba85d98011b9
|
||||
/dsh-cua-native-helper/build-and-service:
|
||||
en: ab8fe195c70dd31c
|
||||
zh: b05bc116dc173c9c
|
||||
en: 7619d37566e773ef
|
||||
zh: c8f6e37f19ad9763
|
||||
/dsh-cua-native-helper/request-protocol:
|
||||
en: fc8043c425322cdd
|
||||
zh: cf1edb9a78fda301
|
||||
@@ -24,8 +24,8 @@
|
||||
en: caeccd866da14a36
|
||||
zh: 6a82e3a16a03813e
|
||||
/dsh-cua-native-helper/verification:
|
||||
en: d7d27c97fff638cd
|
||||
zh: 7f52556496a304d2
|
||||
en: 706d3434799530b3
|
||||
zh: e327c5fc7330c2b9
|
||||
/dsh-cua-native-helper/further-exploration:
|
||||
en: 265e1927952ce6d7
|
||||
zh: 7c35d9fd98b6e6c8
|
||||
|
||||
@@ -23,7 +23,7 @@ This macOS 14+ JSON-lines helper uses Swift 6, AppKit, Accessibility, CoreGraphi
|
||||
<a id="build-and-service"></a>
|
||||
## Build and service
|
||||
|
||||
Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-<arch>`. The `current.json` receipt selects a complete content-addressed generation. Signing defaults to ad hoc; release packagers can pass `--identity` for Developer ID signing and must notarize the distribution. The Host runs the application executable with `--ensure-shared`, which launches the background service through LaunchServices. The service exits after its last connection finishes cleanup. When the helper is nested inside another `.app`, its launcher copies the complete signed bundle to `~/Library/Application Support/DeepSeek Harness/Computer Use/<runtime-key>/` before starting it. Each immutable generation is verified against the executable hash and application signature; earlier generations remain available for running installations. This keeps both macOS permission services attributed to the helper. A failed verification stops startup; remove the named cached generation before retrying.
|
||||
Run `pnpm --dir packages/experimental/cua-macos run build:native` to publish a signed `DSH Computer Use.app` under `native/bin/darwin-<arch>`. The `current.json` receipt selects a complete content-addressed generation. Signing defaults to ad hoc; release packagers can pass `--identity` for Developer ID signing and must notarize the distribution. The Host runs the application executable with `--ensure-shared`, which launches the background service through LaunchServices. The service exits after its last connection finishes cleanup.
|
||||
|
||||
Generations in `native/.build/prepared/<arch>` and `native/bin/darwin-<arch>` are retained without automatic garbage collection. Use a fresh `--output-directory` for release staging, or clean the packaging output before building while no client uses it, so old generations do not enter the tarball. Secure signing timestamps can create distinct generations for identical sources.
|
||||
|
||||
@@ -125,7 +125,7 @@ Run `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py -
|
||||
|
||||
Run `python3 packages/experimental/cua-macos/native/tests/application_consent_e2e.py --helper /absolute/helper` in an unlocked macOS GUI session with the Apple Swift compiler available. It owns and cleans up its AppKit bundles and standalone GUI processes, checks metadata replacement, cold and direct launches, shared bundle IDs, persistent path identity across standalone restarts, and selection after a running executable is deleted. The default identity check requires no Accessibility or Screen Recording grants. Add `--desktop` to read intact fixtures’ controls, verify AX button presses in their state files, capture their windows, and record observation results after executable deletion; this requires existing grants for both permissions.
|
||||
|
||||
Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access. Run `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py` to verify signature-preserving extraction outside an enclosing `.app`, concurrent publication, and service teardown with uniquely signed fixtures.
|
||||
Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py` in a GUI login session to verify that the helper owns its permission identity even when started through two nested GUI launchers. Concurrent connections report the same helper name and icon. The check owns its applications, cleans up LaunchServices registrations, and requests no Accessibility or Screen Recording access.
|
||||
|
||||
Run `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py` after building and unlocking the Mac to verify an owned window whose application removes and later restores its AX roots. The check requires existing Accessibility/Screen Recording grants, rejects stale element indices, captures the AXless window, verifies a coordinate click in the fixture state file, and checks restoration. It never changes system permission settings.
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ kind: "package-reference"
|
||||
<a id="build-and-service"></a>
|
||||
## 构建与服务
|
||||
|
||||
运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-<arch>` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。 helper 嵌套在另一个 `.app` 内时,启动器先把完整的已签名应用复制到 `~/Library/Application Support/DeepSeek Harness/Computer Use/<runtime-key>/`,再启动它。每个不可变目录都校验可执行文件哈希和应用签名,旧目录保留给仍在运行的安装版本使用,使两项 macOS 权限都归属于 helper。校验失败会中止启动;删除报错中指定的缓存目录后再重试。
|
||||
运行 `pnpm --dir packages/experimental/cua-macos run build:native`,在 `native/bin/darwin-<arch>` 下生成带签名的 `DSH Computer Use.app`,`current.json` 选择完整的内容摘要目录。默认使用临时签名;正式打包可传入 `--identity` 指定 Developer ID,并由发布流程完成公证。Host 运行应用内的 `--ensure-shared` 入口,经 LaunchServices 后台启动服务。最后一条连接完成清理后,服务退出。
|
||||
|
||||
`native/.build/prepared/<arch>` 和 `native/bin/darwin-<arch>` 中的各代应用不会自动清理。正式打包时使用全新的 `--output-directory`,或确认没有客户端使用后清理打包输出再构建,避免旧应用进入 tarball。安全签名时间戳可能让相同源码生成不同代应用。
|
||||
|
||||
@@ -125,7 +125,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
|
||||
|
||||
在已解锁的 macOS GUI 会话中运行 `python3 packages/experimental/cua-macos/native/tests/application_consent_e2e.py --helper /absolute/helper`,需要可用的 Apple Swift 编译器。它创建并清理自己的 AppKit 应用和独立 GUI 进程,检查元数据替换、冷启动与直接启动、共用 Bundle ID、独立程序重启后的持久路径身份,以及删除运行中可执行文件后的选择行为。默认身份检查不需要辅助功能或屏幕录制权限。添加 `--desktop` 可读取完整测试应用的控件,通过状态文件验证 AX 按钮点击,截取窗口,并记录删除可执行文件后的观察结果;此模式要求已有两项系统权限。
|
||||
|
||||
在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。 运行 `python3 packages/experimental/cua-macos/native/tests/nested_application_e2e.py`,用独立签名的测试应用验证 helper 在外层 `.app` 之外保留签名发布、并发发布和服务退出。
|
||||
在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py`,验证两个嵌套 GUI 启动器启动 helper 后,授权归属仍为 helper 自己,多条连接得到相同名称和图标。检查自行创建应用并清理 LaunchServices 注册,不申请辅助功能或屏幕录制权限。
|
||||
|
||||
构建并解锁 Mac 后运行 `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py`,验证应用移除并恢复 AX 根节点的窗口。检查需要已有辅助功能/屏幕录制权限,会拒绝过期元素索引,捕获无 AX 窗口,通过 fixture 状态文件核实坐标点击,并检查恢复。不会修改系统权限设置。
|
||||
|
||||
|
||||
@@ -296,7 +296,6 @@ final class SharedSocket: @unchecked Sendable {
|
||||
throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED",
|
||||
message: "Computer Use requires its signed application bundle; set helperPath to DSH Computer Use.app/Contents/MacOS/dsh-cua-native")
|
||||
}
|
||||
let applicationURL = try StandaloneApplication.prepare(bundle.bundleURL, runtimeKey: options.runtimeKey, deadline: deadline)
|
||||
let configuration = NSWorkspace.OpenConfiguration()
|
||||
configuration.activates = false
|
||||
configuration.addsToRecentItems = false
|
||||
@@ -311,12 +310,12 @@ final class SharedSocket: @unchecked Sendable {
|
||||
guard DispatchTime.now().uptimeNanoseconds < deadline else {
|
||||
throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Computer Use launch lock exhausted the startup deadline")
|
||||
}
|
||||
// LaunchServices and a standalone bundle keep both permission services attributed to this helper.
|
||||
// LaunchServices gives the application its own TCC identity; direct spawning inherits the terminal's.
|
||||
let application: NSRunningApplication
|
||||
do { application = try await NSWorkspace.shared.openApplication(at: applicationURL, configuration: configuration) }
|
||||
do { application = try await NSWorkspace.shared.openApplication(at: bundle.bundleURL, configuration: configuration) }
|
||||
catch {
|
||||
if let failure = try SharedHelperOptions.startupFailure(at: failurePath) { throw failure }
|
||||
throw NativeFailure(code: "NATIVE_STARTUP", message: "macOS could not launch Computer Use at \(applicationURL.path): \(error.localizedDescription)")
|
||||
throw NativeFailure(code: "NATIVE_STARTUP", message: "macOS could not launch Computer Use at \(bundle.bundleURL.path): \(error.localizedDescription)")
|
||||
}
|
||||
let pid = application.processIdentifier
|
||||
guard pid > 0 else {
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
// Nested applications share their enclosing app's Screen Recording identity in TCC.
|
||||
import CryptoKit
|
||||
import Darwin
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
enum StandaloneApplication {
|
||||
static func hasApplicationAncestor(_ application: URL) -> Bool {
|
||||
var parent = application.deletingLastPathComponent()
|
||||
while parent.path != "/" {
|
||||
if parent.pathExtension.lowercased() == "app" { return true }
|
||||
parent.deleteLastPathComponent()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
static func prepare(_ application: URL, runtimeKey: String, deadline: UInt64) throws -> URL {
|
||||
let source = application.resolvingSymlinksInPath()
|
||||
guard hasApplicationAncestor(source) else { return source }
|
||||
let support = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
return try install(source, runtimeKey: runtimeKey,
|
||||
root: support.appendingPathComponent("DeepSeek Harness/Computer Use"), deadline: deadline)
|
||||
}
|
||||
|
||||
// Published generations remain immutable while any installed DSH version may still run them.
|
||||
static func install(_ source: URL, runtimeKey: String, root: URL, deadline: UInt64) throws -> URL {
|
||||
let files = FileManager.default
|
||||
try files.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
||||
let root = root.resolvingSymlinksInPath()
|
||||
let generation = root.appendingPathComponent(runtimeKey, isDirectory: true)
|
||||
let application = generation.appendingPathComponent(source.lastPathComponent, isDirectory: true)
|
||||
guard !hasApplicationAncestor(application) else {
|
||||
throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application storage must be outside another .app: \(root.path)")
|
||||
}
|
||||
var lock: SharedHelperLock?
|
||||
repeat {
|
||||
lock = try SharedHelperLock(path: root.appendingPathComponent("\(runtimeKey).lock").path)
|
||||
if lock != nil { break }
|
||||
usleep(10_000)
|
||||
} while DispatchTime.now().uptimeNanoseconds < deadline
|
||||
guard let lock else {
|
||||
throw NativeFailure(code: "NATIVE_STARTUP_TIMEOUT", message: "Computer Use application installation is still in progress")
|
||||
}
|
||||
defer { withExtendedLifetime(lock) {} }
|
||||
if files.fileExists(atPath: generation.path) {
|
||||
do { try validate(application, runtimeKey: runtimeKey) }
|
||||
catch {
|
||||
throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use cached application is invalid: \(error.localizedDescription); remove \(generation.path) and retry")
|
||||
}
|
||||
return application
|
||||
}
|
||||
let staging = root.appendingPathComponent(".staging-\(UUID().uuidString)", isDirectory: true)
|
||||
try files.createDirectory(at: staging, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
do {
|
||||
let stagedApplication = staging.appendingPathComponent(source.lastPathComponent, isDirectory: true)
|
||||
try files.copyItem(at: source, to: stagedApplication)
|
||||
try validate(stagedApplication, runtimeKey: runtimeKey)
|
||||
try files.moveItem(at: staging, to: generation)
|
||||
} catch {
|
||||
let failure = error
|
||||
do { try files.removeItem(at: staging) }
|
||||
catch {
|
||||
throw NativeFailure(code: "NATIVE_IO", message: "Computer Use installation failed: \(failure.localizedDescription); could not remove \(staging.path): \(error.localizedDescription)")
|
||||
}
|
||||
throw failure
|
||||
}
|
||||
return application
|
||||
}
|
||||
|
||||
private static func validate(_ application: URL, runtimeKey: String) throws {
|
||||
guard !hasApplicationAncestor(application.resolvingSymlinksInPath()) else {
|
||||
throw NativeFailure(code: "NATIVE_APPLICATION_REQUIRED", message: "Computer Use application resolves inside another .app: \(application.path)")
|
||||
}
|
||||
let executable = application.appendingPathComponent("Contents/MacOS/dsh-cua-native")
|
||||
let bytes = try Data(contentsOf: executable, options: .mappedIfSafe)
|
||||
let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
|
||||
var code: SecStaticCode?
|
||||
let flags = SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures | kSecCSCheckNestedCode)
|
||||
guard digest == runtimeKey,
|
||||
SecStaticCodeCreateWithPath(application as CFURL, [], &code) == errSecSuccess,
|
||||
let code, SecStaticCodeCheckValidity(code, flags, nil) == errSecSuccess else {
|
||||
throw NativeFailure(code: "NATIVE_APPLICATION_INVALID", message: "Computer Use application failed signature or executable verification at \(application.path)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
"""Verify nested helper extraction and concurrent launchers without granting macOS permissions."""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
from contextlib import ExitStack
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
from native_test_support import copy_helper, default_binary, unregister_helper
|
||||
from shared_helper_e2e import Connection, wait_released
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--helper', type=Path, default=None)
|
||||
args = parser.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix='cua-nest-', dir='/tmp') as temporary, ExitStack() as cleanup:
|
||||
root = Path(temporary)
|
||||
parent = root / 'Desktop.app' / 'Contents' / 'Resources'
|
||||
parent.mkdir(parents=True)
|
||||
helper = copy_helper(args.helper or default_binary(), parent)
|
||||
application = helper.parents[2]
|
||||
manifest = application / 'Contents/Info.plist'
|
||||
info = plistlib.loads(manifest.read_bytes())
|
||||
info['CFBundleIdentifier'] = 'dev.dsh.cua.nested-test.' + uuid.uuid4().hex
|
||||
manifest.write_bytes(plistlib.dumps(info))
|
||||
subprocess.run(['codesign', '--force', '--sign', '-', '--timestamp=none', str(application)],
|
||||
check=True, capture_output=True, timeout=30)
|
||||
key = hashlib.sha256(helper.read_bytes()).hexdigest()
|
||||
cache = Path.home() / 'Library/Application Support/DeepSeek Harness/Computer Use'
|
||||
generation = cache / key
|
||||
assert not generation.exists(), 'The unique signed fixture unexpectedly shares an existing generation'
|
||||
cleanup.callback(lambda: (cache / (key + '.lock')).unlink(missing_ok=True))
|
||||
cleanup.callback(lambda: shutil.rmtree(generation) if generation.exists() else None)
|
||||
copied_helper = generation / application.name / 'Contents/MacOS/dsh-cua-native'
|
||||
cleanup.callback(unregister_helper, copied_helper)
|
||||
runtime = [root / 'a', root / 'b']
|
||||
|
||||
def stop_owned(directory, pid):
|
||||
try:
|
||||
os.kill(pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
wait_released(directory / (key + '.lock'), pid)
|
||||
|
||||
def launch(directory):
|
||||
result = subprocess.run([str(helper), '--ensure-shared', '--runtime-key', key,
|
||||
'--runtime-directory', str(directory), '--startup-timeout-ms', '15000'],
|
||||
check=True, capture_output=True, text=True, timeout=25)
|
||||
ready = json.loads(result.stdout)
|
||||
cleanup.callback(stop_owned, directory, ready['pid'])
|
||||
client = Connection(directory / (key + '.sock'), key)
|
||||
cleanup.callback(client.close)
|
||||
return client
|
||||
|
||||
# Separate launcher processes share the installation lock while retaining independent service sockets.
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as workers:
|
||||
clients = list(workers.map(launch, runtime))
|
||||
for client in clients:
|
||||
state = client.call('permissionStatus', {})
|
||||
assert Path(state['helper']['path']).resolve() == copied_helper.resolve(), state
|
||||
assert Path(state['launchApplication']['path']).resolve() == copied_helper.parents[2].resolve(), state
|
||||
assert not any(part.endswith('.app') for part in copied_helper.parents[3].parts), state
|
||||
assert clients[0].ready['pid'] != clients[1].ready['pid']
|
||||
assert copied_helper.read_bytes() == helper.read_bytes()
|
||||
subprocess.run(['codesign', '--verify', '--deep', '--strict', str(copied_helper.parents[2])],
|
||||
check=True, capture_output=True, timeout=30)
|
||||
print('PASS: concurrent launchers use the same signature-preserving standalone application and drain both helpers')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,136 +0,0 @@
|
||||
// Real signed fixtures exercise cache publication, reuse, integrity and isolated permission ownership.
|
||||
import CryptoKit
|
||||
import Darwin
|
||||
import Foundation
|
||||
import Testing
|
||||
@testable import CuaNative
|
||||
|
||||
private struct ApplicationFixture {
|
||||
let root: URL
|
||||
let application: URL
|
||||
let cache: URL
|
||||
var executable: URL { application.appendingPathComponent("Contents/MacOS/dsh-cua-native") }
|
||||
var resource: URL { application.appendingPathComponent("Contents/Resources/value.txt") }
|
||||
var key: String { get throws { SHA256.hash(data: try Data(contentsOf: executable)).map { String(format: "%02x", $0) }.joined() } }
|
||||
var deadline: UInt64 { DispatchTime.now().uptimeNanoseconds + 30_000_000_000 }
|
||||
|
||||
init() throws {
|
||||
root = FileManager.default.temporaryDirectory.appendingPathComponent("cua-application-\(UUID().uuidString)")
|
||||
application = root.appendingPathComponent("Desktop.app/Contents/Resources/DSH Computer Use.app")
|
||||
cache = root.appendingPathComponent("support")
|
||||
try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try FileManager.default.createDirectory(at: resource.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try FileManager.default.copyItem(at: URL(fileURLWithPath: "/usr/bin/true"), to: executable)
|
||||
try Data("original resource".utf8).write(to: resource)
|
||||
let plist = try PropertyListSerialization.data(fromPropertyList: [
|
||||
"CFBundleIdentifier": "dev.dsh.cua.cache-test.\(UUID().uuidString)",
|
||||
"CFBundleExecutable": "dsh-cua-native", "CFBundleName": "DSH Computer Use", "CFBundlePackageType": "APPL",
|
||||
], format: .xml, options: 0)
|
||||
try plist.write(to: application.appendingPathComponent("Contents/Info.plist"))
|
||||
try sign()
|
||||
}
|
||||
|
||||
func sign() throws {
|
||||
let process = Process(), finished = DispatchSemaphore(value: 0)
|
||||
process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")
|
||||
process.arguments = ["--force", "--sign", "-", "--timestamp=none", application.path]
|
||||
process.standardOutput = FileHandle.nullDevice
|
||||
process.standardError = FileHandle.nullDevice
|
||||
process.terminationHandler = { _ in finished.signal() }
|
||||
try process.run()
|
||||
if finished.wait(timeout: .now() + 30) == .timedOut {
|
||||
kill(process.processIdentifier, SIGKILL)
|
||||
process.waitUntilExit()
|
||||
throw NativeFailure(code: "FIXTURE_TIMEOUT", message: "Ad-hoc fixture signing did not exit")
|
||||
}
|
||||
#expect(process.terminationReason == .exit)
|
||||
try #require(process.terminationStatus == 0)
|
||||
}
|
||||
|
||||
func close() {
|
||||
do { try FileManager.default.removeItem(at: root) }
|
||||
catch { Issue.record("Could not remove owned application fixture: \(error)") }
|
||||
}
|
||||
}
|
||||
|
||||
@Test func onlyNestedApplicationsNeedAnIndependentInstallation() throws {
|
||||
#expect(StandaloneApplication.hasApplicationAncestor(URL(fileURLWithPath: "/Applications/Desktop.app/Contents/Helper.app")))
|
||||
#expect(StandaloneApplication.hasApplicationAncestor(URL(fileURLWithPath: "/Applications/Desktop.APP/Helper.app")))
|
||||
let standalone = URL(fileURLWithPath: "/Users/example/Helper.app")
|
||||
#expect(!StandaloneApplication.hasApplicationAncestor(standalone))
|
||||
#expect(try StandaloneApplication.prepare(standalone, runtimeKey: "unused", deadline: 0) == standalone)
|
||||
}
|
||||
|
||||
@Test func aSignedHelperIsPublishedOutsideItsEnclosingApplicationAndReused() throws {
|
||||
let f = try ApplicationFixture(); defer { f.close() }
|
||||
let key = try f.key
|
||||
let installed = try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline)
|
||||
#expect(!StandaloneApplication.hasApplicationAncestor(installed))
|
||||
#expect(try Data(contentsOf: installed.appendingPathComponent("Contents/MacOS/dsh-cua-native")) == Data(contentsOf: f.executable))
|
||||
#expect(try Data(contentsOf: installed.appendingPathComponent("Contents/Resources/value.txt")) == Data(contentsOf: f.resource))
|
||||
#expect(try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline) == installed)
|
||||
}
|
||||
|
||||
@Test func changingTheSignedApplicationRetainsTheEarlierGeneration() throws {
|
||||
let f = try ApplicationFixture(); defer { f.close() }
|
||||
let old = try StandaloneApplication.install(f.application, runtimeKey: f.key, root: f.cache, deadline: f.deadline)
|
||||
try Data("new resource".utf8).write(to: f.resource)
|
||||
try f.sign()
|
||||
let new = try StandaloneApplication.install(f.application, runtimeKey: f.key, root: f.cache, deadline: f.deadline)
|
||||
#expect(old != new)
|
||||
#expect(try String(contentsOf: old.appendingPathComponent("Contents/Resources/value.txt"), encoding: .utf8) == "original resource")
|
||||
#expect(try String(contentsOf: new.appendingPathComponent("Contents/Resources/value.txt"), encoding: .utf8) == "new resource")
|
||||
}
|
||||
|
||||
@Test(arguments: ["Contents/Resources/value.txt", "Contents/MacOS/dsh-cua-native"])
|
||||
func aChangedCachedApplicationIsRejected(file: String) throws {
|
||||
let f = try ApplicationFixture(); defer { f.close() }
|
||||
let key = try f.key
|
||||
let installed = try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline)
|
||||
try Data("changed".utf8).write(to: installed.appendingPathComponent(file))
|
||||
#expect(throws: (any Error).self) {
|
||||
try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func anInvalidSourceLeavesNoPartialPublishedApplication() throws {
|
||||
let f = try ApplicationFixture(); defer { f.close() }
|
||||
let key = try f.key
|
||||
try Data("unsigned change".utf8).write(to: f.resource)
|
||||
#expect(throws: (any Error).self) {
|
||||
try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline)
|
||||
}
|
||||
#expect(try FileManager.default.contentsOfDirectory(atPath: f.cache.path) == ["\(key).lock"])
|
||||
}
|
||||
|
||||
@Test func applicationStorageCannotItselfBeNestedInAnotherApplication() throws {
|
||||
let f = try ApplicationFixture(); defer { f.close() }
|
||||
#expect(throws: (any Error).self) {
|
||||
try StandaloneApplication.install(f.application, runtimeKey: f.key,
|
||||
root: f.root.appendingPathComponent("Other.app/cache"), deadline: f.deadline)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func aCachedSymlinkCannotRedirectTheHelperIntoAnEnclosingApplication() throws {
|
||||
let f = try ApplicationFixture(); defer { f.close() }
|
||||
let key = try f.key
|
||||
try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true)
|
||||
try FileManager.default.createSymbolicLink(at: f.cache.appendingPathComponent(key),
|
||||
withDestinationURL: f.application.deletingLastPathComponent())
|
||||
#expect(throws: (any Error).self) {
|
||||
try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache, deadline: f.deadline)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func aCompetingInstallerDoesNotUseAPartialGeneration() throws {
|
||||
let f = try ApplicationFixture(); defer { f.close() }
|
||||
let key = try f.key
|
||||
try FileManager.default.createDirectory(at: f.cache, withIntermediateDirectories: true)
|
||||
let lock = try #require(try SharedHelperLock(path: f.cache.appendingPathComponent("\(key).lock").path))
|
||||
defer { withExtendedLifetime(lock) {} }
|
||||
#expect(throws: (any Error).self) {
|
||||
try StandaloneApplication.install(f.application, runtimeKey: key, root: f.cache,
|
||||
deadline: DispatchTime.now().uptimeNanoseconds)
|
||||
}
|
||||
#expect(!FileManager.default.fileExists(atPath: f.cache.appendingPathComponent(key).path))
|
||||
}
|
||||
Reference in new issue
Block a user