@@ -78,7 +78,11 @@ final class AgentTrustStore {
7878 }
7979
8080 static let maxClients = AgentPairing . slotCount
81- static let maxRevoked = 64
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
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
@@ -110,6 +114,8 @@ final class AgentTrustStore {
110114 switch Self . readDisk ( url ) {
111115 case . loaded ( let loaded , let stamp ) :
112116 file = loaded
117+ onDisk = loaded
118+ lastGood = loaded
113119 loadedExisting = true
114120 diskStamp = stamp
115121 case . missing :
@@ -133,10 +139,15 @@ final class AgentTrustStore {
133139 /// the file again when it takes the socket over and whenever the file changed
134140 /// since its own last read or write. Missing or unreadable after this instance
135141 /// knew approvals: nothing is trusted and receipt is off. The user's denials
136- /// not yet saved are applied again on top of what is read.
137- func adoptDisk ( ) {
142+ /// not yet saved are applied again on top of what is read. An instance that
143+ /// does not hold the socket (`writeBack == false`) only reads: what it would
144+ /// write stays pending for when it takes the socket over.
145+ func adoptDisk ( writeBack : Bool = true ) {
146+ let known = file . revoked
138147 let disk = Self . readDisk ( url )
139148 guard case . loaded ( let loaded , let stamp ) = disk else {
149+ // What was last read is no longer what the file holds.
150+ onDisk = nil
140151 if case . unreadable ( let stamp ) = disk {
141152 diskStamp = stamp
142153 needsAdopt = stamp == nil
@@ -158,25 +169,78 @@ final class AgentTrustStore {
158169 readFailed = false
159170 closedByDisk = false
160171 diskStamp = stamp
172+ onDisk = loaded
173+ lastGood = loaded
161174 needsAdopt = false
162- guard ! pending . isEmpty else {
163- file = loaded
164- return
175+ // Revocations are never undone (a revoked key cannot be approved again),
176+ // so every revocation this run knows is kept, also over a restored older
177+ // copy that predates it. Receipt choices are not merged this way: the user
178+ // may have turned receipt back on through another instance in between.
179+ // A missing one becomes a pending denial like the user's own, so a failed
180+ // write-back is retried and only a re-read file holding it settles it.
181+ for keyID in known where ! Self . holds ( loaded , . revoke ( keyID ) ) && ! pending . contains ( . revoke ( keyID ) ) {
182+ pending . append ( . revoke ( keyID ) )
165183 }
166184 var merged = loaded
167185 for denial in pending { Self . apply ( denial , to : & merged ) }
168186 guard merged != loaded else {
169- // The file already says what the user asked for, except one app's off
170- // for a row it does not have: that stays for when the row comes back.
187+ // The file already says what the user asked for (or nothing is
188+ // pending), except one app's off for a row it does not have: that
189+ // stays for when the row comes back.
171190 file = loaded
172191 // A file this run re-created never settles pending denials.
173192 if ! recreated { pending . removeAll { Self . holds ( loaded , $0 ) } }
174193 return
175194 }
176195 file = merged
196+ guard writeBack else {
197+ // Read again (and written) once this instance holds the socket.
198+ needsAdopt = false
199+ return
200+ }
177201 _ = commit ( merged , byUser : false )
178202 }
179203
204+ private static func encodedSize ( _ file : File ) -> Int {
205+ ( try? JSONEncoder ( ) . encode ( file ) ) ? . count ?? Int . max
206+ }
207+
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 ( ) )
218+ var fitted = file
219+ func build ( ) -> [ String ] {
220+ let kept = Set ( required ) . union ( others )
221+ return file . revoked . filter { kept . contains ( $0 ) }
222+ }
223+ 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 ( )
239+ fitted . revoked = build ( )
240+ }
241+ return fitted
242+ }
243+
180244 private func close ( failed : Bool ) {
181245 var closed = File ( )
182246 closed . receiptChoice = . off
@@ -330,7 +394,7 @@ final class AgentTrustStore {
330394 if let index = file . clients . firstIndex ( where : { $0 . id == id } ) { file . clients [ index ] . receivesDrafts = false }
331395 case . revoke ( let keyID ) :
332396 file . clients . removeAll { $0 . keyID == keyID }
333- if ! file . revoked . contains ( keyID ) { revoke ( keyID , in : & file ) }
397+ if ! file . revoked . contains ( keyID ) { file . revoked . append ( keyID ) }
334398 }
335399 }
336400
@@ -348,8 +412,7 @@ final class AgentTrustStore {
348412 }
349413
350414 private static func revoke ( _ keyID : String , in file : inout File ) {
351- file . revoked . append ( keyID )
352- if file . revoked . count > maxRevoked { file . revoked . removeFirst ( file . revoked . count - maxRevoked ) }
415+ if ! file . revoked . contains ( keyID ) { file . revoked . append ( keyID ) }
353416 }
354417
355418 /// A denial is in effect here at once and stays pending until a re-read of
@@ -396,7 +459,27 @@ final class AgentTrustStore {
396459 needsAdopt = true
397460 return false
398461 }
399- guard let bytes = try? JSONEncoder ( ) . encode ( next ) , ( try? write ( bytes , url ) ) != nil else {
462+ // Never replace the file with one that could not be read back. Past the
463+ // limit only the most important revocations are written; the rest stay in
464+ // effect here and pending.
465+ var toWrite = next
466+ if Self . encodedSize ( next ) > Self . maxFileBytes {
467+ guard let fitted = Self . fitting ( next , onDisk : lastGood ) else {
468+ if ! pending . isEmpty { needsAdopt = true }
469+ return false
470+ }
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+ }
480+ }
481+ guard let bytes = try? JSONEncoder ( ) . encode ( toWrite ) , bytes . count <= Self . maxFileBytes ,
482+ ( try? write ( bytes , url ) ) != nil else {
400483 if ! pending . isEmpty { needsAdopt = true }
401484 return false
402485 }
@@ -406,17 +489,25 @@ final class AgentTrustStore {
406489 // Remember the file only if it is what was just written. Otherwise (another
407490 // writer got in between, or it is gone) the next check reads it again and
408491 // the user's denials are applied to it once more.
409- if case . loaded ( let disk , let stamp ) = Self . readDisk ( url ) , disk == next {
492+ if case . loaded ( let disk , let stamp ) = Self . readDisk ( url ) , disk == toWrite {
410493 diskStamp = stamp
494+ onDisk = disk
495+ lastGood = disk
411496 needsAdopt = false
412497 lastCommitSeen = true
413- if ! recreated { pending . removeAll { Self . holds ( next , $0 ) } }
498+ if ! recreated { pending . removeAll { Self . holds ( toWrite , $0 ) } }
414499 } else {
415500 needsAdopt = true
416501 }
417502 return true
418503 }
419504
505+ /// The file as this instance last read or wrote it.
506+ private var onDisk : File ?
507+ /// The last file read or written intact, kept while the file is missing or
508+ /// unreadable: what it held is still what the fit keeps first.
509+ private var lastGood : File ?
510+
420511 /// The last write was read back unchanged.
421512 private var lastCommitSeen = false
422513
@@ -432,11 +523,11 @@ final class AgentTrustStore {
432523 guard fstat ( fd , & meta ) == 0 else { return . unreadable ( nil ) }
433524 let fileStamp = stamp ( meta )
434525 guard ( meta . st_mode & S_IFMT ) == S_IFREG , meta . st_uid == getuid ( ) ,
435- meta . st_nlink == 1 , meta . st_mode & 0o777 == 0o600 , meta . st_size > 0 , meta . st_size <= 256 * 1024
526+ meta . st_nlink == 1 , meta . st_mode & 0o777 == 0o600 , meta . st_size > 0 , meta . st_size <= maxFileBytes
436527 else { return . unreadable ( fileStamp ) }
437528 // A read error may be passing; only bytes that do not parse keep the stamp.
438- guard let bytes = try? reader . read ( upToCount : 256 * 1024 + 1 ) else { return . unreadable ( nil ) }
439- guard bytes . count <= 256 * 1024 ,
529+ guard let bytes = try? reader . read ( upToCount : maxFileBytes + 1 ) else { return . unreadable ( nil ) }
530+ guard bytes . count <= maxFileBytes ,
440531 let loaded = try? JSONDecoder ( ) . decode ( File . self , from : bytes ) , loaded . version == 1 ,
441532 loaded . clients . count <= maxClients ,
442533 loaded . clients . allSatisfy ( { AgentPairingProof . keyID ( $0 . publicKey ) == $0 . keyID } ) ,
0 commit comments