PTT hardening: per-peer burst keys + live-capture storage quota (#1420)

* PTT hardening: burst-ID collision hijack + live-capture quota bypass

Fix C — burst-ID collision hijack: inbound live-voice assemblies and the
finished-burst registry were keyed by the sender-chosen burst ID alone, so
an attacker who observed a public burst ID could race a START and capture
the real talker's frames (packets from the true sender were dropped as
"collisions"). Assemblies now key on (peerID, scope, burstID): a colliding
START from another peer opens its own capped assembly and can never divert
the victim's frames; finalized-note absorption matches on the same triple,
preserving the sender/scope binding. Live capture files also gain the peer
ID in their name so colliding bursts land on distinct paths (still rejected
by burstID(fromVoiceFileName:), so live names remain unabsorbable).

Fix B — live-burst files bypassed the incoming-media quota: progressive
voice_live_*.aac captures were written via raw FileHandle without ever
touching BLEIncomingFileStore.enforceQuota, growing disk unbounded outside
the 100 MB LRU accounting. The coordinator now takes an injected
BLEIncomingFileStore, reserves pttMaxBurstBytes before opening a capture,
and sweeps orphaned voice_live_* partials from previous sessions at
startup. enforceQuota gains an `excluding:` set so in-flight partials are
never LRU-evicted mid-stream; existing callers are unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Review fixes: pattern-guard live captures in quota, scope in capture names

Quota-eviction gap: BLEFileTransferHandler enforces the quota for every
finalized arrival via enforceQuota(reservingBytes:) with no exclusion set,
so a file landing at quota could LRU-evict an in-flight live capture —
unlinking the inode under the coordinator's open FileHandle and leaving a
dead bubble. Protection is now layer-independent: enforceQuota itself skips
voice_live_* names (they still count toward usage), and the excluding:
parameter is gone since the pattern guard covers its only caller. Orphaned
partials are still reclaimed by the coordinator's startup sweep, which the
quota deliberately never touches.

Same-peer cross-scope truncation: makeIncomingURL omitted the scope, so one
peer running a DM burst and a public burst with the same burst ID mapped
both assemblies onto one path — and FileManager.createFile truncates, so
each START corrupted the other capture. Names now mirror the assembly key:
voice_live_<burstHex>_<peerID>_<dm|mesh>.aac. The sweep and quota guard
match on the voice_live_ prefix and burstID(fromVoiceFileName:) still
rejects every live name, so live captures remain unabsorbable;
sameBurstIDCoexistsAcrossScopes now asserts both files survive with intact
contents.

Nits: the coordinator's file operations route through the store's
injectable FileManager instead of FileManager.default, and the
TestEnvironment.isRunningTests branch in init is replaced by a
sweepsOnInit parameter (tests sharing the real application-support
directory pass false for hermeticity).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Promote kept live captures off the voice_live_ name at finalize

Codex P1 follow-up: when a burst finalizes with frames but its .m4a note
never arrives, the voice_live_*.aac capture stays behind as the bubble's
replayable audio — yet the startup sweep deletes every voice_live_* file
and the quota guard skips them forever, so a kept fallback was both
quota-immune for the rest of the session and doomed at the next launch.

finalize now promotes the capture to a plain voice_ name (same suffix) and
republishes the row pointing at it; the finished-burst registry tracks the
promoted URL so a late note still absorbs and deletes it. voice_live_ is
thereby scoped to genuinely in-flight captures: the sweep never touches a
referenced fallback, and promoted files age out of the quota like any
finalized media. If the move fails the live name is kept — exactly the
pre-promotion behavior.

Premise correction, verified while tracing the reference model: chat rows
are NOT persisted across restarts (ConversationStore is in-memory; the
gossip archive replays MessageType.message packets only), so today's sweep
never orphaned a persisted row — the fix removes the in-session quota
immunity and makes the invariant hold if row persistence ever lands. Crash
case stays deliberate and documented: a mid-burst partial from a dead
process is swept because no surviving row can reference it.

Tests: finalize-as-fallback promotes the file, repoints the row, and
survives a later coordinator's startup sweep; promoted fallbacks are
LRU-evictable by the quota; the sweep still removes true orphans while
sparing promoted names; existing burst tests updated for the promoted
paths.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
jack
2026-07-09 16:45:45 +02:00
committed by GitHub
co-authored by jack Claude Opus 4.8
parent 84d315e62d
commit c8479c15e3
4 changed files with 534 additions and 75 deletions
+150 -51
View File
@@ -59,7 +59,7 @@ extension ChatViewModel: ChatLiveVoiceContext {
}
/// Where a live voice burst lives: a Noise DM or the public mesh timeline.
enum VoiceBurstScope: Equatable {
enum VoiceBurstScope: Hashable {
case directMessage
case publicMesh
}
@@ -72,6 +72,16 @@ enum VoiceBurstScope: Equatable {
/// bubble so nobody sees a duplicate.
@MainActor
final class ChatLiveVoiceCoordinator {
/// Burst IDs are sender-chosen, so they only identify a burst *within*
/// an authenticated (peer, scope) pair: keying assemblies by the full
/// triple stops an attacker who observed a public burst ID from racing
/// a START to capture the real talker's frames.
private struct AssemblyKey: Hashable {
let peerID: PeerID
let scope: VoiceBurstScope
let burstID: Data
}
private final class Assembly {
let burstID: Data
let peerID: PeerID
@@ -97,6 +107,8 @@ final class ChatLiveVoiceCoordinator {
var idleTimeout: Task<Void, Never>?
var gapRedrain: Task<Void, Never>?
var key: AssemblyKey { AssemblyKey(peerID: peerID, scope: scope, burstID: burstID) }
init(burstID: Data, peerID: PeerID, scope: VoiceBurstScope, nickname: String, message: BitchatMessage, fileURL: URL, fileHandle: FileHandle) {
self.burstID = burstID
self.peerID = peerID
@@ -123,11 +135,26 @@ final class ChatLiveVoiceCoordinator {
private static let finishedBurstsCap = 32
private unowned let context: any ChatLiveVoiceContext
private var assemblies: [Data: Assembly] = [:]
private var finishedBursts: [Data: FinishedBurst] = [:]
private let fileStore: BLEIncomingFileStore
/// Captures live in the store's directories, so file operations go
/// through the store's (injectable) file manager.
private var fileManager: FileManager { fileStore.fileManager }
private var assemblies: [AssemblyKey: Assembly] = [:]
private var finishedBursts: [AssemblyKey: FinishedBurst] = [:]
init(context: any ChatLiveVoiceContext) {
/// `sweepsOnInit` exists for tests whose coordinator shares the real
/// application-support directory: they pass `false` so parallel test
/// runs never sweep each other's in-flight capture files.
init(context: any ChatLiveVoiceContext, fileStore: BLEIncomingFileStore = BLEIncomingFileStore(), sweepsOnInit: Bool = true) {
self.context = context
self.fileStore = fileStore
// Orphaned partial captures from a previous session (live-only bursts
// whose finalized note never arrived) are dead weight the quota can
// never reclaim (eviction skips voice_live_* by design) sweep them
// on startup.
if sweepsOnInit {
sweepStaleLiveCaptures()
}
}
// MARK: - Inbound frames
@@ -160,11 +187,12 @@ final class ChatLiveVoiceCoordinator {
return
}
if let assembly = assemblies[packet.burstID] {
// The sender is authenticated (Noise session or packet
// signature); a different peer or scope reusing the same burst
// ID is a collision or a replay drop it.
guard assembly.peerID == peerID, assembly.scope == scope else { return }
// The sender is authenticated (Noise session or packet signature),
// and the key binds the burst ID to that (peer, scope): a colliding
// START from another peer opens its own assembly instead of
// capturing this one's frames.
let key = AssemblyKey(peerID: peerID, scope: scope, burstID: packet.burstID)
if let assembly = assemblies[key] {
apply(packet, to: assembly)
return
}
@@ -178,7 +206,7 @@ final class ChatLiveVoiceCoordinator {
return
}
guard let assembly = makeAssembly(burstID: packet.burstID, peerID: peerID, scope: scope, nickname: nickname, timestamp: timestamp) else { return }
assemblies[packet.burstID] = assembly
assemblies[key] = assembly
updatePublicTalkerIndicator()
apply(packet, to: assembly)
case .end, .canceled:
@@ -203,17 +231,25 @@ final class ChatLiveVoiceCoordinator {
let burstID = Self.burstID(fromVoiceFileName: String(message.content.dropFirst(prefix.count)))
else { return false }
// Bind the note to the burst's authenticated sender and scope: an
// attacker's burst reusing the same ID lives under its own key and
// never matches the real sender's note (registry is capped at
// `finishedBurstsCap`, so the linear scan is cheap).
func matches(_ key: AssemblyKey) -> Bool {
key.burstID == burstID
&& (message.senderPeerID == nil || key.peerID == message.senderPeerID)
&& message.isPrivate == (key.scope == .directMessage)
}
// The note usually lands after END, but a lost END or a fast transfer
// can beat it close out the live assembly first.
if let assembly = assemblies[burstID] {
if let assembly = assemblies.first(where: { matches($0.key) })?.value {
finalize(assembly)
}
pruneFinishedBursts()
guard let finished = finishedBursts[burstID] else { return false }
// Bind the note to the burst's authenticated sender and scope.
guard message.senderPeerID == nil || message.senderPeerID == finished.peerID else { return false }
guard message.isPrivate == (finished.scope == .directMessage) else { return false }
guard let entry = finishedBursts.first(where: { matches($0.key) }) else { return false }
let finished = entry.value
let replacement = BitchatMessage(
id: finished.messageID,
@@ -237,8 +273,8 @@ final class ChatLiveVoiceCoordinator {
// The complete .m4a replaces the partial live capture.
WaveformCache.shared.purge(url: finished.fileURL)
try? FileManager.default.removeItem(at: finished.fileURL)
finishedBursts.removeValue(forKey: burstID)
try? fileManager.removeItem(at: finished.fileURL)
finishedBursts.removeValue(forKey: entry.key)
context.notifyUIChanged()
SecureLogger.debug("PTT: absorbed finalized note for burst \(burstID.hexEncodedString())", category: .session)
@@ -248,14 +284,19 @@ final class ChatLiveVoiceCoordinator {
// MARK: - Assembly lifecycle
private func makeAssembly(burstID: Data, peerID: PeerID, scope: VoiceBurstScope, nickname: String, timestamp: Date) -> Assembly? {
guard let fileURL = Self.makeIncomingURL(burstID: burstID) else {
guard let fileURL = makeIncomingURL(burstID: burstID, peerID: peerID, scope: scope) else {
SecureLogger.error("PTT: cannot resolve incoming media directory for burst \(burstID.hexEncodedString())", category: .session)
return nil
}
FileManager.default.createFile(atPath: fileURL.path, contents: nil)
// BCH-01-002: live captures share the incoming-media quota with
// finalized transfers; reserve the burst's worst case up front.
// Eviction skips voice_live_* names, so partials still streaming in
// are safe no matter which caller triggers enforcement.
fileStore.enforceQuota(reservingBytes: TransportConfig.pttMaxBurstBytes)
fileManager.createFile(atPath: fileURL.path, contents: nil)
guard let handle = try? FileHandle(forWritingTo: fileURL) else {
SecureLogger.error("PTT: cannot open capture file for burst \(burstID.hexEncodedString())", category: .session)
try? FileManager.default.removeItem(at: fileURL)
try? fileManager.removeItem(at: fileURL)
return nil
}
@@ -413,13 +454,13 @@ final class ChatLiveVoiceCoordinator {
}
try? assembly.fileHandle?.close()
assembly.fileHandle = nil
assemblies.removeValue(forKey: assembly.burstID)
assemblies.removeValue(forKey: assembly.key)
updatePublicTalkerIndicator()
guard assembly.deliveredFrames > 0 else {
// Nothing audible ever arrived drop the empty bubble.
removeBubble(of: assembly)
try? FileManager.default.removeItem(at: assembly.fileURL)
try? fileManager.removeItem(at: assembly.fileURL)
context.notifyUIChanged()
return
}
@@ -427,16 +468,22 @@ final class ChatLiveVoiceCoordinator {
assembly.player?.finishAfterDrain()
// The bubble's waveform may have been computed from a partial file.
WaveformCache.shared.purge(url: assembly.fileURL)
// Republish so the row re-renders without its LIVE treatment even if
// no finalized note ever arrives to swap in.
republishBubble(of: assembly)
// The capture is the bubble's replayable audio from here on (unless a
// finalized note arrives to swap in): move it off its voice_live_
// name so only genuinely in-flight files match the startup sweep and
// the quota's live-capture guard a kept fallback is never swept,
// and it ages out of the quota like any finalized media.
let fileURL = promoteToFallback(assembly.fileURL)
// Republish so the row re-renders without its LIVE treatment and
// points at the promoted file even if no note ever arrives.
republishBubble(of: assembly, fileURL: fileURL)
pruneFinishedBursts()
finishedBursts[assembly.burstID] = FinishedBurst(
finishedBursts[assembly.key] = FinishedBurst(
messageID: assembly.messageID,
peerID: assembly.peerID,
scope: assembly.scope,
fileURL: assembly.fileURL,
fileURL: fileURL,
messageTimestamp: assembly.messageTimestamp,
expiresAt: Date().addingTimeInterval(TransportConfig.pttFinishedBurstRegistrySeconds)
)
@@ -453,12 +500,48 @@ final class ChatLiveVoiceCoordinator {
}
}
private func republishBubble(of assembly: Assembly) {
private func republishBubble(of assembly: Assembly, fileURL: URL) {
// Same row (same ID), content re-pointed at `fileURL`; the delivery
// status is carried over because the inbound pipeline may have
// updated it on the shared original.
let message = BitchatMessage(
id: assembly.messageID,
sender: assembly.nickname,
content: "\(MimeType.Category.audio.messagePrefix)\(fileURL.lastPathComponent)",
timestamp: assembly.messageTimestamp,
isRelay: false,
isPrivate: assembly.scope == .directMessage,
recipientNickname: assembly.scope == .directMessage ? context.nickname : nil,
senderPeerID: assembly.peerID,
deliveryStatus: assembly.message.deliveryStatus
)
switch assembly.scope {
case .directMessage:
context.upsertPrivateMessage(assembly.message, in: assembly.peerID)
context.upsertPrivateMessage(message, in: assembly.peerID)
case .publicMesh:
context.upsertPublicMeshMessage(assembly.message)
context.upsertPublicMeshMessage(message)
}
}
/// Moves a finished capture off its `voice_live_` prefix (onto plain
/// `voice_`), so the in-flight patterns the startup sweep and the
/// quota's eviction guard only ever match captures still streaming in.
/// On failure the live name is kept: worst case the file is reclaimed at
/// the next startup, exactly the pre-promotion behavior.
private func promoteToFallback(_ liveURL: URL) -> URL {
let liveName = liveURL.lastPathComponent
guard liveName.hasPrefix(BLEIncomingFileStore.liveCapturePrefix) else { return liveURL }
let fallbackName = "voice_" + liveName.dropFirst(BLEIncomingFileStore.liveCapturePrefix.count)
let destination = liveURL.deletingLastPathComponent().appendingPathComponent(fallbackName)
do {
// A leftover from an earlier burst that reused the same
// (peer, scope, burstID) triple would block the move.
try? fileManager.removeItem(at: destination)
try fileManager.moveItem(at: liveURL, to: destination)
return destination
} catch {
SecureLogger.warning("PTT: keeping live-capture name for finished burst — promotion failed: \(error)", category: .session)
return liveURL
}
}
@@ -468,11 +551,11 @@ final class ChatLiveVoiceCoordinator {
assembly.player?.stop()
try? assembly.fileHandle?.close()
assembly.fileHandle = nil
assemblies.removeValue(forKey: assembly.burstID)
assemblies.removeValue(forKey: assembly.key)
updatePublicTalkerIndicator()
removeBubble(of: assembly)
WaveformCache.shared.purge(url: assembly.fileURL)
try? FileManager.default.removeItem(at: assembly.fileURL)
try? fileManager.removeItem(at: assembly.fileURL)
context.notifyUIChanged()
}
@@ -480,10 +563,10 @@ final class ChatLiveVoiceCoordinator {
private func rescheduleIdleTimeout(for assembly: Assembly) {
assembly.idleTimeout?.cancel()
let burstID = assembly.burstID
let key = assembly.key
assembly.idleTimeout = Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: UInt64(TransportConfig.pttBurstEndTimeoutSeconds * 1_000_000_000))
guard !Task.isCancelled, let self, let assembly = self.assemblies[burstID] else { return }
guard !Task.isCancelled, let self, let assembly = self.assemblies[key] else { return }
// Talker went silent/out of range without an END.
self.finalize(assembly)
}
@@ -491,10 +574,10 @@ final class ChatLiveVoiceCoordinator {
private func scheduleGapRedrain(for assembly: Assembly) {
assembly.gapRedrain?.cancel()
let burstID = assembly.burstID
let key = assembly.key
assembly.gapRedrain = Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: UInt64((Self.gapSkipSeconds + 0.05) * 1_000_000_000))
guard !Task.isCancelled, let self, let assembly = self.assemblies[burstID] else { return }
guard !Task.isCancelled, let self, let assembly = self.assemblies[key] else { return }
self.drainInOrder(assembly)
self.finalizeIfComplete(assembly)
}
@@ -521,21 +604,37 @@ final class ChatLiveVoiceCoordinator {
return Data(hexString: hex)
}
private static func makeIncomingURL(burstID: Data) -> URL? {
guard let base = try? FileManager.default.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
) else { return nil }
let directory = base
.appendingPathComponent("files", isDirectory: true)
.appendingPathComponent("\(MimeType.Category.audio.mediaDir)/incoming", isDirectory: true)
do {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
} catch {
return nil
private static let incomingSubdirectory = "\(MimeType.Category.audio.mediaDir)/incoming"
/// The peer ID and scope in the name mirror the assembly key: colliding
/// burst IDs from different senders or from the same sender across DM
/// and public land on distinct files instead of truncating each other.
/// `burstID(fromVoiceFileName:)` still rejects every `voice_live_*` name,
/// so live captures can never absorb a note.
private func makeIncomingURL(burstID: Data, peerID: PeerID, scope: VoiceBurstScope) -> URL? {
guard let directory = try? fileStore.incomingDirectory(subdirectory: Self.incomingSubdirectory) else { return nil }
let scopeTag = scope == .directMessage ? "dm" : "mesh"
return directory.appendingPathComponent("\(BLEIncomingFileStore.liveCapturePrefix)\(burstID.hexEncodedString())_\(peerID.id)_\(scopeTag).aac")
}
/// Deletes partial live captures left behind by a previous session.
/// In-session cleanup needs no sweep: absorb, cancel, and empty-finalize
/// delete their capture file, and finalize promotes keepers off the
/// `voice_live_` name. So anything the sweep matches was orphaned by a
/// crash mid-burst safe to delete, because chat rows are in-memory
/// only (ConversationStore never persists; the gossip archive replays
/// `MessageType.message` packets only), so no row from a previous
/// process can reference the file.
private func sweepStaleLiveCaptures() {
guard let directory = try? fileStore.incomingDirectory(subdirectory: Self.incomingSubdirectory),
let contents = try? fileManager.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles]
)
else { return }
for url in contents where url.lastPathComponent.hasPrefix(BLEIncomingFileStore.liveCapturePrefix) && url.pathExtension == "aac" {
try? fileManager.removeItem(at: url)
}
return directory.appendingPathComponent("voice_live_\(burstID.hexEncodedString()).aac")
}
}