Skip to content

Commit c6ac0b6

Browse files
authored
Merge pull request #40 from codebasic/integration/issue-31
Bring the #33 promotion fixes for #13/#31 into the promotion candidate (#4)
2 parents 31f30aa + 6262d82 commit c6ac0b6

23 files changed

Lines changed: 793 additions & 206 deletions

‎Helpers/AgentCatalogMCP.swift‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,9 @@ struct ClientKey {
695695
#if TTS_AGENT_FIXTURE_KEYS
696696
// Integration fixtures use their own synthetic key directory.
697697
return ProcessInfo.processInfo.environment["TTS_AGENT_FIXTURE_KEY_DIR"].map { URL(fileURLWithPath: $0, isDirectory: true) }
698+
#elseif TTS_FIXTURE_HOME
699+
// Fixture builds keep keys under the fixture's home, never the user's.
700+
return TTSRuntime.applicationSupport().appendingPathComponent("agent-client-keys", isDirectory: true)
698701
#else
699702
guard let entry = getpwuid(getuid()), let home = entry.pointee.pw_dir else { return nil }
700703
return TTSRuntime.applicationSupport(home: URL(fileURLWithPath: String(cString: home), isDirectory: true))

‎Sources/App/AgentSessionController.swift‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -820,7 +820,8 @@ import Security
820820
private func adoptStoreAfterTakeover() {
821821
let wasFailed = trust.readFailed
822822
let priorKeys = Dictionary(trust.clients.map { ($0.id, $0.keyID) }, uniquingKeysWith: { first, _ in first })
823-
trust.adoptDisk()
823+
// Only the socket holder writes the file; another instance only reads it.
824+
trust.adoptDisk(writeBack: pairingSocket != nil)
824825
// A remembered instruction choice belongs to the key that was approved
825826
// when it was made; a removed or replaced key does not inherit it.
826827
let keys = Dictionary(trust.clients.map { ($0.id, $0.keyID) }, uniquingKeysWith: { first, _ in first })
@@ -983,7 +984,7 @@ import Security
983984
}
984985

985986
private func block(_ peer: LocalInstructionPeer) {
986-
let limit = AgentTrustStore.maxRevoked
987+
let limit = 1024
987988
if blockedPeers.count >= limit { blockedPeers.removeFirst() }
988989
blockedPeers.append(peer)
989990
}
@@ -1025,8 +1026,16 @@ import Security
10251026
let socket = LocalApprovedSocket(peer: pair.peer, endpoint: AgentPairing.draftEndpoint(slot: pair.slot), directory: directory,
10261027
lifetime: nil, maxFrame: AgentLimits.frameBytes,
10271028
verified: Self.verifier(for: pair)) { [weak self] bytes, active in
1028-
guard let request = Self.decode(bytes) else { return Self.reply("invalid") }
1029-
guard Self.isV2(request["schema_version"]) else { return Self.reply("upgrade_required") }
1029+
// The result, the app (its signing identity, or the helper pid for an
1030+
// unverified one) and the lengths only; never the text, title,
1031+
// instruction, request key or key material.
1032+
var lengths = (display: 0, speech: 0)
1033+
func answer(_ status: String) -> Data {
1034+
Log.agent.info("[AGENT-DRAFT] receipt host=\(pair.host ?? "unverified", privacy: .public) pid=\(pair.peer.pid, privacy: .public) result=\(status, privacy: .public) display_len=\(lengths.display, privacy: .public) speech_len=\(lengths.speech, privacy: .public)")
1035+
return Self.reply(status)
1036+
}
1037+
guard let request = Self.decode(bytes) else { return answer("invalid") }
1038+
guard Self.isV2(request["schema_version"]) else { return answer("upgrade_required") }
10301039
let base: Set<String> = ["schema_version", "idempotency_key", "display_text"]
10311040
let linkedKeys: Set<String> = ["profile", "revision", "body_sha256", "proof"]
10321041
var keys = Set(request.keys)
@@ -1040,10 +1049,11 @@ import Security
10401049
(request["title"] == nil || request["title"] is String),
10411050
ExplanationDraft(id: clientKey, display: display, speech: request["speech_text"] as? String,
10421051
title: request["title"] as? String) != nil else {
1043-
return Self.reply("invalid")
1052+
return answer("invalid")
10441053
}
10451054
let speech = request["speech_text"] as? String
10461055
let title = request["title"] as? String
1056+
lengths = (display.count, speech?.count ?? 0)
10471057
let response = Reply()
10481058
let signal = DispatchSemaphore(value: 0)
10491059
let responseDeadline = DispatchTime.now() + .milliseconds(750)
@@ -1112,8 +1122,8 @@ import Security
11121122
self.rates[pair.client] = rate
11131123
response.set(result.rawValue)
11141124
}
1115-
guard signal.wait(timeout: responseDeadline) == .success else { return Self.reply("unconfirmed") }
1116-
return Self.reply(response.get())
1125+
guard signal.wait(timeout: responseDeadline) == .success else { return answer("unconfirmed") }
1126+
return answer(response.get())
11171127
}
11181128
guard socket.start() else {
11191129
status = socket.requiresPathInspection ? LocalApprovedSocket.unknownPathMessage : "대본 받기 소켓을 시작할 수 없습니다."

‎Sources/App/LocalSpeechSocket.swift‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import Foundation
22
import Darwin
33
import CryptoKit
44

5-
/// Single-login, opt-in IPC. No text is logged or persisted by this bridge.
5+
/// Single-login, opt-in IPC. No text is logged or persisted by this bridge; each
6+
/// request logs its result, the peer process and the text length only.
67
final class LocalSpeechSocket {
78
private let queue = DispatchQueue(label: "com.codebasic.tts.local-speech")
89
private var fd: Int32 = -1
@@ -74,12 +75,20 @@ final class LocalSpeechSocket {
7475
if b == 10 { break }; buffer.append(b)
7576
}
7677
var status = "invalid"
78+
var length = 0
79+
defer {
80+
var pid: pid_t = 0
81+
var size = socklen_t(MemoryLayout<pid_t>.size)
82+
let peer = getsockopt(client, SOL_LOCAL, LOCAL_PEERPID, &pid, &size) == 0 ? String(pid) : "unknown"
83+
Log.agent.info("[AGENT-SPEECH] request pid=\(peer, privacy: .public) result=\(status, privacy: .public) len=\(length, privacy: .public)")
84+
}
7785
if buffer.count < 25 * 1024,
7886
let object = try? JSONSerialization.jsonObject(with: Data(buffer)) as? [String: Any],
7987
object.count == 2, let text = object["text"] as? String, let key = object["idempotency_key"] as? String,
8088
text.utf8.count <= 4096, !text.contains("\0"), !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
8189
!key.isEmpty, key.utf8.count <= 128,
8290
key.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 46 || $0 == 95 }) {
91+
length = text.count
8392
let semaphore = DispatchSemaphore(value: 0)
8493
let deadline = DispatchTime.now() + .milliseconds(1000)
8594
let lock = NSLock()

‎Sources/Core/AgentTrustStore.swift‎

Lines changed: 108 additions & 17 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 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 }),

‎Sources/Core/Logging.swift‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ enum Log {
1717
static let service = Logger(subsystem: subsystem, category: "service")
1818
static let app = Logger(subsystem: subsystem, category: "app")
1919
static let tts = Logger(subsystem: subsystem, category: "tts")
20-
/// `[AGENT-CONN]` agent app connection and approval decisions. Never logs
20+
/// `[AGENT-CONN]` agent app connection and approval decisions, `[AGENT-DRAFT]`
21+
/// draft receipt results and `[AGENT-SPEECH]` speech request results. Never logs
2122
/// draft text, instructions or key material; app identity is the code
2223
/// signature (team/certificate + signing identifier), not user data.
2324
static let agent = Logger(subsystem: subsystem, category: "agent")

0 commit comments

Comments
 (0)