@@ -78,11 +78,12 @@ final class AgentTrustStore {
7878 }
7979
8080 static let maxClients = AgentPairing . slotCount
81- /// Revocations are never dropped: any cut-off would let a restored older
82- /// copy bring a dropped key back. At about 70 bytes each, thousands fit
83- /// under this read limit; a file that would exceed it is not written, and
84- /// the denial stays pending (in effect here) and is retried.
85- static let maxFileBytes = 256 * 1024
81+ /// The read and write limit. Revocations have no count limit; at about 70
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.
85+ static let defaultMaxFileBytes = 16 * 1024 * 1024
86+ let maxFileBytes : Int
8687 // Approval does not expire. An approved app stays approved until the user
8788 // revokes it, its key changes, or it is launched by a different app.
8889
@@ -107,15 +108,18 @@ final class AgentTrustStore {
107108 /// Builds before this one (never released) used another file name; their
108109 /// approvals are not imported, so those builds never share a file with this one.
109110 init ( url : URL , now : @escaping ( ) -> Date = Date . init ,
110- write : @escaping ( Data , URL ) throws -> Void = AgentTrustStore . writePrivately ) {
111+ write : @escaping ( Data , URL ) throws -> Void = AgentTrustStore . writePrivately ,
112+ maxFileBytes : Int = AgentTrustStore . defaultMaxFileBytes ) {
111113 self . url = url
114+ self . maxFileBytes = maxFileBytes
112115 self . now = now
113116 self . write = write
114- switch Self . readDisk ( url ) {
117+ switch Self . readDisk ( url , limit : maxFileBytes ) {
115118 case . loaded ( let loaded , let stamp ) :
116119 file = loaded
117120 onDisk = loaded
118121 lastGood = loaded
122+ savedRevoked = Set ( loaded . revoked )
119123 loadedExisting = true
120124 diskStamp = stamp
121125 case . missing :
@@ -144,7 +148,7 @@ final class AgentTrustStore {
144148 /// write stays pending for when it takes the socket over.
145149 func adoptDisk ( writeBack : Bool = true ) {
146150 let known = file . revoked
147- let disk = Self . readDisk ( url )
151+ let disk = Self . readDisk ( url , limit : maxFileBytes )
148152 guard case . loaded ( let loaded , let stamp ) = disk else {
149153 // What was last read is no longer what the file holds.
150154 onDisk = nil
@@ -171,6 +175,7 @@ final class AgentTrustStore {
171175 diskStamp = stamp
172176 onDisk = loaded
173177 lastGood = loaded
178+ savedRevoked . formUnion ( loaded . revoked )
174179 needsAdopt = false
175180 // Revocations are never undone (a revoked key cannot be approved again),
176181 // so every revocation this run knows is kept, also over a restored older
@@ -198,46 +203,70 @@ final class AgentTrustStore {
198203 needsAdopt = false
199204 return
200205 }
201- _ = commit ( merged , byUser : false )
206+ _ = commit ( merged , byUser : false , denial : true )
202207 }
203208
204209 private static func encodedSize ( _ file : File ) -> Int {
205210 ( try? JSONEncoder ( ) . encode ( file ) ) ? . count ?? Int . max
206211 }
207212
208- /// What is written when `file` would pass the read limit: every revocation
209- /// that removes a row of the file last read (that app would connect again),
210- /// every revocation that file already holds, then the newest others that fit.
211- /// Nil when even the first two do not fit. Memory keeps all of them either way.
212- private static func fitting ( _ file : File , onDisk : File ? ) -> File ? {
213- let rows = Set ( ( onDisk ? . clients ?? [ ] ) . map ( \. keyID ) )
214- let own = Set ( onDisk ? . revoked ?? [ ] )
215- let required = file . revoked . filter { rows . contains ( $0 ) || own . contains ( $0 ) }
216- // Newest first, so the oldest are the first left out.
217- var others = Array ( file . revoked . filter { ! rows . contains ( $0 ) && ! own . contains ( $0 ) } . reversed ( ) )
213+ /// Room kept below the limit for writes that are not denials (an approval,
214+ /// a key change, a reconnect time, turning receipt on). Past the limit less
215+ /// this, such a write is refused if it would make the file larger, so this
216+ /// room is only ever used by denials.
217+ static let reserveBytes = 8 * 1024
218+ /// Room a denial that adds a revocation of an app without a row leaves free,
219+ /// for receipt offs (at most a few hundred bytes for all slots), so turning
220+ /// receipt off never has to push a saved revocation out.
221+ static let flagReserveBytes = 1024
222+
223+ /// What a denial writes when `file` would pass the limit less
224+ /// `flagReserveBytes`. A saved revocation is never pushed out by this app's
225+ /// own writes:
226+ /// - every revocation that removes a row of the last intact file;
227+ /// - that file's own revocations, then those this run saw saved in an earlier
228+ /// file (a restored copy may predate them), newest first, up to the limit:
229+ /// they only miss it if a file came from elsewhere already near the limit;
230+ /// - revocations the user asked for that are not saved yet, then any others,
231+ /// newest first, up to the limit less `flagReserveBytes`.
232+ /// What is left out stays in effect for this run. Nil only if the rows'
233+ /// revocations alone do not fit, which the client limit rules out.
234+ private static func fitting ( _ file : File , lastGood : File ? , saved : Set < String > , asked : Set < String > , limit : Int ) -> File ? {
235+ let rows = Set ( ( lastGood ? . clients ?? [ ] ) . map ( \. keyID ) )
236+ let own = Set ( lastGood ? . revoked ?? [ ] )
237+ let required = file . revoked . filter { rows . contains ( $0 ) }
218238 var fitted = file
219- func build ( ) -> [ String ] {
220- let kept = Set ( required ) . union ( others )
221- return file . revoked . filter { kept . contains ( $0 ) }
222- }
223239 fitted . revoked = required
224- guard encodedSize ( fitted ) <= maxFileBytes else { return nil }
225- // Each entry adds its quoted bytes and a comma; trim to that estimate,
226- // then drop the oldest others until the exact size fits.
227- var budget = maxFileBytes - encodedSize ( fitted )
228- var count = 0
229- for keyID in others {
230- let cost = keyID . utf8 . count + 3
231- guard cost <= budget else { break }
232- budget -= cost
233- count += 1
234- }
235- others = Array ( others . prefix ( count ) )
236- fitted . revoked = build ( )
237- while encodedSize ( fitted ) > maxFileBytes , ! others . isEmpty {
238- others . removeLast ( )
240+ guard encodedSize ( fitted ) <= limit else { return nil }
241+ var kept = Set ( required )
242+ func build ( ) -> [ String ] { file . revoked . filter { kept . contains ( $0 ) } }
243+ // Takes entries in order while the exact size stays within `cap`.
244+ func take ( _ entries : [ String ] , cap : Int ) {
245+ var size = encodedSize ( fitted )
246+ var empty = kept . isEmpty
247+ for keyID in entries {
248+ // Its quoted bytes, and a comma unless the list was empty.
249+ let cost = keyID . utf8 . count + 2 + ( empty ? 0 : 1 )
250+ guard size + cost <= cap else { break }
251+ size += cost
252+ empty = false
253+ kept . insert ( keyID )
254+ }
239255 fitted . revoked = build ( )
256+ var taken = entries . filter { kept . contains ( $0 ) }
257+ while encodedSize ( fitted ) > cap , let last = taken . popLast ( ) {
258+ kept . remove ( last )
259+ fitted . revoked = build ( )
260+ }
240261 }
262+ let rest = file . revoked . filter { ! rows . contains ( $0 ) }
263+ take ( Array ( rest . filter { own . contains ( $0 ) } . reversed ( ) ) , cap : limit )
264+ take ( Array ( rest . filter { ! own . contains ( $0 ) && saved . contains ( $0 ) } . reversed ( ) ) , cap : limit )
265+ let small = limit - flagReserveBytes
266+ take ( Array ( rest . filter { ! own . contains ( $0 ) && ! saved . contains ( $0 ) && asked . contains ( $0 ) } . reversed ( ) ) ,
267+ cap : max ( encodedSize ( fitted ) , small ) )
268+ take ( Array ( rest . filter { ! own . contains ( $0 ) && ! saved . contains ( $0 ) && ! asked . contains ( $0 ) } . reversed ( ) ) ,
269+ cap : max ( encodedSize ( fitted ) , small ) )
241270 return fitted
242271 }
243272
@@ -365,7 +394,7 @@ final class AgentTrustStore {
365394 guard let index = file . clients . firstIndex ( where : { $0 . id == id } ) else { return }
366395 var next = file
367396 next . clients [ index ] . lastSeen = now ( )
368- _ = commit ( next , byUser : false )
397+ _ = commit ( next , byUser : false , denial : false )
369398 }
370399
371400 /// Forgetting tombstones the key, so the same credential cannot come back
@@ -421,7 +450,7 @@ final class AgentTrustStore {
421450 private func deny ( _ next : File , _ denial : Denial ) -> Bool {
422451 if ! pending . contains ( denial ) { pending . append ( denial ) }
423452 file = next
424- if ! closedByDisk { _ = commit ( next , byUser : false ) }
453+ if ! closedByDisk { _ = commit ( next , byUser : false , denial : true ) }
425454 guard pending . contains ( denial ) else { return true }
426455 // Try again at the next check, even if nothing else changes the file.
427456 if ! closedByDisk || readFailed { needsAdopt = true }
@@ -435,7 +464,7 @@ final class AgentTrustStore {
435464 /// on top) and the grant is refused.
436465 private func grant ( _ next : File , byUser : Bool ) -> Bool {
437466 let before = file
438- guard commit ( next , byUser : byUser ) else { return false }
467+ guard commit ( next , byUser : byUser , denial : false ) else { return false }
439468 guard lastCommitSeen else {
440469 // Nothing granted stays in memory, even if the file is now gone.
441470 file = before
@@ -449,7 +478,7 @@ final class AgentTrustStore {
449478 /// file shows up there, its own writes do not settle pending denials.
450479 private var recreated = false
451480
452- private func commit ( _ next : File , byUser : Bool ) -> Bool {
481+ private func commit ( _ next : File , byUser : Bool , denial : Bool ) -> Bool {
453482 lastCommitSeen = false
454483 // A file written where the last one vanished may be replaced by the
455484 // original again, so pending denials are not settled by it.
@@ -459,26 +488,44 @@ final class AgentTrustStore {
459488 needsAdopt = true
460489 return false
461490 }
462- // Never replace the file with one that could not be read back. Past the
491+ // Never replace the file with one that could not be read back. Near the
463492 // limit only the most important revocations are written; the rest stay in
464493 // effect here and pending.
465494 var toWrite = next
466- if Self . encodedSize ( next ) > Self . maxFileBytes {
467- guard let fitted = Self . fitting ( next , onDisk : lastGood ) else {
495+ if denial || readFailed {
496+ // A denial, or the user's turning receipt on over an unreadable file.
497+ if Self . encodedSize ( next ) > maxFileBytes - Self . flagReserveBytes {
498+ let asked = Set ( pending . compactMap { item -> String ? in
499+ if case . revoke ( let keyID ) = item { return keyID }
500+ return nil
501+ } )
502+ guard let fitted = Self . fitting ( next , lastGood : lastGood , saved : savedRevoked , asked : asked , limit : maxFileBytes ) else {
503+ if ! pending . isEmpty { needsAdopt = true }
504+ return false
505+ }
506+ toWrite = fitted
507+ }
508+ } else if Self . encodedSize ( next ) > maxFileBytes - Self . reserveBytes {
509+ // Not a denial: only the revocations the file holds are written, and
510+ // the file may not grow past the limit less the reserve.
511+ let base = onDisk ?? lastGood
512+ let keep = Set ( ( base ? . revoked ?? [ ] ) + ( base ? . clients ?? [ ] ) . map ( \. keyID ) )
513+ toWrite . revoked = next . revoked . filter { keep . contains ( $0 ) }
514+ let bound = min ( maxFileBytes , max ( maxFileBytes - Self . reserveBytes , base . map ( Self . encodedSize ) ?? 0 ) )
515+ guard Self . encodedSize ( toWrite ) <= bound else {
468516 if ! pending . isEmpty { needsAdopt = true }
469517 return false
470518 }
471- toWrite = fitted
472- if ! readFailed , ! closedByDisk , toWrite == onDisk , diskStamp != nil , Self . stamp ( url ) == diskStamp {
473- // Nothing more fits: the file already holds all it can.
474- file = next
475- needsAdopt = false
476- lastCommitSeen = true
477- if ! recreated { pending . removeAll { Self . holds ( toWrite , $0 ) } }
478- return true
479- }
480519 }
481- guard let bytes = try? JSONEncoder ( ) . encode ( toWrite ) , bytes . count <= Self . maxFileBytes ,
520+ if toWrite != next , ! readFailed , ! closedByDisk , toWrite == onDisk , diskStamp != nil , Self . stamp ( url ) == diskStamp {
521+ // Nothing more fits: the file already holds all it can.
522+ file = next
523+ needsAdopt = false
524+ lastCommitSeen = true
525+ if ! recreated { pending . removeAll { Self . holds ( toWrite , $0 ) } }
526+ return true
527+ }
528+ guard let bytes = try? JSONEncoder ( ) . encode ( toWrite ) , bytes . count <= maxFileBytes ,
482529 ( try? write ( bytes , url ) ) != nil else {
483530 if ! pending . isEmpty { needsAdopt = true }
484531 return false
@@ -489,10 +536,11 @@ final class AgentTrustStore {
489536 // Remember the file only if it is what was just written. Otherwise (another
490537 // writer got in between, or it is gone) the next check reads it again and
491538 // the user's denials are applied to it once more.
492- if case . loaded ( let disk , let stamp ) = Self . readDisk ( url ) , disk == toWrite {
539+ if case . loaded ( let disk , let stamp ) = Self . readDisk ( url , limit : maxFileBytes ) , disk == toWrite {
493540 diskStamp = stamp
494541 onDisk = disk
495542 lastGood = disk
543+ savedRevoked . formUnion ( disk . revoked )
496544 needsAdopt = false
497545 lastCommitSeen = true
498546 if ! recreated { pending . removeAll { Self . holds ( toWrite , $0 ) } }
@@ -507,14 +555,17 @@ final class AgentTrustStore {
507555 /// The last file read or written intact, kept while the file is missing or
508556 /// unreadable: what it held is still what the fit keeps first.
509557 private var lastGood : File ?
558+ /// Every revocation this run has seen in an intact file, also one a restored
559+ /// copy dropped since: the fit keeps these before any other.
560+ private var savedRevoked : Set < String > = [ ]
510561
511562 /// The last write was read back unchanged.
512563 private var lastCommitSeen = false
513564
514565 /// Denials made here that the file does not hold yet.
515566 var hasUnsavedDenials : Bool { ! pending . isEmpty }
516567
517- private static func readDisk ( _ url : URL ) -> Disk {
568+ private static func readDisk ( _ url : URL , limit maxFileBytes : Int ) -> Disk {
518569 let fd = Darwin . open ( url . path , O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC )
519570 guard fd >= 0 else { return errno == ENOENT ? . missing : . unreadable ( nil ) }
520571 let reader = FileHandle ( fileDescriptor : fd , closeOnDealloc : true )
0 commit comments