Skip to content

Commit 53e055f

Browse files
committed
Near the size limit, refuse writes that are not denials if they grow the file; revocations without a row fill to 1 KiB short of it; exact fit cost (#31)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015LJG7KnMPqFcfTZ8A1C2qh
1 parent d5f2840 commit 53e055f

3 files changed

Lines changed: 130 additions & 41 deletions

File tree

‎Sources/Core/AgentTrustStore.swift‎

Lines changed: 64 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,9 @@ final class AgentTrustStore {
7979

8080
static let maxClients = AgentPairing.slotCount
8181
/// The read and write limit. Revocations have no count limit; at about 70
82-
/// bytes each, this holds some 240,000 of them. Only past it does a write
83-
/// leave the oldest revocations of apps without an approval row out.
82+
/// bytes each, this holds some 240,000 of them. Near it, approvals are no
83+
/// longer saved, and a new revocation of an app without an approval row stays
84+
/// in effect for this run only rather than push a saved one out.
8485
static let defaultMaxFileBytes = 16 * 1024 * 1024
8586
let maxFileBytes: Int
8687
// Approval does not expire. An approved app stays approved until the user
@@ -200,28 +201,34 @@ final class AgentTrustStore {
200201
needsAdopt = false
201202
return
202203
}
203-
_ = commit(merged, byUser: false)
204+
_ = commit(merged, byUser: false, denial: true)
204205
}
205206

206207
private static func encodedSize(_ file: File) -> Int {
207208
(try? JSONEncoder().encode(file))?.count ?? Int.max
208209
}
209210

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.
211+
/// Room kept below the limit for writes that are not denials (an approval,
212+
/// a key change, a reconnect time, turning receipt on). Past the limit less
213+
/// this, such a write is refused if it would make the file larger, so this
214+
/// room is only ever used by denials.
213215
static let reserveBytes = 8 * 1024
214-
215-
/// What is written when `file` would pass the limit. A denial is always
216-
/// written and a saved revocation is never pushed out by this app's own
217-
/// writes:
216+
/// Room a denial that adds a revocation of an app without a row leaves free,
217+
/// for receipt offs (at most a few hundred bytes for all slots), so turning
218+
/// receipt off never has to push a saved revocation out.
219+
static let flagReserveBytes = 1024
220+
221+
/// What a denial writes when `file` would pass the limit less
222+
/// `flagReserveBytes`. A saved revocation is never pushed out by this app's
223+
/// own writes:
218224
/// - every revocation that removes a row of the last intact file;
219225
/// - that file's own revocations (newest first, up to the limit, which they
220226
/// 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.
227+
/// - revocations the user asked for that are not saved yet, then any others,
228+
/// newest first, up to the limit less `flagReserveBytes`.
222229
/// What is left out stays in effect for this run. Nil only if the rows'
223230
/// revocations alone do not fit, which the client limit rules out.
224-
private static func fitting(_ file: File, lastGood: File?, limit: Int) -> File? {
231+
private static func fitting(_ file: File, lastGood: File?, asked: Set<String>, limit: Int) -> File? {
225232
let rows = Set((lastGood?.clients ?? []).map(\.keyID))
226233
let own = Set(lastGood?.revoked ?? [])
227234
let required = file.revoked.filter { rows.contains($0) }
@@ -233,11 +240,13 @@ final class AgentTrustStore {
233240
// Takes entries in order while the exact size stays within `cap`.
234241
func take(_ entries: [String], cap: Int) {
235242
var size = encodedSize(fitted)
243+
var empty = kept.isEmpty
236244
for keyID in entries {
237-
// Each entry adds its quoted bytes and a comma.
238-
let cost = keyID.utf8.count + 3
245+
// Its quoted bytes, and a comma unless the list was empty.
246+
let cost = keyID.utf8.count + 2 + (empty ? 0 : 1)
239247
guard size + cost <= cap else { break }
240248
size += cost
249+
empty = false
241250
kept.insert(keyID)
242251
}
243252
fitted.revoked = build()
@@ -247,9 +256,13 @@ final class AgentTrustStore {
247256
fitted.revoked = build()
248257
}
249258
}
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))
259+
let rest = file.revoked.filter { !rows.contains($0) }
260+
take(Array(rest.filter { own.contains($0) }.reversed()), cap: limit)
261+
let small = limit - flagReserveBytes
262+
take(Array(rest.filter { !own.contains($0) && asked.contains($0) }.reversed()),
263+
cap: max(encodedSize(fitted), small))
264+
take(Array(rest.filter { !own.contains($0) && !asked.contains($0) }.reversed()),
265+
cap: max(encodedSize(fitted), small))
253266
return fitted
254267
}
255268

@@ -377,7 +390,7 @@ final class AgentTrustStore {
377390
guard let index = file.clients.firstIndex(where: { $0.id == id }) else { return }
378391
var next = file
379392
next.clients[index].lastSeen = now()
380-
_ = commit(next, byUser: false)
393+
_ = commit(next, byUser: false, denial: false)
381394
}
382395

383396
/// Forgetting tombstones the key, so the same credential cannot come back
@@ -433,7 +446,7 @@ final class AgentTrustStore {
433446
private func deny(_ next: File, _ denial: Denial) -> Bool {
434447
if !pending.contains(denial) { pending.append(denial) }
435448
file = next
436-
if !closedByDisk { _ = commit(next, byUser: false) }
449+
if !closedByDisk { _ = commit(next, byUser: false, denial: true) }
437450
guard pending.contains(denial) else { return true }
438451
// Try again at the next check, even if nothing else changes the file.
439452
if !closedByDisk || readFailed { needsAdopt = true }
@@ -447,7 +460,7 @@ final class AgentTrustStore {
447460
/// on top) and the grant is refused.
448461
private func grant(_ next: File, byUser: Bool) -> Bool {
449462
let before = file
450-
guard commit(next, byUser: byUser) else { return false }
463+
guard commit(next, byUser: byUser, denial: false) else { return false }
451464
guard lastCommitSeen else {
452465
// Nothing granted stays in memory, even if the file is now gone.
453466
file = before
@@ -461,7 +474,7 @@ final class AgentTrustStore {
461474
/// file shows up there, its own writes do not settle pending denials.
462475
private var recreated = false
463476

464-
private func commit(_ next: File, byUser: Bool) -> Bool {
477+
private func commit(_ next: File, byUser: Bool, denial: Bool) -> Bool {
465478
lastCommitSeen = false
466479
// A file written where the last one vanished may be replaced by the
467480
// original again, so pending denials are not settled by it.
@@ -471,24 +484,42 @@ final class AgentTrustStore {
471484
needsAdopt = true
472485
return false
473486
}
474-
// Never replace the file with one that could not be read back. Past the
487+
// Never replace the file with one that could not be read back. Near the
475488
// limit only the most important revocations are written; the rest stay in
476489
// effect here and pending.
477490
var toWrite = next
478-
if Self.encodedSize(next) > maxFileBytes - Self.reserveBytes {
479-
guard let fitted = Self.fitting(next, lastGood: lastGood, limit: maxFileBytes) else {
491+
if denial || readFailed {
492+
// A denial, or the user's turning receipt on over an unreadable file.
493+
if Self.encodedSize(next) > maxFileBytes - Self.flagReserveBytes {
494+
let asked = Set(pending.compactMap { item -> String? in
495+
if case .revoke(let keyID) = item { return keyID }
496+
return nil
497+
})
498+
guard let fitted = Self.fitting(next, lastGood: lastGood, asked: asked, limit: maxFileBytes) else {
499+
if !pending.isEmpty { needsAdopt = true }
500+
return false
501+
}
502+
toWrite = fitted
503+
}
504+
} else if Self.encodedSize(next) > maxFileBytes - Self.reserveBytes {
505+
// Not a denial: only the revocations the file holds are written, and
506+
// the file may not grow past the limit less the reserve.
507+
let base = onDisk ?? lastGood
508+
let keep = Set((base?.revoked ?? []) + (base?.clients ?? []).map(\.keyID))
509+
toWrite.revoked = next.revoked.filter { keep.contains($0) }
510+
let bound = min(maxFileBytes, max(maxFileBytes - Self.reserveBytes, base.map(Self.encodedSize) ?? 0))
511+
guard Self.encodedSize(toWrite) <= bound else {
480512
if !pending.isEmpty { needsAdopt = true }
481513
return false
482514
}
483-
toWrite = fitted
484-
if !readFailed, !closedByDisk, toWrite == onDisk, diskStamp != nil, Self.stamp(url) == diskStamp {
485-
// Nothing more fits: the file already holds all it can.
486-
file = next
487-
needsAdopt = false
488-
lastCommitSeen = true
489-
if !recreated { pending.removeAll { Self.holds(toWrite, $0) } }
490-
return true
491-
}
515+
}
516+
if toWrite != next, !readFailed, !closedByDisk, toWrite == onDisk, diskStamp != nil, Self.stamp(url) == diskStamp {
517+
// Nothing more fits: the file already holds all it can.
518+
file = next
519+
needsAdopt = false
520+
lastCommitSeen = true
521+
if !recreated { pending.removeAll { Self.holds(toWrite, $0) } }
522+
return true
492523
}
493524
guard let bytes = try? JSONEncoder().encode(toWrite), bytes.count <= maxFileBytes,
494525
(try? write(bytes, url)) != nil else {

‎Tests/AgentTrustStoreTests.swift‎

Lines changed: 65 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -397,9 +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 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.
400+
// Near the limit (a file from elsewhere, within 1 KiB of it): a new
401+
// revocation of an app without a row stays in effect here and pending,
402+
// and nothing the file held is pushed out for it.
403403
let smallLimit = 256 * 1024
404404
let nearLimit = (0..<3900).map { String(format: "%064d", $0) }
405405
var fullFile = AgentTrustStore.File()
@@ -408,7 +408,7 @@ import Foundation
408408
let limitURL = directory.appendingPathComponent("limit.json")
409409
try AgentTrustStore.writePrivately(JSONEncoder().encode(fullFile), limitURL)
410410
let limitBefore = try Data(contentsOf: limitURL)
411-
precondition(limitBefore.count <= smallLimit && limitBefore.count > smallLimit - AgentTrustStore.reserveBytes)
411+
precondition(limitBefore.count <= smallLimit && limitBefore.count > smallLimit - AgentTrustStore.flagReserveBytes)
412412
let atLimit = AgentTrustStore(url: limitURL, maxFileBytes: smallLimit)
413413
let extraKey = "y" + String(repeating: "0", count: 63)
414414
precondition(!atLimit.forget(keyID: extraKey) && atLimit.hasUnsavedDenials)
@@ -428,9 +428,9 @@ import Foundation
428428
precondition(atLimit.hasUnsavedDenials && atLimit.lookup(keyID: extraKey, host: hostA) == .revoked)
429429

430430
// 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.
431+
// writes: they stop 1 KiB short of the limit, so turning another app's
432+
// receipt off afterwards still saves and never pushes the first saved
433+
// revocation out.
434434
let growURL = directory.appendingPathComponent("grow.json")
435435
let growing = AgentTrustStore(url: growURL, maxFileBytes: smallLimit)
436436
let growApp = try growing.trust(publicKey: P256.Signing.PrivateKey().publicKey.x963Representation, label: "G", host: hostA)
@@ -529,6 +529,64 @@ import Foundation
529529
let capRevoked = AgentTrustStore(url: capURL2, maxFileBytes: smallLimit)
530530
precondition(capRevoked.clients.isEmpty && capRevoked.lookup(keyID: capApp.keyID, host: hostA) == .revoked)
531531

532+
// At the limit less the reserve (a restored copy from elsewhere): the
533+
// user's revocation of an app with no row in it is still saved, but a new
534+
// approval, which would make the file larger, is refused and the file
535+
// stays as it was.
536+
let softURL = directory.appendingPathComponent("soft.json")
537+
let softStore = AgentTrustStore(url: softURL, maxFileBytes: smallLimit)
538+
_ = try softStore.trust(publicKey: P256.Signing.PrivateKey().publicKey.x963Representation, label: "S", host: hostA)
539+
var softFile = try JSONDecoder().decode(AgentTrustStore.File.self, from: Data(contentsOf: softURL))
540+
var softIndex = 0
541+
while try JSONEncoder().encode(softFile).count <= smallLimit - AgentTrustStore.reserveBytes + 200 {
542+
softFile.revoked.append(String(format: "s%063d", softIndex))
543+
softIndex += 1
544+
}
545+
try AgentTrustStore.writePrivately(JSONEncoder().encode(softFile), softURL)
546+
softStore.adoptDisk()
547+
let missingRow = "m" + String(repeating: "0", count: 63)
548+
precondition(softStore.forget(keyID: missingRow) && !softStore.hasUnsavedDenials)
549+
let softSaved = AgentTrustStore(url: softURL, maxFileBytes: smallLimit)
550+
precondition(softSaved.lookup(keyID: missingRow, host: hostA) == .revoked)
551+
let softBytes = try Data(contentsOf: softURL)
552+
var approvalRefused = false
553+
do {
554+
_ = try softStore.trust(publicKey: P256.Signing.PrivateKey().publicKey.x963Representation, label: "N", host: hostB)
555+
} catch {
556+
approvalRefused = (error as? AgentTrustStore.Failure) == .unwritable
557+
}
558+
precondition(approvalRefused && softStore.clients.count == 1)
559+
let softAfter = try Data(contentsOf: softURL)
560+
precondition(softAfter == softBytes)
561+
562+
// Approving and revoking apps again and again stops below the limit less
563+
// the reserve: every revocation is saved and the first one stays.
564+
let cycleURL = directory.appendingPathComponent("cycle.json")
565+
let cycling = AgentTrustStore(url: cycleURL, maxFileBytes: smallLimit)
566+
let firstCycled = "q" + String(repeating: "0", count: 63)
567+
precondition(cycling.forget(keyID: firstCycled))
568+
var cycleFile = try JSONDecoder().decode(AgentTrustStore.File.self, from: Data(contentsOf: cycleURL))
569+
var cycleIndex = 0
570+
while try JSONEncoder().encode(cycleFile).count + 67 <= smallLimit - AgentTrustStore.reserveBytes - 2000 {
571+
cycleFile.revoked.append(String(format: "c%063d", cycleIndex))
572+
cycleIndex += 1
573+
}
574+
try AgentTrustStore.writePrivately(JSONEncoder().encode(cycleFile), cycleURL)
575+
cycling.adoptDisk()
576+
var cycledKeys: [String] = []
577+
while cycledKeys.count < 200,
578+
let cycled = try? cycling.trust(publicKey: P256.Signing.PrivateKey().publicKey.x963Representation,
579+
label: "R", host: hostB) {
580+
precondition(cycling.forget(cycled.id))
581+
cycledKeys.append(cycled.keyID)
582+
}
583+
precondition(!cycledKeys.isEmpty && cycledKeys.count < 200 && !cycling.hasUnsavedDenials)
584+
let cycledAgain = AgentTrustStore(url: cycleURL, maxFileBytes: smallLimit)
585+
precondition(cycledAgain.lookup(keyID: firstCycled, host: hostA) == .revoked && cycledAgain.clients.isEmpty)
586+
for keyID in cycledKeys { precondition(cycledAgain.lookup(keyID: keyID, host: hostB) == .revoked) }
587+
let cycleBytes = try Data(contentsOf: cycleURL)
588+
precondition(cycleBytes.count <= smallLimit - AgentTrustStore.reserveBytes)
589+
532590
// Reconnect policy shared with the helper.
533591
precondition(AgentReconnect.next(after: "receiving_only", attempt: 3) == .done)
534592
precondition(AgentReconnect.next(after: "ready", attempt: 0) == .done)

0 commit comments

Comments
 (0)