Skip to content

Commit cc1548e

Browse files
committed
Order merged revocations so the file's own stay newest, bound the merge, guard file size (#31)
Answers the round-19 Codex review: - Revocations the file lacks are put before the file's own, so a later trim (oldest first) drops them before anything the file recorded; the cap is 1024 and a merge holds at most twice that. - commit never writes a file larger than the read limit. - The product home has no environment fallback (getpwuid only, like the helper). - [AGENT-DRAFT] logs the key prefix the connect line shows instead of the approval id. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015LJG7KnMPqFcfTZ8A1C2qh
1 parent 699a092 commit cc1548e

5 files changed

Lines changed: 55 additions & 13 deletions

File tree

‎Sources/App/AgentSessionController.swift‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,12 +1026,12 @@ import Security
10261026
let socket = LocalApprovedSocket(peer: pair.peer, endpoint: AgentPairing.draftEndpoint(slot: pair.slot), directory: directory,
10271027
lifetime: nil, maxFrame: AgentLimits.frameBytes,
10281028
verified: Self.verifier(for: pair)) { [weak self] bytes, active in
1029-
// The result, the app (its signing identity, the approval id the
1030-
// connect/approve/revoke lines also show, and the helper pid) and the
1031-
// lengths only; never the text, title, instruction or request key.
1029+
// The result, the app (its signing identity, the key prefix the connect
1030+
// line also shows, and the helper pid) and the lengths only; never the
1031+
// text, title, instruction or request key.
10321032
var lengths = (display: 0, speech: 0)
10331033
func answer(_ status: String) -> Data {
1034-
Log.agent.info("[AGENT-DRAFT] receipt host=\(pair.host ?? "unverified", privacy: .public) client=\(pair.client.uuidString, privacy: .public) pid=\(pair.peer.pid, privacy: .public) result=\(status, privacy: .public) display_len=\(lengths.display, privacy: .public) speech_len=\(lengths.speech, privacy: .public)")
1034+
Log.agent.info("[AGENT-DRAFT] receipt host=\(pair.host ?? "unverified", privacy: .public) key=\(String(pair.keyID.prefix(12)), privacy: .public) pid=\(pair.peer.pid, privacy: .public) result=\(status, privacy: .public) display_len=\(lengths.display, privacy: .public) speech_len=\(lengths.speech, privacy: .public)")
10351035
return Self.reply(status)
10361036
}
10371037
guard let request = Self.decode(bytes) else { return answer("invalid") }

‎Sources/Core/AgentTrustStore.swift‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,11 @@ final class AgentTrustStore {
7878
}
7979

8080
static let maxClients = AgentPairing.slotCount
81-
static let maxRevoked = 64
81+
/// Revocations kept; the oldest fall out past this. A merge of two histories
82+
/// may hold up to twice as many until the next revocation trims it. At about
83+
/// 70 bytes per entry both stay well under the 256 KiB read limit.
84+
static let maxRevoked = 1024
85+
static let maxFileBytes = 256 * 1024
8286
// Approval does not expire. An approved app stays approved until the user
8387
// revokes it, its key changes, or it is launched by a different app.
8488

@@ -171,9 +175,21 @@ final class AgentTrustStore {
171175
for keyID in known where !Self.holds(loaded, .revoke(keyID)) && !pending.contains(.revoke(keyID)) {
172176
pending.append(.revoke(keyID))
173177
}
178+
// Revocations the file lacks go before the file's own, which are treated
179+
// as the newest: a later trim (oldest first) drops these before anything
180+
// the file recorded. Only a merge of more than twice the cap is trimmed
181+
// here, and a revocation trimmed away is no longer pending.
174182
var merged = loaded
175-
// Merging never trims the list: trimming here would push out entries that
176-
// the next pass adds back, until the newest revocations are lost.
183+
let missing = pending.compactMap { denial -> String? in
184+
guard case .revoke(let keyID) = denial, !loaded.revoked.contains(keyID) else { return nil }
185+
return keyID
186+
}
187+
merged.revoked = missing + loaded.revoked
188+
if merged.revoked.count > 2 * Self.maxRevoked {
189+
merged.revoked.removeFirst(merged.revoked.count - 2 * Self.maxRevoked)
190+
let kept = Set(merged.revoked)
191+
pending.removeAll { if case .revoke(let keyID) = $0 { return !kept.contains(keyID) }; return false }
192+
}
177193
for denial in pending { Self.apply(denial, to: &merged, trim: false) }
178194
guard merged != loaded else {
179195
// The file already says what the user asked for (or nothing is
@@ -414,7 +430,9 @@ final class AgentTrustStore {
414430
needsAdopt = true
415431
return false
416432
}
417-
guard let bytes = try? JSONEncoder().encode(next), (try? write(bytes, url)) != nil else {
433+
// Never replace the file with one that could not be read back.
434+
guard let bytes = try? JSONEncoder().encode(next), bytes.count <= Self.maxFileBytes,
435+
(try? write(bytes, url)) != nil else {
418436
if !pending.isEmpty { needsAdopt = true }
419437
return false
420438
}
@@ -450,11 +468,11 @@ final class AgentTrustStore {
450468
guard fstat(fd, &meta) == 0 else { return .unreadable(nil) }
451469
let fileStamp = stamp(meta)
452470
guard (meta.st_mode & S_IFMT) == S_IFREG, meta.st_uid == getuid(),
453-
meta.st_nlink == 1, meta.st_mode & 0o777 == 0o600, meta.st_size > 0, meta.st_size <= 256 * 1024
471+
meta.st_nlink == 1, meta.st_mode & 0o777 == 0o600, meta.st_size > 0, meta.st_size <= maxFileBytes
454472
else { return .unreadable(fileStamp) }
455473
// A read error may be passing; only bytes that do not parse keep the stamp.
456-
guard let bytes = try? reader.read(upToCount: 256 * 1024 + 1) else { return .unreadable(nil) }
457-
guard bytes.count <= 256 * 1024,
474+
guard let bytes = try? reader.read(upToCount: maxFileBytes + 1) else { return .unreadable(nil) }
475+
guard bytes.count <= maxFileBytes,
458476
let loaded = try? JSONDecoder().decode(File.self, from: bytes), loaded.version == 1,
459477
loaded.clients.count <= maxClients,
460478
loaded.clients.allSatisfy({ AgentPairingProof.keyID($0.publicKey) == $0.keyID }),

‎Sources/Core/TTSRuntime.swift‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,10 @@ enum TTSRuntime {
5151
/// The account's home from the user database, as the helper reads it.
5252
/// `NSHomeDirectory()` follows `CFFIXED_USER_HOME`, an environment variable.
5353
static let home: URL = {
54+
// The helper finds no key directory without it either; no environment
55+
// fallback, so the app and the helper never disagree on the folder.
5456
guard let entry = getpwuid(getuid()), let dir = entry.pointee.pw_dir else {
55-
return URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)
57+
preconditionFailure("no home directory for this account")
5658
}
5759
return URL(fileURLWithPath: String(cString: dir), isDirectory: true)
5860
}()

‎Tests/AgentTrustStoreTests.swift‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,28 @@ import Foundation
344344
precondition(cappedAgain.lookup(keyID: "R\(index)", host: hostA) == .revoked)
345345
}
346346

347+
// A standby that remembers older revocations takes over a file holding
348+
// newer ones: the merge keeps both, the file's own entries count as the
349+
// newest, and the next revocation does not push them out.
350+
let takeoverURL = directory.appendingPathComponent("takeover.json")
351+
var olderList = AgentTrustStore.File()
352+
olderList.revoked = (0..<64).map { "older-\($0)" }
353+
try AgentTrustStore.writePrivately(JSONEncoder().encode(olderList), takeoverURL)
354+
let rememberer = AgentTrustStore(url: takeoverURL)
355+
var newerList = AgentTrustStore.File()
356+
newerList.revoked = (0..<64).map { "newer-\($0)" }
357+
try AgentTrustStore.writePrivately(JSONEncoder().encode(newerList), takeoverURL)
358+
rememberer.adoptDisk(writeBack: false)
359+
precondition(rememberer.file.revoked == olderList.revoked + newerList.revoked)
360+
rememberer.adoptDisk()
361+
precondition(!rememberer.hasUnsavedDenials && rememberer.file.revoked == olderList.revoked + newerList.revoked)
362+
precondition(rememberer.forget(keyID: "latest"))
363+
let takenOver = AgentTrustStore(url: takeoverURL)
364+
for keyID in olderList.revoked + newerList.revoked + ["latest"] {
365+
precondition(takenOver.lookup(keyID: keyID, host: hostA) == .revoked)
366+
}
367+
precondition(takenOver.file.revoked.last == "latest")
368+
347369
// Reconnect policy shared with the helper.
348370
precondition(AgentReconnect.next(after: "receiving_only", attempt: 3) == .done)
349371
precondition(AgentReconnect.next(after: "ready", attempt: 0) == .done)

‎docs/mcp-explanation-drafts.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ Helpers/tts_mcp_client.py --helper "<앱>/Contents/Helpers/CodebasicAgentMCP" se
7373
- `connect host=<앱 식별자|unverified> key=<키 ID 앞 12자> lookup=<trusted|unknown|revoked|host_changed> result=<상태>`: 재연결 때 앱을 알아봤는지와 결과. 승인한 앱이 재시작 후 `lookup=trusted result=ready`(또는 `receiving_only`)이면 재승인 없이 연결된 것입니다.
7474
- `approve host=… client=… scope=<persistent|this_run> result=ok|store_failed`: 승인. `this_run`은 앱을 식별할 수 없어 이번 실행에만 허용한 경우입니다.
7575
- `revoke host=… client=… result=ok|unsaved`: 승인 철회.
76-
- `[AGENT-DRAFT] receipt host=… client=<승인 ID> pid=<도우미 프로세스> result=<accepted|duplicate|conflict|busy|rate_limited|instruction_required|unproven|invalid|upgrade_required|unconfirmed|disabled> display_len=<글자 수> speech_len=<글자 수>`: 대본 접수 결과. 본문은 남기지 않고 길이만 남깁니다.
76+
- `[AGENT-DRAFT] receipt host=… key=<키 ID 앞 12자> pid=<도우미 프로세스> result=<accepted|duplicate|conflict|busy|rate_limited|instruction_required|unproven|invalid|upgrade_required|unconfirmed|disabled> display_len=<글자 수> speech_len=<글자 수>`: 대본 접수 결과. 본문은 남기지 않고 길이만 남깁니다.
7777
- `[AGENT-SPEECH] request pid=<요청 프로세스> result=<accepted|duplicate|conflict|busy|invalid|unconfirmed> len=<글자 수>`: 음성 소켓 요청 결과. 이 소켓은 앱별 승인이 없으므로 앱 대신 요청한 프로세스 번호를 남깁니다.
7878

7979
### 에이전트 탭 자동 연결 (#31)

0 commit comments

Comments
 (0)