Skip to content

Commit b42d5ad

Browse files
committed
Keep a reserve below the size limit so a denial never pushes out a saved revocation; close SQLite once on a failed open (#31, #4)
Answers the round-26 Codex finding: new revocations without a row are saved only up to the limit less an 8 KiB reserve, and a saved revocation is never pushed out by this app's own writes. Receipt and row changes use the reserve, so they always save. Revocations that remove a row are always written. Test: a revocation saved at normal size survives revocations piling up to the soft limit and another app's receipt off. Also: SQLiteDraftStore no longer closes its handle twice when setup fails (deinit runs for a failed init). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015LJG7KnMPqFcfTZ8A1C2qh
1 parent 804d4a3 commit b42d5ad

4 files changed

Lines changed: 78 additions & 49 deletions

File tree

‎Sources/Core/AgentTrustStore.swift‎

Lines changed: 34 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -207,43 +207,49 @@ final class AgentTrustStore {
207207
(try? JSONEncoder().encode(file))?.count ?? Int.max
208208
}
209209

210+
/// Room kept below the limit for changes that are not revocations (one
211+
/// app's receipt, the overall choice, an approval row), so saving them never
212+
/// has to push a saved revocation out.
213+
static let reserveBytes = 8 * 1024
214+
210215
/// What is written when `file` would pass the limit. A denial is always
211-
/// written: every revocation that removes a row of the last intact file is
212-
/// kept, then that file's own revocations, newest first, then the newest
213-
/// others. Only revocations of apps that have no approval row there are left
214-
/// out, oldest first; memory keeps all of them for this run. Nil only if the
215-
/// rows' revocations alone do not fit, which the client limit rules out.
216+
/// written and a saved revocation is never pushed out by this app's own
217+
/// writes:
218+
/// - every revocation that removes a row of the last intact file;
219+
/// - that file's own revocations (newest first, up to the limit, which they
220+
/// only miss if that file came from elsewhere already at the limit);
221+
/// - other revocations, newest first, only up to the limit less the reserve.
222+
/// What is left out stays in effect for this run. Nil only if the rows'
223+
/// revocations alone do not fit, which the client limit rules out.
216224
private static func fitting(_ file: File, lastGood: File?, limit: Int) -> File? {
217225
let rows = Set((lastGood?.clients ?? []).map(\.keyID))
218226
let own = Set(lastGood?.revoked ?? [])
219227
let required = file.revoked.filter { rows.contains($0) }
220-
let fromFile = file.revoked.filter { own.contains($0) && !rows.contains($0) }.reversed()
221-
let others = file.revoked.filter { !own.contains($0) && !rows.contains($0) }.reversed()
222-
// Highest priority first.
223-
var optional = Array(fromFile) + Array(others)
224228
var fitted = file
225-
func build() -> [String] {
226-
let kept = Set(required).union(optional)
227-
return file.revoked.filter { kept.contains($0) }
228-
}
229229
fitted.revoked = required
230230
guard encodedSize(fitted) <= limit else { return nil }
231-
// Each entry adds its quoted bytes and a comma; take what that estimate
232-
// allows, then drop the lowest priority until the exact size fits.
233-
var budget = limit - encodedSize(fitted)
234-
var count = 0
235-
for keyID in optional {
236-
let cost = keyID.utf8.count + 3
237-
guard cost <= budget else { break }
238-
budget -= cost
239-
count += 1
240-
}
241-
optional = Array(optional.prefix(count))
242-
fitted.revoked = build()
243-
while encodedSize(fitted) > limit, !optional.isEmpty {
244-
optional.removeLast()
231+
var kept = Set(required)
232+
func build() -> [String] { file.revoked.filter { kept.contains($0) } }
233+
// Takes entries in order while the exact size stays within `cap`.
234+
func take(_ entries: [String], cap: Int) {
235+
var size = encodedSize(fitted)
236+
for keyID in entries {
237+
// Each entry adds its quoted bytes and a comma.
238+
let cost = keyID.utf8.count + 3
239+
guard size + cost <= cap else { break }
240+
size += cost
241+
kept.insert(keyID)
242+
}
245243
fitted.revoked = build()
244+
var taken = entries.filter { kept.contains($0) }
245+
while encodedSize(fitted) > cap, let last = taken.popLast() {
246+
kept.remove(last)
247+
fitted.revoked = build()
248+
}
246249
}
250+
take(Array(file.revoked.filter { own.contains($0) && !rows.contains($0) }.reversed()), cap: limit)
251+
take(Array(file.revoked.filter { !own.contains($0) && !rows.contains($0) }.reversed()),
252+
cap: max(encodedSize(fitted), limit - reserveBytes))
247253
return fitted
248254
}
249255

@@ -469,7 +475,7 @@ final class AgentTrustStore {
469475
// limit only the most important revocations are written; the rest stay in
470476
// effect here and pending.
471477
var toWrite = next
472-
if Self.encodedSize(next) > maxFileBytes {
478+
if Self.encodedSize(next) > maxFileBytes - Self.reserveBytes {
473479
guard let fitted = Self.fitting(next, lastGood: lastGood, limit: maxFileBytes) else {
474480
if !pending.isEmpty { needsAdopt = true }
475481
return false

‎Sources/Core/DraftStore.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,9 @@ final class SQLiteDraftStore: DraftStoring {
115115
fingerprint TEXT, body BLOB NOT NULL);
116116
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT);
117117
""") else {
118+
// deinit still runs for a failed init; close the handle only once.
118119
sqlite3_close(db)
120+
db = nil
119121
return nil
120122
}
121123
}

‎Tests/AgentTrustStoreTests.swift‎

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -397,8 +397,9 @@ import Foundation
397397
precondition(bigAgain.clients.isEmpty && bigAgain.file.revoked.count == bigList.count + 1)
398398
precondition(bigAgain.lookup(keyID: bigApp.keyID, host: hostA) == .revoked)
399399
for keyID in bigList { precondition(bigAgain.lookup(keyID: keyID, host: hostA) == .revoked) }
400-
// Near the read limit: the next revocation stays in effect here but the
401-
// file is not replaced by one that could not be read back.
400+
// Near the limit (a file from elsewhere, above the limit less the reserve):
401+
// a new revocation of an app without a row stays in effect here and
402+
// pending, and nothing the file held is pushed out for it.
402403
let smallLimit = 256 * 1024
403404
let nearLimit = (0..<3900).map { String(format: "%064d", $0) }
404405
var fullFile = AgentTrustStore.File()
@@ -407,32 +408,52 @@ import Foundation
407408
let limitURL = directory.appendingPathComponent("limit.json")
408409
try AgentTrustStore.writePrivately(JSONEncoder().encode(fullFile), limitURL)
409410
let limitBefore = try Data(contentsOf: limitURL)
410-
precondition(limitBefore.count <= smallLimit)
411+
precondition(limitBefore.count <= smallLimit && limitBefore.count > smallLimit - AgentTrustStore.reserveBytes)
411412
let atLimit = AgentTrustStore(url: limitURL, maxFileBytes: smallLimit)
412-
var overflow = 0
413-
while (try JSONEncoder().encode(atLimit.file)).count <= smallLimit - 67 {
414-
overflow += 1
415-
precondition(atLimit.forget(keyID: String(format: "x%063d", overflow)))
416-
}
417-
precondition(!atLimit.forget(keyID: "y" + String(repeating: "0", count: 63)) && atLimit.hasUnsavedDenials)
418-
precondition(atLimit.lookup(keyID: "y" + String(repeating: "0", count: 63), host: hostA) == .revoked)
413+
let extraKey = "y" + String(repeating: "0", count: 63)
414+
precondition(!atLimit.forget(keyID: extraKey) && atLimit.hasUnsavedDenials)
415+
precondition(atLimit.lookup(keyID: extraKey, host: hostA) == .revoked)
419416
let limitAfter = try Data(contentsOf: limitURL)
420-
precondition(limitAfter.count <= smallLimit && AgentTrustStore(url: limitURL, maxFileBytes: smallLimit).lookup(keyID: String(format: "x%063d", overflow), host: hostA) == .revoked)
417+
precondition(limitAfter == limitBefore)
421418

422419
// An unreadable file is never taken for the last good one: turning receipt
423-
// on replaces it even when the fitted list equals what was read before.
420+
// on replaces it, keeping every revocation the last readable file held.
424421
precondition(chmod(limitURL.path, 0o644) == 0)
425422
atLimit.adoptDisk()
426423
precondition(atLimit.readFailed)
427424
precondition(atLimit.setAutoReceive(true) && !atLimit.readFailed && atLimit.autoReceive)
428425
let replaced = AgentTrustStore(url: limitURL, maxFileBytes: smallLimit)
429426
precondition(!replaced.readFailed && replaced.autoReceive)
430-
// Replacing it keeps every revocation the last readable file held (the
431-
// oldest too); only what never fit is left out, and it stays pending.
432-
for keyID in nearLimit + (1...overflow).map({ String(format: "x%063d", $0) }) {
433-
precondition(replaced.lookup(keyID: keyID, host: hostA) == .revoked)
427+
for keyID in nearLimit { precondition(replaced.lookup(keyID: keyID, host: hostA) == .revoked) }
428+
precondition(atLimit.hasUnsavedDenials && atLimit.lookup(keyID: extraKey, host: hostA) == .revoked)
429+
430+
// Saved at a normal size, then revocations pile up through this app's own
431+
// writes: they stop at the limit less the reserve, so turning another
432+
// app's receipt off afterwards still saves and never pushes the first
433+
// saved revocation out.
434+
let growURL = directory.appendingPathComponent("grow.json")
435+
let growing = AgentTrustStore(url: growURL, maxFileBytes: smallLimit)
436+
let growApp = try growing.trust(publicKey: P256.Signing.PrivateKey().publicKey.x963Representation, label: "G", host: hostA)
437+
let firstSaved = "k" + String(repeating: "0", count: 63)
438+
precondition(growing.forget(keyID: firstSaved))
439+
var grown = try JSONDecoder().decode(AgentTrustStore.File.self, from: Data(contentsOf: growURL))
440+
var growIndex = 0
441+
while try JSONEncoder().encode(grown).count + 67 <= smallLimit - AgentTrustStore.reserveBytes - 300 {
442+
grown.revoked.append(String(format: "g%063d", growIndex))
443+
growIndex += 1
444+
}
445+
try AgentTrustStore.writePrivately(JSONEncoder().encode(grown), growURL)
446+
growing.adoptDisk()
447+
var growMore = 0
448+
while growing.forget(keyID: String(format: "h%063d", growMore)) { growMore += 1 }
449+
precondition(growMore >= 1 && growing.hasUnsavedDenials)
450+
precondition(growing.setReceiptEnabled(false, for: growApp.id))
451+
let grownAgain = AgentTrustStore(url: growURL, maxFileBytes: smallLimit)
452+
precondition(grownAgain.lookup(keyID: firstSaved, host: hostA) == .revoked)
453+
precondition(grownAgain.clients.count == 1 && !grownAgain.clients[0].receiptEnabled)
454+
for index in 0..<growMore {
455+
precondition(grownAgain.lookup(keyID: String(format: "h%063d", index), host: hostA) == .revoked)
434456
}
435-
precondition(atLimit.hasUnsavedDenials)
436457

437458
// Two histories that each fit but not together: this instance knows 2,000
438459
// revocations ending with K, and a restored backup holds 2,000 others plus
@@ -475,9 +496,9 @@ import Foundation
475496
let mergedBytes = try Data(contentsOf: mergeURL)
476497
precondition(mergedBytes.count <= smallLimit)
477498

478-
// A file exactly at the limit: turning one app's receipt off (one byte
479-
// more) is still saved, by leaving out the oldest revocation of an app
480-
// that has no row; the newest stay.
499+
// A file from elsewhere exactly at the limit: turning one app's receipt
500+
// off (one byte more) is still saved, by leaving out its oldest
501+
// revocation of an app that has no row; the newest stay.
481502
let capURL2 = directory.appendingPathComponent("at-cap.json")
482503
let capStore = AgentTrustStore(url: capURL2, maxFileBytes: smallLimit)
483504
let capApp = try capStore.trust(publicKey: P256.Signing.PrivateKey().publicKey.x963Representation, label: "A", host: hostA)

‎docs/mcp-explanation-drafts.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ Helpers/tts_mcp_client.py --helper "<앱>/Contents/Helpers/CodebasicAgentMCP" se
8484

8585
승인·받기 설정은 `agent-approvals.json`에 저장하며, 페어링 소켓을 가진 앱 인스턴스만 바꿉니다. 같은 앱을 하나 더 띄우면 그 창에서는 바꿀 수 없다고 안내하고 `policy change refused reason=not_socket_owner`를 남깁니다. 소켓을 넘겨받을 때, 탭을 열 때, 도우미의 상태 확인·증명 때, 설정을 바꾸기 직전에 파일이 자신이 마지막으로 읽거나 쓴 뒤 바뀌었으면 다시 읽습니다(`policy adopt reason=external_change`). 그래서 이미 연결된 도우미에도 다른 인스턴스가 저장한 철회·끄기가 바로 적용됩니다. 파일을 쓴 직후 다시 읽어 방금 쓴 내용일 때만 그 상태를 기억하고, 아니면 다음 확인에서 다시 읽습니다.
8686

87-
승인을 알고 있던 상태에서 파일이 사라졌거나 읽을 수 없으면 승인 없음·받기 꺼짐으로 보고, 철회한 키는 계속 철회 상태로 둡니다. 철회는 되돌릴 수 없으므로, 이 실행이 아는 철회는 파일을 다시 읽을 때마다 그 위에 다시 적용합니다. 철회 목록은 개수 상한 없이 모두 보관합니다(상한이 있으면 밀려난 키가 옛 사본 복원으로 되살아나기 때문). 파일 크기 상한은 16 MiB(철회 약 24만 개)입니다. 이를 넘게 되어도 사용자의 거부(받기 끄기, 철회)는 항상 저장합니다. 마지막으로 온전히 읽은 파일의 승인 행을 지우는 철회는 모두 쓰고, 그다음 그 파일의 철회, 이 실행이 아는 다른 철회 순으로 각각 최근 것부터 넣습니다. 그래서 빠지는 것은 승인 행이 없는 앱의 가장 오래된 철회뿐이며, 빠진 철회도 이 실행에서는 계속 적용됩니다. 철회 전에 만든 옛 사본이 되돌아와도 철회한 앱은 다시 연결되지 않고, 앱은 철회를 넣어 파일을 다시 저장합니다. 읽을 수 없는 파일은 앱이 덮어쓰지 않고 탭에 안내하며, 다시 읽히면 그 내용을 채택합니다. 이때 끊긴 도우미는 철회로 보지 않고 다시 신호를 받습니다. 저장하지 못한 사용자의 거부(전체 받기 끄기, 앱별 받기 끄기, 승인 철회)는 이 인스턴스에서 바로 적용되고, 파일을 다시 읽을 때 그 내용 위에 다시 적용해 저장합니다. 파일을 읽을 수 없는 동안 사용자가 전체 받기를 켜면 승인 목록을 비운 새 설정으로 파일을 바꿉니다. 화면 잠금과 콘솔 사용자 전환은 따로 추적해 둘 다 풀렸을 때만 받기를 다시 엽니다.
87+
승인을 알고 있던 상태에서 파일이 사라졌거나 읽을 수 없으면 승인 없음·받기 꺼짐으로 보고, 철회한 키는 계속 철회 상태로 둡니다. 철회는 되돌릴 수 없으므로, 이 실행이 아는 철회는 파일을 다시 읽을 때마다 그 위에 다시 적용합니다. 철회 목록은 개수 상한 없이 모두 보관합니다(상한이 있으면 밀려난 키가 옛 사본 복원으로 되살아나기 때문). 파일 크기 상한은 16 MiB(철회 약 24만 개)입니다. 새 철회는 상한에서 8 KiB를 남긴 곳까지만 저장하고, 남긴 자리는 받기 끄기·켜기와 승인 행 같은 다른 변경에 씁니다. 그래서 사용자의 받기 끄기는 상한 근처에서도 항상 저장되고, 이미 저장된 철회를 밀어내지 않습니다. 승인 행이 있는 앱의 철회는 언제나 저장합니다. 자리가 없어 저장하지 못한 철회도 이 실행에서는 계속 적용됩니다. 철회 전에 만든 옛 사본이 되돌아와도 철회한 앱은 다시 연결되지 않고, 앱은 철회를 넣어 파일을 다시 저장합니다. 읽을 수 없는 파일은 앱이 덮어쓰지 않고 탭에 안내하며, 다시 읽히면 그 내용을 채택합니다. 이때 끊긴 도우미는 철회로 보지 않고 다시 신호를 받습니다. 저장하지 못한 사용자의 거부(전체 받기 끄기, 앱별 받기 끄기, 승인 철회)는 이 인스턴스에서 바로 적용되고, 파일을 다시 읽을 때 그 내용 위에 다시 적용해 저장합니다. 파일을 읽을 수 없는 동안 사용자가 전체 받기를 켜면 승인 목록을 비운 새 설정으로 파일을 바꿉니다. 화면 잠금과 콘솔 사용자 전환은 따로 추적해 둘 다 풀렸을 때만 받기를 다시 엽니다.
8888

8989
이전 빌드(#13 통합 브랜치, 배포된 적 없음)는 `agent-clients.json`을 썼습니다. 이 파일은 가져오지 않으므로 그 빌드에서 승인한 앱은 한 번 다시 승인해야 하며, 이전 빌드를 함께 띄워도 서로 다른 파일을 써서 철회나 끄기가 되살아나지 않습니다. 저장하지 못한 거부는 다음 확인(도우미 상태 확인, 탭 열기, 설정 변경) 때 다시 저장을 시도합니다. 읽을 수 없는 파일을 이번 클릭에서 처음 발견했다면 받기를 켜지 않고 먼저 안내하며, 다시 켜야 빈 목록으로 바꿉니다.
9090

0 commit comments

Comments
 (0)