Skip to content

Commit f46e566

Browse files
committed
Remember approval per agent app without an opt-in key or idle expiry (#13)
Identify the agent app that launches the helper by its code signature: team ID (or leaf certificate without a team) plus signing identifier. Any hardened, certificate-signed, non-platform app now gets a durable approval; the CodebasicTTSDirectMCPHost Info.plist key that no real agent app carries is no longer required. Hosts may have entitlements other than get-task-allow and dyld environment variables. Ad-hoc, unsigned, shell or system-interpreter launchers still get a one-run approval. An approval no longer lapses after 30 idle days; it ends only on revocation, a different signer or app, or a replaced helper key. Add AgentTrustStoreTests to ./build.sh test. Agent: Claude Code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015LJG7MWqYoCZivtQ96kBhP
1 parent 05e167b commit f46e566

6 files changed

Lines changed: 95 additions & 25 deletions

File tree

‎Sources/App/AgentPeerSigning.swift‎

Lines changed: 43 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,14 @@ enum AgentPeerSigning {
4343
identifier: identifier, leaf: leaf, expectedHash: expectedHash)
4444
}
4545

46-
/// Only a directly launching app whose signed bundle explicitly declares ownership
47-
/// of the MCP transport can have durable approval. An unregistered launcher can
48-
/// still ask for approval for one live helper.
46+
/// Identifies the agent app that launched the helper, so its approval can be
47+
/// remembered. The direct parent must be a validly signed, hardened program
48+
/// with a real signing certificate (not ad-hoc) that is not part of macOS
49+
/// itself: shells and system interpreters are shared by many apps and so
50+
/// cannot stand for one app. The identity is the signing team (or, without a
51+
/// team, the leaf certificate) plus the code-signing identifier, so it
52+
/// survives app updates and restarts but not a different signer or program.
53+
/// Anything that cannot be identified this way gets a one-run approval.
4954
static func registeredHost(pid: pid_t) -> String? {
5055
guard let child = process(pid), child.pbi_ppid > 1 else { return nil }
5156
let parentPID = pid_t(child.pbi_ppid)
@@ -58,32 +63,41 @@ enum AgentPeerSigning {
5863
[], &guest) == errSecSuccess, let guest,
5964
SecCodeCheckValidity(guest, [], nil) == errSecSuccess,
6065
SecCodeCopyStaticCode(guest, [], &code) == errSecSuccess, let code,
66+
!isPlatformCode(code),
6167
SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,
62-
let details = info as? [String: Any], hardened(details),
68+
let details = info as? [String: Any], hostHardened(details),
6369
let identifier = details[kSecCodeInfoIdentifier as String] as? String,
64-
!identifier.isEmpty, identifier.utf8.count <= 255,
65-
let plist = details[kSecCodeInfoPList as String] as? [String: Any],
66-
plist["CFBundlePackageType"] as? String == "APPL",
67-
plist["CFBundleIdentifier"] as? String == identifier,
68-
let optedIn = plist["CodebasicTTSDirectMCPHost"] as? NSNumber,
69-
CFGetTypeID(optedIn) == CFBooleanGetTypeID(), optedIn.boolValue,
70+
!identifier.isEmpty, identifier.utf8.count <= 255, !identifier.contains(":"),
7071
let main = (details[kSecCodeInfoMainExecutable as String] as? URL)?.resolvingSymlinksInPath(),
71-
plist["CFBundleExecutable"] as? String == main.lastPathComponent,
7272
main.path == runningPath,
73-
main.deletingLastPathComponent().lastPathComponent == "MacOS",
74-
main.deletingLastPathComponent().deletingLastPathComponent().lastPathComponent == "Contents",
75-
main.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().pathExtension == "app",
7673
let certificates = details[kSecCodeInfoCertificates as String] as? [SecCertificate],
7774
let certificate = certificates.first,
7875
let currentChild = process(pid), currentChild.pbi_ppid == child.pbi_ppid,
7976
sameProcess(child, currentChild),
8077
let currentParent = process(parentPID), sameProcess(parent, currentParent),
8178
executablePath(parentPID) == runningPath,
8279
SecCodeCheckValidity(guest, [], nil) == errSecSuccess else { return nil }
83-
let signer = AgentBytes.hash(SecCertificateCopyData(certificate) as Data)
80+
// A bundle must agree with its own signature about which app it is.
81+
if let plist = details[kSecCodeInfoPList as String] as? [String: Any],
82+
let bundleID = plist["CFBundleIdentifier"] as? String, bundleID != identifier { return nil }
83+
let signer: String
84+
if let team = details[kSecCodeInfoTeamIdentifier as String] as? String, !team.isEmpty,
85+
team.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) }) {
86+
signer = "team." + team
87+
} else {
88+
signer = AgentBytes.hash(SecCertificateCopyData(certificate) as Data)
89+
}
8490
return AgentPairing.registeredHostPrefix + "\(signer):\(identifier)"
8591
}
8692

93+
/// Code signed as part of macOS (shells, interpreters, system tools).
94+
private static func isPlatformCode(_ code: SecStaticCode) -> Bool {
95+
var requirement: SecRequirement?
96+
guard SecRequirementCreateWithString("anchor apple" as CFString, [], &requirement) == errSecSuccess,
97+
let requirement else { return true }
98+
return SecStaticCodeCheckValidity(code, [], requirement) == errSecSuccess
99+
}
100+
87101
private static func process(_ pid: pid_t) -> proc_bsdinfo? {
88102
var info = proc_bsdinfo()
89103
let size = Int32(MemoryLayout<proc_bsdinfo>.size)
@@ -131,6 +145,20 @@ enum AgentPeerSigning {
131145
return expectedHash == nil || details[kSecCodeInfoUnique as String] as? Data == expectedHash
132146
}
133147

148+
/// Agent apps commonly carry entitlements (JIT, library validation for
149+
/// plug-ins), so a host only has to use the hardened runtime and must not
150+
/// let another process attach to it or inject code through the environment.
151+
private static func hostHardened(_ details: [String: Any]) -> Bool {
152+
guard let flags = details[kSecCodeInfoFlags as String] as? NSNumber,
153+
flags.uint32Value & SecCodeSignatureFlags.runtime.rawValue != 0 else { return false }
154+
guard let entitlements = details[kSecCodeInfoEntitlementsDict as String] else {
155+
return details[kSecCodeInfoEntitlements as String] == nil
156+
}
157+
guard let parsed = entitlements as? [String: Any] else { return false }
158+
let unsafe = ["com.apple.security.get-task-allow", "com.apple.security.cs.allow-dyld-environment-variables"]
159+
return !unsafe.contains { (parsed[$0] as? Bool) == true }
160+
}
161+
134162
/// Neither of these two bundled executables needs entitlements, including
135163
/// runtime exceptions for dynamic code, library validation or debugging.
136164
private static func hardened(_ details: [String: Any]) -> Bool {

‎Sources/Core/AgentTrustStore.swift‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,15 @@ final class AgentTrustStore {
4848

4949
enum Lookup: Equatable {
5050
case trusted(AgentTrustedClient)
51-
case unknown, revoked, hostChanged, expired
51+
case unknown, revoked, hostChanged
5252
}
5353

5454
enum Failure: Error { case invalid, full, revoked, hostChanged, unwritable }
5555

5656
static let maxClients = AgentPairing.slotCount
5757
static let maxRevoked = 64
58-
/// Sliding: a client that has not reconnected for this long must be approved again.
59-
static let idleLimit: TimeInterval = 30 * 24 * 3600
58+
// Approval does not expire. An approved app stays approved until the user
59+
// revokes it, its key changes, or it is launched by a different app.
6060

6161
private let url: URL
6262
private let now: () -> Date
@@ -86,7 +86,6 @@ final class AgentTrustStore {
8686
func lookup(keyID: String, host: String) -> Lookup {
8787
if file.revoked.contains(keyID) { return .revoked }
8888
guard let client = file.clients.first(where: { $0.keyID == keyID }) else { return .unknown }
89-
if now().timeIntervalSince(client.lastSeen) > Self.idleLimit { return .expired }
9089
return client.host == host ? .trusted(client) : .hostChanged
9190
}
9291

‎Tests/AgentTrustStoreTests.swift‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import CryptoKit
2+
import Foundation
3+
4+
/// An approved agent app stays approved across restarts and idle time until the
5+
/// user revokes it; approvals of different apps stay independent.
6+
@main struct AgentTrustStoreTests {
7+
static func main() throws {
8+
let directory = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)
9+
let url = directory.appendingPathComponent("agent-clients.json")
10+
var clock = Date(timeIntervalSince1970: 1_800_000_000)
11+
func store() -> AgentTrustStore { AgentTrustStore(url: url, now: { clock }) }
12+
let hostA = AgentPairing.registeredHostPrefix + "team.ABCDE12345:com.example.agent-a"
13+
let hostB = AgentPairing.registeredHostPrefix + "team.ABCDE12345:com.example.agent-b"
14+
let keyA = P256.Signing.PrivateKey().publicKey.x963Representation
15+
let keyB = P256.Signing.PrivateKey().publicKey.x963Representation
16+
let idA = AgentPairingProof.keyID(keyA)!, idB = AgentPairingProof.keyID(keyB)!
17+
18+
let first = store()
19+
let a = try first.trust(publicKey: keyA, label: "Agent", host: hostA)
20+
let b = try first.trust(publicKey: keyB, label: "Agent", host: hostB)
21+
precondition(a.id != b.id)
22+
23+
// A year without reconnecting and an app restart keep the approval.
24+
clock = clock.addingTimeInterval(365 * 24 * 3600)
25+
let reopened = store()
26+
precondition(reopened.lookup(keyID: idA, host: hostA) == .trusted(reopened.clients.first { $0.id == a.id }!))
27+
precondition(reopened.lookup(keyID: idB, host: hostB) != .unknown)
28+
29+
// The same key presented through another app is not the approved app.
30+
precondition(reopened.lookup(keyID: idA, host: hostB) == .hostChanged)
31+
32+
// Revoking A leaves B approved, also after a restart.
33+
precondition(reopened.forget(a.id))
34+
let afterRevoke = store()
35+
precondition(afterRevoke.lookup(keyID: idA, host: hostA) == .revoked)
36+
if case .trusted = afterRevoke.lookup(keyID: idB, host: hostB) {} else { preconditionFailure("B lost approval") }
37+
print("agent trust store tests passed")
38+
}
39+
}

‎Tests/Fixtures/run_agent_app_connections.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,11 @@ def build_hosts(root, env):
106106
"CFBundlePackageType": "APPL",
107107
"CFBundleVersion": "1",
108108
}
109-
if registered:
110-
info["CodebasicTTSDirectMCPHost"] = True
111109
with (bundle / "Contents/Info.plist").open("wb") as plist:
112110
plistlib.dump(info, plist)
113-
sign(bundle, identifier)
111+
# A certificate-signed app is identified by its signature; an ad-hoc signed
112+
# one cannot be told apart from other apps, so its approval lasts one run.
113+
sign(bundle, identifier, IDENTITY if registered else "-")
114114
hosts[name] = binary
115115
return hosts
116116

@@ -263,7 +263,7 @@ def connect(host, helper="helper", key_dir=keys):
263263
expect_status(broker, "approval_required")
264264
assert broker.send("broker-restart", "공용 런처의 재실행 원고")["outcome"] == "rejected"
265265
broker.close()
266-
check("lock cancels stale approvals and unregistered signed host requires approval for each run")
266+
check("lock cancels stale approvals and an ad-hoc signed host requires approval for each run")
267267

268268
assert server("disconnect " + client_a["id"]) == "ok"
269269
expect_status(a, "disabled")

‎build.sh‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,10 @@ case "${1:-install}" in
217217
swiftc -O "$HERE/Sources/Core/AgentCatalog.swift" "$HERE/Sources/Core/AgentInstructionEditing.swift" \
218218
"$HERE/Tests/AgentInstructionEditingTests.swift" -o "$BUILD_DIR/agent-instruction-editing-tests"
219219
"$BUILD_DIR/agent-instruction-editing-tests" "$editing_fixture"
220+
trust_fixture="$(mktemp -d "$BUILD_DIR/trust-test.XXXXXX")"
221+
swiftc -O "$HERE/Sources/Core/AgentCatalog.swift" "$HERE/Sources/Core/AgentTrustStore.swift" \
222+
"$HERE/Tests/AgentTrustStoreTests.swift" -o "$BUILD_DIR/agent-trust-store-tests"
223+
"$BUILD_DIR/agent-trust-store-tests" "$trust_fixture"
220224
socket_fixture="$(mktemp -d "$BUILD_DIR/socket-test.XXXXXX")"
221225
swiftc -O "$RUNTIME_SOURCE" "$HERE/Sources/App/LocalInstructionSocket.swift" \
222226
"$HERE/Tests/LocalApprovedSocketLifecycleTests.swift" -o "$BUILD_DIR/local-approved-socket-tests"

‎docs/mcp-explanation-drafts.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ command = "/absolute/path/to/Codebasic TTS.app/Contents/Helpers/CodebasicAgentMC
3333

3434
## 연결 유지
3535

36-
지속 승인은 도우미를 직접 실행하고 MCP 입출력을 소유하는 등록된 호스트 앱을 대상으로 합니다. 호스트는 서명된 앱의 `Info.plist`에 불리언 `CodebasicTTSDirectMCPHost`를 `true`로 넣어 이 경계를 명시합니다. 도우미에서 받은 이름과 `--client` 값은 화면에 표시합니다. 공유 런처 뒤에서 실제 앱을 확인할 수 없거나 호스트가 이 경계를 제공하지 않으면, 현재 도우미 실행에 대해 별도로 허용해야 합니다. 기존 후보가 이름과 런처로 저장한 승인은 새 등록으로 승계되지 않습니다.
36+
**승인은 에이전트 앱 단위입니다.** 도우미를 직접 실행한 앱을 코드 서명으로 식별합니다. 식별자는 서명 팀 ID(없으면 서명 인증서)와 코드 서명 식별자(번들 ID)의 조합이며, 앱 이름·경로·PID는 쓰지 않습니다. 유효한 인증서로 강화 런타임 서명이 되어 있고 macOS 기본 구성요소(셸·시스템 인터프리터)가 아닌 앱이면, 한 번 승인한 뒤 그 앱이나 Codebasic TTS를 재시작·업데이트해도, 오래 쓰지 않아도 다시 승인하지 않습니다. 앱이 따로 등록할 것은 없습니다. 애드혹 서명이거나 서명이 없는 실행 파일, 셸(`/bin/zsh -c …`)이나 시스템 인터프리터를 거쳐 도우미를 실행하는 호스트는 앱을 구별할 수 없어 실행별로 승인합니다. 같은 서명된 런타임(예: 공용 `node`)으로 직접 실행되는 서로 다른 도구는 같은 앱으로 보입니다.
3737

38-
등록된 앱은 로그인 키체인에 저장된 앱별 키로 새 챌린지에 응답합니다. Codebasic TTS는 실행 중인 상대 도우미와 호스트의 서명, 승인된 키를 확인합니다. 전체 받기와 해당 앱의 받기가 켜져 있을 때 다시 연결되고, 화면 잠금 중에는 모든 수신이 막힙니다. **잊기**를 누르면 해당 앱에 한해 진행 중인 요청과 기존 키를 거절합니다. 해당 호스트가 다시 등록하려면 해당 호스트가 직접 도우미를 `--forget-key` 인자로 실행해 자격증명을 폐기한 뒤 새 연결을 승인해야 합니다.
38+
식별된 앱은 앱별 키로 새 챌린지에 응답합니다. 키는 `~/Library/Application Support/Codebasic TTS/agent-client-keys/`(폴더 0700, 파일 0600)에 저장됩니다. 키체인에 두면 자체 서명 빌드에서 앱을 다시 빌드·업데이트할 때마다 도우미가 키에 접근하지 못하기 때문입니다. Codebasic TTS는 실행 중인 상대 도우미와 호스트의 서명, 승인된 키를 확인합니다. 전체 받기와 해당 앱의 받기가 켜져 있을 때 다시 연결되고, 화면 잠금 중에는 모든 수신이 막힙니다. **잊기**를 누르면 해당 앱에 한해 진행 중인 요청과 기존 키를 거절합니다. 해당 호스트가 다시 등록하려면 해당 호스트가 직접 도우미를 `--forget-key` 인자로 실행해 자격증명을 폐기한 뒤 새 연결을 승인해야 합니다.
3939

4040
전송 키는 승인된 연결마다 따로 해석합니다. 등록된 앱에서 저장 문서가 남아 있으면 재시작 후에도 동일 키와 동일 제목·본문·낭독본은 중복으로 보고합니다. 임시 승인 세션을 다시 실행한 경우에는 재전송하기 전에 수신 목록을 확인하세요. 선택 지시는 사용자가 지정한 앱에만 공유하며 Codebasic TTS를 다시 실행하면 선택이 풀립니다.
4141

0 commit comments

Comments
 (0)