Skip to content

Commit 2033e9d

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 9f058b4 commit 2033e9d

6 files changed

Lines changed: 98 additions & 23 deletions

File tree

‎Sources/App/AgentPeerSigning.swift‎

Lines changed: 43 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,14 @@ enum AgentPeerSigning {
4848
identifier: identifier, leaf: leaf, expectedHash: expectedHash)
4949
}
5050

51-
/// Only a directly launching app whose signed bundle explicitly declares ownership
52-
/// of the MCP transport can have durable approval. An unregistered launcher can
53-
/// still ask for approval for one live helper.
51+
/// Identifies the agent app that launched the helper, so its approval can be
52+
/// remembered. The direct parent must be a validly signed, hardened program
53+
/// with a real signing certificate (not ad-hoc) that is not part of macOS
54+
/// itself: shells and system interpreters are shared by many apps and so
55+
/// cannot stand for one app. The identity is the signing team (or, without a
56+
/// team, the leaf certificate) plus the code-signing identifier, so it
57+
/// survives app updates and restarts but not a different signer or program.
58+
/// Anything that cannot be identified this way gets a one-run approval.
5459
static func registeredHost(pid: pid_t) -> String? {
5560
guard let child = process(pid), child.pbi_ppid > 1 else { return nil }
5661
let parentPID = pid_t(child.pbi_ppid)
@@ -63,32 +68,41 @@ enum AgentPeerSigning {
6368
[], &guest) == errSecSuccess, let guest,
6469
SecCodeCheckValidity(guest, [], nil) == errSecSuccess,
6570
SecCodeCopyStaticCode(guest, [], &code) == errSecSuccess, let code,
71+
!isPlatformCode(code),
6672
SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,
67-
let details = info as? [String: Any], hardened(details),
73+
let details = info as? [String: Any], hostHardened(details),
6874
let identifier = details[kSecCodeInfoIdentifier as String] as? String,
69-
!identifier.isEmpty, identifier.utf8.count <= 255,
70-
let plist = details[kSecCodeInfoPList as String] as? [String: Any],
71-
plist["CFBundlePackageType"] as? String == "APPL",
72-
plist["CFBundleIdentifier"] as? String == identifier,
73-
let optedIn = plist["CodebasicTTSDirectMCPHost"] as? NSNumber,
74-
CFGetTypeID(optedIn) == CFBooleanGetTypeID(), optedIn.boolValue,
75+
!identifier.isEmpty, identifier.utf8.count <= 255, !identifier.contains(":"),
7576
let main = (details[kSecCodeInfoMainExecutable as String] as? URL)?.resolvingSymlinksInPath(),
76-
plist["CFBundleExecutable"] as? String == main.lastPathComponent,
7777
main.path == runningPath,
78-
main.deletingLastPathComponent().lastPathComponent == "MacOS",
79-
main.deletingLastPathComponent().deletingLastPathComponent().lastPathComponent == "Contents",
80-
main.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().pathExtension == "app",
8178
let certificates = details[kSecCodeInfoCertificates as String] as? [SecCertificate],
8279
let certificate = certificates.first,
8380
let currentChild = process(pid), currentChild.pbi_ppid == child.pbi_ppid,
8481
sameProcess(child, currentChild),
8582
let currentParent = process(parentPID), sameProcess(parent, currentParent),
8683
executablePath(parentPID) == runningPath,
8784
SecCodeCheckValidity(guest, [], nil) == errSecSuccess else { return nil }
88-
let signer = AgentBytes.hash(SecCertificateCopyData(certificate) as Data)
85+
// A bundle must agree with its own signature about which app it is.
86+
if let plist = details[kSecCodeInfoPList as String] as? [String: Any],
87+
let bundleID = plist["CFBundleIdentifier"] as? String, bundleID != identifier { return nil }
88+
let signer: String
89+
if let team = details[kSecCodeInfoTeamIdentifier as String] as? String, !team.isEmpty,
90+
team.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) }) {
91+
signer = "team." + team
92+
} else {
93+
signer = AgentBytes.hash(SecCertificateCopyData(certificate) as Data)
94+
}
8995
return AgentPairing.registeredHostPrefix + "\(signer):\(identifier)"
9096
}
9197

98+
/// Code signed as part of macOS (shells, interpreters, system tools).
99+
private static func isPlatformCode(_ code: SecStaticCode) -> Bool {
100+
var requirement: SecRequirement?
101+
guard SecRequirementCreateWithString("anchor apple" as CFString, [], &requirement) == errSecSuccess,
102+
let requirement else { return true }
103+
return SecStaticCodeCheckValidity(code, [], requirement) == errSecSuccess
104+
}
105+
92106
private static func process(_ pid: pid_t) -> proc_bsdinfo? {
93107
var info = proc_bsdinfo()
94108
let size = Int32(MemoryLayout<proc_bsdinfo>.size)
@@ -138,6 +152,20 @@ enum AgentPeerSigning {
138152

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

‎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
@@ -94,7 +94,6 @@ final class AgentTrustStore {
9494
func lookup(keyID: String, host: String) -> Lookup {
9595
if file.revoked.contains(keyID) { return .revoked }
9696
guard let client = file.clients.first(where: { $0.keyID == keyID }) else { return .unknown }
97-
if now().timeIntervalSince(client.lastSeen) > Self.idleLimit { return .expired }
9897
return client.host == host ? .trusted(client) : .hostChanged
9998
}
10099

‎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: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,11 +94,14 @@ def sign(path, identifier):
9494
"CFBundleExecutable": binary.name, "CFBundleIdentifier": identifier, "CFBundleName": "Same Agent Name",
9595
"CFBundlePackageType": "APPL", "CFBundleVersion": "1",
9696
}
97-
if direct:
98-
info["CodebasicTTSDirectMCPHost"] = True
9997
with (bundle / "Contents/Info.plist").open("wb") as plist:
10098
plistlib.dump(info, plist)
101-
sign(bundle, identifier)
99+
if direct:
100+
sign(bundle, identifier)
101+
else:
102+
# Ad-hoc signed: no certificate identifies the app, so approval lasts one run.
103+
run("/usr/bin/codesign", "--force", "--options", "runtime", "--sign", "-", "--identifier",
104+
identifier, bundle, env=env)
102105
hosts[name] = binary
103106
return hosts
104107

‎build.sh‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,10 @@ case "${1:-install}" in
144144
swiftc -O "$HERE/Sources/Core/AgentCatalog.swift" "$HERE/Sources/Core/AgentDeliveryProofs.swift" \
145145
"$HERE/Sources/Core/ExplanationDraftWorkspace.swift" "$HERE/Tests/AgentCatalogTests.swift" -o "$BUILD_DIR/agent-catalog-tests"
146146
"$BUILD_DIR/agent-catalog-tests" "$catalog_fixture"
147+
trust_fixture="$(mktemp -d "$BUILD_DIR/trust-test.XXXXXX")"
148+
swiftc -O "$HERE/Sources/Core/AgentCatalog.swift" "$HERE/Sources/Core/AgentTrustStore.swift" \
149+
"$HERE/Tests/AgentTrustStoreTests.swift" -o "$BUILD_DIR/agent-trust-store-tests"
150+
"$BUILD_DIR/agent-trust-store-tests" "$trust_fixture"
147151
socket_fixture="$(mktemp -d "$BUILD_DIR/socket-test.XXXXXX")"
148152
swiftc -O "$HERE/Sources/App/LocalInstructionSocket.swift" \
149153
"$HERE/Tests/LocalApprovedSocketLifecycleTests.swift" -o "$BUILD_DIR/local-approved-socket-tests"

‎docs/mcp-explanation-drafts.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@
1616
command = "/absolute/path/to/Codebasic TTS.app/Contents/Helpers/CodebasicAgentMCP"
1717
```
1818

19-
- `tts_agent_status`는 현재 연결과 받기 상태를 확인합니다. 등록된 직접 호스트의 승인은 재시작 뒤에도 유지될 수 있습니다. 앱을 개별 확인할 수 없는 호스트에는 실행별 승인이 필요합니다. 표시 이름은 요청을 알아보는 데 사용합니다.
19+
- `tts_agent_status`는 현재 연결과 받기 상태를 확인합니다. 표시 이름은 요청을 알아보는 데만 쓰고 승인 기준이 아닙니다.
20+
- **승인은 에이전트 앱 단위입니다.** 도우미를 직접 실행한 앱을 코드 서명으로 식별합니다. 식별자는 서명 팀 ID(없으면 서명 인증서)와 코드 서명 식별자(번들 ID)의 조합입니다. 강화 런타임으로 서명되고 macOS 기본 구성요소(셸·시스템 인터프리터)가 아닌 앱이면 한 번 승인한 뒤 앱을 재시작하거나 업데이트해도, 오래 쓰지 않아도 다시 승인하지 않습니다. 승인은 **승인 철회**, 다른 서명·다른 앱, 도우미 키 교체로만 끝납니다.
21+
- 애드혹 서명이거나 서명이 없는 실행 파일, 셸(`/bin/zsh -c …`)이나 시스템 인터프리터를 거쳐 도우미를 실행하는 호스트는 앱을 구별할 수 없어 실행별로 승인합니다. 같은 서명된 런타임(예: 공용 `node`)으로 직접 실행되는 서로 다른 도구는 같은 앱으로 보입니다.
2022
- 지시 없이 제출할 때는 `submit_tts_draft`에 `display_text`, 선택적인 `speech_text`, `idempotency_key`를 보냅니다. 지시와 연결할 때는 `get_tts_instructions`로 승인된 원문을 읽고 `submit_explanation_draft`에 그 응답의 `profile`과 `revision`도 보냅니다.
2123
- 각 본문과 지시의 한도는 UTF-8 8 KiB이고 받은 대본은 한 번에 8개까지 대기합니다. 대기 중인 대본과 등록 앱마다 최근 전송 키 128개는 수신 앱을 다시 실행해도 유지됩니다. 같은 앱에서 같은 키와 같은 내용이면 중복이며 내용이 바뀌면 충돌입니다. 실행별 승인 호스트가 재시작했거나 응답이 불명확하면 먼저 수신함을 확인합니다.
2224
- 철회한 등록 앱을 다시 연결하려면 해당 호스트에서 번들 도우미를 `--forget-key` 인자로 직접 실행한 뒤 평소 설정으로 재시작하고 새 요청을 승인합니다.

0 commit comments

Comments
 (0)