mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-29 08:29:22 +00:00
Harden waveform decoding and audio container validation at ingest (#1873)
* Harden waveform decoding and audio container validation at ingest * Keep AudioContainerValidator MemoryReader alive across CoreAudio callbacks --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
1 parent
6db5495a33
commit
ad3f3dbab5
9 files changed
+491
-34
No files matched your search
@@ -14,14 +14,15 @@ final class VoiceNotePlaybackController: NSObject, ObservableObject, AVAudioPlay
|
||||
|
||||
/// rounded so 4.9s shows "00:05"
|
||||
var roundedDuration: Int {
|
||||
guard duration.isFinite else { return 0 }
|
||||
return Int(duration.rounded())
|
||||
guard duration.isFinite, duration >= 0 else { return 0 }
|
||||
return Int(min(duration, Double(Int.max / 2)).rounded())
|
||||
}
|
||||
|
||||
/// ceil so "00:01" stays visible until playback ends, capped to rounded duration
|
||||
var remainingSeconds: Int {
|
||||
guard duration.isFinite, currentTime.isFinite else { return 0 }
|
||||
let remaining = max(0, duration - currentTime)
|
||||
return min(roundedDuration, Int(ceil(remaining)))
|
||||
return min(roundedDuration, Int(ceil(min(remaining, Double(Int.max / 2)))))
|
||||
}
|
||||
|
||||
private var player: AVAudioPlayer?
|
||||
|
||||
@@ -6,6 +6,12 @@ import BitLogger
|
||||
final class WaveformCache {
|
||||
static let shared = WaveformCache()
|
||||
|
||||
/// Hard bounds on decoded waveform work so a crafted audio header cannot
|
||||
/// overflow `AVAudioFrameCount` or allocate an unbounded PCM buffer.
|
||||
static let maxWaveformDurationSeconds: TimeInterval = 600
|
||||
static let maxWaveformFrames: Int64 = 30_000_000
|
||||
private static let chunkFrameCapacity: AVAudioFrameCount = 8_192
|
||||
|
||||
private let queue = DispatchQueue(label: "com.bitchat.waveform-cache", attributes: .concurrent)
|
||||
private var cache: [URL: (waveform: [Float], lastAccess: Date)] = [:]
|
||||
private let maxCacheSize = 20 // Limit cache to prevent unbounded memory growth
|
||||
@@ -29,7 +35,7 @@ final class WaveformCache {
|
||||
return
|
||||
}
|
||||
|
||||
guard let computed = self.computeWaveform(url: url, bins: bins) else {
|
||||
guard let computed = Self.computeWaveform(url: url, bins: bins) else {
|
||||
DispatchQueue.main.async { completion([]) }
|
||||
return
|
||||
}
|
||||
@@ -56,42 +62,73 @@ final class WaveformCache {
|
||||
}
|
||||
}
|
||||
|
||||
private func computeWaveform(url: URL, bins: Int) -> [Float]? {
|
||||
static func computeWaveform(url: URL, bins: Int) -> [Float]? {
|
||||
guard bins > 0 else { return nil }
|
||||
// Use autoreleasepool to manage memory from audio buffer allocations
|
||||
return autoreleasepool {
|
||||
do {
|
||||
let audioFile = try AVAudioFile(forReading: url)
|
||||
let length = Int(audioFile.length)
|
||||
guard length > 0 else { return nil }
|
||||
|
||||
guard let buffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat, frameCapacity: AVAudioFrameCount(length)) else {
|
||||
let format = audioFile.processingFormat
|
||||
let channelCount = Int(format.channelCount)
|
||||
let sampleRate = format.sampleRate
|
||||
guard channelCount > 0, sampleRate.isFinite, sampleRate > 0 else {
|
||||
return nil
|
||||
}
|
||||
try audioFile.read(into: buffer, frameCount: AVAudioFrameCount(length))
|
||||
guard let channelData = buffer.floatChannelData else { return nil }
|
||||
|
||||
let channelCount = Int(audioFile.processingFormat.channelCount)
|
||||
let frameLength = Int(buffer.frameLength)
|
||||
let samplesPerBin = max(1, frameLength / bins)
|
||||
let rawLength = audioFile.length
|
||||
guard rawLength > 0,
|
||||
rawLength <= maxWaveformFrames,
|
||||
Double(rawLength) / sampleRate <= maxWaveformDurationSeconds,
|
||||
let totalFrames = AVAudioFrameCount(exactly: rawLength) else {
|
||||
SecureLogger.warning(
|
||||
"Waveform rejected audio with out-of-range length (\(rawLength) frames at \(sampleRate) Hz) for \(url.lastPathComponent)",
|
||||
category: .security
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
var magnitudes: [Float] = Array(repeating: 0, count: bins)
|
||||
for bin in 0..<bins {
|
||||
let start = bin * samplesPerBin
|
||||
let end = min(frameLength, start + samplesPerBin)
|
||||
if start >= end { break }
|
||||
let bufferCapacity = min(totalFrames, chunkFrameCapacity)
|
||||
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: bufferCapacity) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var sum: Float = 0
|
||||
var sampleCount = 0
|
||||
for frame in start..<end {
|
||||
let totalFrameCount = Int(totalFrames)
|
||||
let samplesPerBin = max(1, totalFrameCount / bins)
|
||||
var binSums = Array(repeating: Double(0), count: bins)
|
||||
var binCounts = Array(repeating: 0, count: bins)
|
||||
var frameCursor = 0
|
||||
|
||||
while frameCursor < totalFrameCount {
|
||||
let remaining = totalFrameCount - frameCursor
|
||||
let framesToRead = min(chunkFrameCapacity, AVAudioFrameCount(remaining))
|
||||
buffer.frameLength = 0
|
||||
try audioFile.read(into: buffer, frameCount: framesToRead)
|
||||
|
||||
let readFrames = Int(buffer.frameLength)
|
||||
guard readFrames > 0, let channelData = buffer.floatChannelData else {
|
||||
break
|
||||
}
|
||||
|
||||
let invChannels = 1.0 / Double(channelCount)
|
||||
for localFrame in 0..<readFrames {
|
||||
let globalFrame = frameCursor + localFrame
|
||||
let bin = min(bins - 1, globalFrame / samplesPerBin)
|
||||
var sampleValue: Float = 0
|
||||
for channel in 0..<channelCount {
|
||||
sampleValue += fabsf(channelData[channel][frame])
|
||||
sampleValue += fabsf(channelData[channel][localFrame])
|
||||
}
|
||||
sum += sampleValue / Float(channelCount)
|
||||
sampleCount += 1
|
||||
binSums[bin] += Double(sampleValue) * invChannels
|
||||
binCounts[bin] += 1
|
||||
}
|
||||
magnitudes[bin] = sampleCount > 0 ? sum / Float(sampleCount) : 0
|
||||
|
||||
frameCursor += readFrames
|
||||
}
|
||||
|
||||
guard frameCursor > 0 else { return nil }
|
||||
|
||||
var magnitudes: [Float] = Array(repeating: 0, count: bins)
|
||||
for bin in 0..<bins where binCounts[bin] > 0 {
|
||||
magnitudes[bin] = Float(binSums[bin] / Double(binCounts[bin]))
|
||||
}
|
||||
|
||||
if let maxMagnitude = magnitudes.max(), maxMagnitude > 0 {
|
||||
|
||||
@@ -226,6 +226,8 @@ final class BLEFileTransferHandler {
|
||||
SecureLogger.warning("🚫 MIME REJECT: '\(mimeType ?? "<empty>")' not supported. Size=\(bytes)b from \(peerID.id.prefix(8))...", category: .security)
|
||||
case .failure(.magicMismatch(let mime, let bytes, let prefixHex)):
|
||||
SecureLogger.warning("🚫 MAGIC REJECT: MIME='\(mime)' size=\(bytes)b prefix=[\(prefixHex)] from \(peerID.id.prefix(8))...", category: .security)
|
||||
case .failure(.invalidAudio(let mime, let bytes, let reason)):
|
||||
SecureLogger.warning("🚫 AUDIO REJECT: MIME='\(mime)' size=\(bytes)b reason='\(reason)' from \(peerID.id.prefix(8))...", category: .security)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import AudioToolbox
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
|
||||
@@ -39,6 +40,7 @@ enum BLEIncomingFileRejection: Error, Equatable {
|
||||
case payloadTooLarge(bytes: Int)
|
||||
case unsupportedMime(mimeType: String?, bytes: Int)
|
||||
case magicMismatch(mime: MimeType, bytes: Int, prefixHex: String)
|
||||
case invalidAudio(mime: MimeType, bytes: Int, reason: String)
|
||||
}
|
||||
|
||||
enum BLEIncomingFileValidator {
|
||||
@@ -66,6 +68,143 @@ enum BLEIncomingFileValidator {
|
||||
))
|
||||
}
|
||||
|
||||
if mime.category == .audio,
|
||||
let failureReason = AudioContainerValidator.validate(data: filePacket.content, mime: mime) {
|
||||
return .failure(.invalidAudio(
|
||||
mime: mime,
|
||||
bytes: filePacket.content.count,
|
||||
reason: failureReason
|
||||
))
|
||||
}
|
||||
|
||||
return .success(BLEIncomingFileAcceptance(filePacket: filePacket, mime: mime))
|
||||
}
|
||||
}
|
||||
|
||||
/// Inspects incoming audio payloads in memory with CoreAudio before they are
|
||||
/// persisted or tracked for gossip sync. Blocks container spoofing (e.g., CAF
|
||||
/// disguised as M4A) and crafted headers claiming absurd durations or frame
|
||||
/// counts.
|
||||
enum AudioContainerValidator {
|
||||
private final class MemoryReader {
|
||||
let data: Data
|
||||
init(data: Data) { self.data = data }
|
||||
}
|
||||
|
||||
static func validate(data: Data, mime: MimeType) -> String? {
|
||||
guard let allowedFormats = allowedFileFormats(for: mime) else {
|
||||
// Formats CoreAudio does not parse (e.g., Ogg) rely on magic + size checks.
|
||||
return nil
|
||||
}
|
||||
|
||||
let reader = MemoryReader(data: data)
|
||||
return withExtendedLifetime(reader) {
|
||||
let clientData = Unmanaged.passUnretained(reader).toOpaque()
|
||||
var audioFileID: AudioFileID?
|
||||
|
||||
let openStatus = AudioFileOpenWithCallbacks(
|
||||
clientData,
|
||||
{ inClientData, inPosition, requestCount, buffer, actualCount in
|
||||
let reader = Unmanaged<MemoryReader>.fromOpaque(inClientData).takeUnretainedValue()
|
||||
guard inPosition >= 0 else { return kAudioFilePositionError }
|
||||
let total = Int64(reader.data.count)
|
||||
if inPosition >= total {
|
||||
actualCount.pointee = 0
|
||||
return noErr
|
||||
}
|
||||
let available = Int(min(Int64(requestCount), total - inPosition))
|
||||
if available > 0 {
|
||||
let start = Int(inPosition)
|
||||
reader.data.copyBytes(
|
||||
to: buffer.assumingMemoryBound(to: UInt8.self),
|
||||
from: start..<(start + available)
|
||||
)
|
||||
}
|
||||
actualCount.pointee = UInt32(available)
|
||||
return noErr
|
||||
},
|
||||
nil,
|
||||
{ inClientData in
|
||||
let reader = Unmanaged<MemoryReader>.fromOpaque(inClientData).takeUnretainedValue()
|
||||
return Int64(reader.data.count)
|
||||
},
|
||||
nil,
|
||||
0,
|
||||
&audioFileID
|
||||
)
|
||||
|
||||
guard openStatus == noErr, let fileID = audioFileID else {
|
||||
return "unparseable container (status \(openStatus))"
|
||||
}
|
||||
defer { AudioFileClose(fileID) }
|
||||
|
||||
var detectedFormat: AudioFileTypeID = 0
|
||||
var formatSize = UInt32(MemoryLayout<AudioFileTypeID>.size)
|
||||
let formatStatus = AudioFileGetProperty(fileID, kAudioFilePropertyFileFormat, &formatSize, &detectedFormat)
|
||||
guard formatStatus == noErr, allowedFormats.contains(detectedFormat) else {
|
||||
return "container format mismatch (\(detectedFormat))"
|
||||
}
|
||||
|
||||
var asbd = AudioStreamBasicDescription()
|
||||
var asbdSize = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
let asbdStatus = AudioFileGetProperty(fileID, kAudioFilePropertyDataFormat, &asbdSize, &asbd)
|
||||
guard asbdStatus == noErr,
|
||||
asbd.mSampleRate.isFinite,
|
||||
asbd.mSampleRate > 0,
|
||||
asbd.mChannelsPerFrame > 0 else {
|
||||
return "invalid audio stream description"
|
||||
}
|
||||
|
||||
var estimatedDuration: TimeInterval = 0
|
||||
var durationSize = UInt32(MemoryLayout<TimeInterval>.size)
|
||||
let durationStatus = AudioFileGetProperty(
|
||||
fileID,
|
||||
kAudioFilePropertyEstimatedDuration,
|
||||
&durationSize,
|
||||
&estimatedDuration
|
||||
)
|
||||
if durationStatus == noErr {
|
||||
guard estimatedDuration.isFinite,
|
||||
estimatedDuration >= 0,
|
||||
estimatedDuration <= WaveformCache.maxWaveformDurationSeconds else {
|
||||
return "duration out of bounds (\(estimatedDuration)s)"
|
||||
}
|
||||
}
|
||||
|
||||
var packetCount: UInt64 = 0
|
||||
var packetCountSize = UInt32(MemoryLayout<UInt64>.size)
|
||||
let packetStatus = AudioFileGetProperty(
|
||||
fileID,
|
||||
kAudioFilePropertyAudioDataPacketCount,
|
||||
&packetCountSize,
|
||||
&packetCount
|
||||
)
|
||||
if packetStatus == noErr, asbd.mFramesPerPacket > 0 {
|
||||
let (totalFrames, overflow) = packetCount.multipliedReportingOverflow(by: UInt64(asbd.mFramesPerPacket))
|
||||
if overflow || totalFrames > UInt64(WaveformCache.maxWaveformFrames) {
|
||||
return "frame count out of bounds"
|
||||
}
|
||||
if Double(totalFrames) / asbd.mSampleRate > WaveformCache.maxWaveformDurationSeconds {
|
||||
return "frame duration out of bounds"
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private static func allowedFileFormats(for mime: MimeType) -> Set<AudioFileTypeID>? {
|
||||
switch mime {
|
||||
case .m4a, .mp4Audio:
|
||||
return [kAudioFileM4AType, kAudioFileMPEG4Type, kAudioFile3GPType, kAudioFile3GP2Type]
|
||||
case .aac:
|
||||
return [kAudioFileAAC_ADTSType, kAudioFileM4AType, kAudioFileMPEG4Type]
|
||||
case .mp3, .mpeg:
|
||||
return [kAudioFileMP3Type, kAudioFileMP2Type, kAudioFileMP1Type]
|
||||
case .wav, .xWav:
|
||||
return [kAudioFileWAVEType]
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,10 +135,11 @@ enum MimeType: CaseIterable, Hashable {
|
||||
data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46 &&
|
||||
data[8] == 0x57 && data[9] == 0x45 && data[10] == 0x42 && data[11] == 0x50
|
||||
|
||||
case .m4a, .mp4Audio, .aac:
|
||||
// AVAudioRecorder output varies by platform - be lenient
|
||||
// Security: size already capped + sandboxed execution
|
||||
return data.count > 100
|
||||
case .m4a, .mp4Audio:
|
||||
return Self.matchesISOBMFF(data)
|
||||
|
||||
case .aac:
|
||||
return Self.matchesADTSAAC(data) || Self.matchesISOBMFF(data)
|
||||
|
||||
case .mpeg, .mp3:
|
||||
if data.count >= 3 && data[0] == 0x49 && data[1] == 0x44 && data[2] == 0x33 {
|
||||
@@ -186,6 +187,30 @@ enum MimeType: CaseIterable, Hashable {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// ISO Base Media File Format (`ftyp` box) used by `.m4a` and `.mp4` audio.
|
||||
private static func matchesISOBMFF(_ data: Data) -> Bool {
|
||||
guard data.count >= 12 else { return false }
|
||||
guard data[4] == 0x66 && data[5] == 0x74 && data[6] == 0x79 && data[7] == 0x70 else {
|
||||
return false
|
||||
}
|
||||
let boxSize = (UInt32(data[0]) << 24)
|
||||
| (UInt32(data[1]) << 16)
|
||||
| (UInt32(data[2]) << 8)
|
||||
| UInt32(data[3])
|
||||
// Standard 32-bit ftyp box size (>= 12 and within payload) or 64-bit extended size (1).
|
||||
return (boxSize >= 12 && Int(boxSize) <= data.count) || (boxSize == 1 && data.count >= 16)
|
||||
}
|
||||
|
||||
/// ADTS-framed AAC: 12-bit syncword (0xFFF) with MPEG layer bits == 00 and frame length >= 7.
|
||||
private static func matchesADTSAAC(_ data: Data) -> Bool {
|
||||
guard data.count >= 7 else { return false }
|
||||
guard data[0] == 0xFF && (data[1] & 0xF6) == 0xF0 else { return false }
|
||||
let frameLength = ((Int(data[3]) & 0x03) << 11)
|
||||
| (Int(data[4]) << 3)
|
||||
| ((Int(data[5]) & 0xE0) >> 5)
|
||||
return frameLength >= 7 && frameLength <= data.count
|
||||
}
|
||||
}
|
||||
|
||||
extension MimeType {
|
||||
|
||||
@@ -106,6 +106,7 @@ struct VoiceNoteView: View {
|
||||
.task {
|
||||
// Defer loading to let UI settle after view appears
|
||||
try? await Task.sleep(nanoseconds: 100_000_000) // 0.1s
|
||||
guard !Task.isCancelled else { return }
|
||||
playback.loadDuration()
|
||||
await withCheckedContinuation { continuation in
|
||||
WaveformCache.shared.waveform(for: url, completion: { bins in
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import AVFoundation
|
||||
import BitFoundation
|
||||
import Combine
|
||||
import CoreBluetooth
|
||||
@@ -1104,10 +1105,7 @@ struct PrivateMediaEndToEndTests {
|
||||
@Test
|
||||
func finalizedPrivateM4AIsOpaqueBeforeFragmentationAndDelivers() async throws {
|
||||
let marker = Data("M4A_PRIVATE_MARKER_e0cd431b61fb4a6c".utf8)
|
||||
let content = Data([0x00, 0x00, 0x00, 0x18])
|
||||
+ Data("ftypM4A ".utf8)
|
||||
+ marker
|
||||
+ Data(repeating: 0x4D, count: 6 * 1024)
|
||||
let content = try makeValidM4APayload(embedding: marker, extraPaddingBytes: 6 * 1024)
|
||||
try await assertPrivateMediaRoundTrip(
|
||||
fileName: "voice_0011223344556677.m4a",
|
||||
mimeType: "audio/mp4",
|
||||
@@ -1117,6 +1115,33 @@ struct PrivateMediaEndToEndTests {
|
||||
)
|
||||
}
|
||||
|
||||
/// Generates a real AAC `.m4a` container and appends a spec-compliant ISO BMFF
|
||||
/// `free` box carrying `marker` + padding so wire-opacity and fragmentation
|
||||
/// assertions run against an audio payload that passes ingest validation.
|
||||
private func makeValidM4APayload(embedding marker: Data, extraPaddingBytes: Int) throws -> Data {
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("e2e-voice-\(UUID().uuidString).m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let format = try #require(PTTAudioFormat.pcmFormat)
|
||||
let frameCount: AVAudioFrameCount = 1_600
|
||||
let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount))
|
||||
buffer.frameLength = frameCount
|
||||
do {
|
||||
// Releasing AVAudioFile finalizes the .m4a moov atom on disk.
|
||||
let file = try AVAudioFile(forWriting: url, settings: PTTAudioFormat.voiceNoteFileSettings)
|
||||
try file.write(from: buffer)
|
||||
}
|
||||
|
||||
var data = try Data(contentsOf: url)
|
||||
let freeBody = marker + Data(repeating: 0x4D, count: extraPaddingBytes)
|
||||
var boxSize = UInt32(8 + freeBody.count).bigEndian
|
||||
withUnsafeBytes(of: &boxSize) { data.append(contentsOf: $0) }
|
||||
data.append(contentsOf: Array("free".utf8))
|
||||
data.append(freeBody)
|
||||
return data
|
||||
}
|
||||
|
||||
@Test
|
||||
func capablePeerUsesCanonicalAndroid0x20EncryptedSend() async throws {
|
||||
let marker = Data("PDF_PRIVATE_MARKER_b333f84b8fc7478d".utf8)
|
||||
|
||||
@@ -58,6 +58,13 @@ struct MimeTypeTests {
|
||||
0x57, 0x45, 0x42, 0x50]), // "RIFF....WEBP"
|
||||
|
||||
// === Audio types ===
|
||||
(MimeType.mp4Audio, [0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70,
|
||||
0x4D, 0x34, 0x41, 0x20, 0x00, 0x00, 0x00, 0x00,
|
||||
0x4D, 0x34, 0x41, 0x20, 0x6D, 0x70, 0x34, 0x32]), // ISO BMFF ftypM4A
|
||||
(MimeType.m4a, [0x00, 0x00, 0x00, 0x14, 0x66, 0x74, 0x79, 0x70,
|
||||
0x69, 0x73, 0x6F, 0x6D, 0x00, 0x00, 0x02, 0x00,
|
||||
0x69, 0x73, 0x6F, 0x6D]), // ISO BMFF ftypisom
|
||||
(MimeType.aac, [0xFF, 0xF1, 0x5C, 0x40, 0x01, 0x1F, 0xFC, 0x00]), // ADTS AAC (frame len 8)
|
||||
(MimeType.mp3, [0x49, 0x44, 0x33]), // "ID3"
|
||||
(MimeType.wav, [0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00,
|
||||
0x57, 0x41, 0x56, 0x45]), // "RIFF....WAVE"
|
||||
@@ -81,6 +88,18 @@ struct MimeTypeTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test func cafContainerAndArbitraryPaddingRejectedForAudioMimes() throws {
|
||||
// Previously audio/mp4, audio/m4a, and audio/aac only checked data.count > 100,
|
||||
// letting a 268-byte CAF file pass as an M4A voice note.
|
||||
let cafPrefix = Data("caff".utf8) + Data(repeating: 0x00, count: 264)
|
||||
let arbitrary = Data(repeating: 0x41, count: 268)
|
||||
|
||||
for mime in [MimeType.mp4Audio, .m4a, .aac, .mp3, .mpeg, .wav, .xWav, .ogg] {
|
||||
#expect(!mime.matches(data: cafPrefix), "CAF should not match \(mime.mimeString)")
|
||||
#expect(!mime.matches(data: arbitrary), "Arbitrary bytes should not match \(mime.mimeString)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Octet-stream (generic binary)
|
||||
@Test func octetStreamAlwaysMatches() throws {
|
||||
let randomData = Data([0x00, 0x11, 0x22, 0x33])
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//
|
||||
// WaveformTests.swift
|
||||
// bitchatTests
|
||||
//
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
// For more information, see <https://unlicense.org>
|
||||
//
|
||||
|
||||
import AVFoundation
|
||||
import Foundation
|
||||
import Testing
|
||||
|
||||
@testable import bitchat
|
||||
|
||||
@Suite("Waveform & Audio Ingest Hardening Tests")
|
||||
struct WaveformTests {
|
||||
@Test("Crafted CAF claiming 2^40 data bytes does not crash waveform extraction and is rejected at ingest")
|
||||
func craftedGiantCAFRejectedWithoutCrash() throws {
|
||||
let cafData = makeCraftedCAF(claimedDataBytes: Int64(1) << 40)
|
||||
#expect(cafData.count < 512)
|
||||
|
||||
// 1. Direct waveform extraction must refuse out-of-range frame counts cleanly instead of trapping.
|
||||
let tempURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("crafted-giant-\(UUID().uuidString).m4a")
|
||||
try cafData.write(to: tempURL)
|
||||
defer { try? FileManager.default.removeItem(at: tempURL) }
|
||||
|
||||
#expect(WaveformCache.computeWaveform(url: tempURL, bins: 64) == nil)
|
||||
|
||||
// 2. Ingest validator must reject CAF disguised as any audio MIME type.
|
||||
for mimeType in ["audio/mp4", "audio/m4a", "audio/aac", "audio/wav", "audio/mpeg"] {
|
||||
let packet = BitchatFilePacket(
|
||||
fileName: "voice_crafted.m4a",
|
||||
fileSize: UInt64(cafData.count),
|
||||
mimeType: mimeType,
|
||||
content: cafData
|
||||
)
|
||||
let encoded = try #require(packet.encode())
|
||||
let result = BLEIncomingFileValidator.validate(payload: encoded)
|
||||
guard case .failure(.magicMismatch) = result else {
|
||||
Issue.record("Expected magicMismatch for CAF with \(mimeType), got \(result)")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Crafted WAV declaring an oversized duration is rejected at ingest and by WaveformCache")
|
||||
func craftedGiantWAVRejected() throws {
|
||||
// Valid RIFF/WAVE at 10 Hz mono 16-bit PCM carrying 7,000 samples (700s > 600s cap)
|
||||
// in only ~14 KiB of payload.
|
||||
let sampleCount = 7_000
|
||||
let wavData = makeCraftedWAV(sampleRate: 10, sampleCount: sampleCount)
|
||||
|
||||
let packet = BitchatFilePacket(
|
||||
fileName: "voice_huge.wav",
|
||||
fileSize: UInt64(wavData.count),
|
||||
mimeType: "audio/wav",
|
||||
content: wavData
|
||||
)
|
||||
let encoded = try #require(packet.encode())
|
||||
let result = BLEIncomingFileValidator.validate(payload: encoded)
|
||||
guard case .failure(.invalidAudio(let mime, _, _)) = result else {
|
||||
Issue.record("Expected invalidAudio for oversized WAV, got \(result)")
|
||||
return
|
||||
}
|
||||
#expect(mime == .wav)
|
||||
|
||||
let tempURL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("crafted-huge-\(UUID().uuidString).wav")
|
||||
try wavData.write(to: tempURL)
|
||||
defer { try? FileManager.default.removeItem(at: tempURL) }
|
||||
|
||||
#expect(WaveformCache.computeWaveform(url: tempURL, bins: 64) == nil)
|
||||
}
|
||||
|
||||
@Test("Unparseable ftyp prefix garbage is rejected by audio ingest validator")
|
||||
func unparseableFtypGarbageRejected() throws {
|
||||
let fakeM4A = Data([0x00, 0x00, 0x00, 0x18])
|
||||
+ Data("ftypM4A ".utf8)
|
||||
+ Data(repeating: 0x00, count: 12)
|
||||
+ Data(repeating: 0x42, count: 256)
|
||||
let packet = BitchatFilePacket(
|
||||
fileName: "voice_fake.m4a",
|
||||
fileSize: UInt64(fakeM4A.count),
|
||||
mimeType: "audio/mp4",
|
||||
content: fakeM4A
|
||||
)
|
||||
let encoded = try #require(packet.encode())
|
||||
let result = BLEIncomingFileValidator.validate(payload: encoded)
|
||||
guard case .failure(.invalidAudio(let mime, _, _)) = result else {
|
||||
Issue.record("Expected invalidAudio for truncated/fake M4A, got \(result)")
|
||||
return
|
||||
}
|
||||
#expect(mime == .mp4Audio)
|
||||
}
|
||||
|
||||
@Test("Valid M4A passes audio ingest validation and produces normalized waveform across multiple read chunks")
|
||||
func validM4APassesIngestAndChunkedWaveform() throws {
|
||||
// 1.2 seconds at 16 kHz = 19,200 frames (> 8,192 chunk capacity), exercising multi-chunk reads.
|
||||
let m4aURL = try makeValidM4A(durationSeconds: 1.2)
|
||||
defer { try? FileManager.default.removeItem(at: m4aURL) }
|
||||
|
||||
let data = try Data(contentsOf: m4aURL)
|
||||
let packet = BitchatFilePacket(
|
||||
fileName: "voice_valid.m4a",
|
||||
fileSize: UInt64(data.count),
|
||||
mimeType: "audio/mp4",
|
||||
content: data
|
||||
)
|
||||
let encoded = try #require(packet.encode())
|
||||
let result = BLEIncomingFileValidator.validate(payload: encoded)
|
||||
guard case .success(let acceptance) = result else {
|
||||
Issue.record("Expected valid M4A to pass ingest, got \(result)")
|
||||
return
|
||||
}
|
||||
#expect(acceptance.mime == .mp4Audio)
|
||||
|
||||
let bins = try #require(WaveformCache.computeWaveform(url: m4aURL, bins: 32))
|
||||
#expect(bins.count == 32)
|
||||
#expect(bins.allSatisfy { $0.isFinite && $0 >= 0 && $0 <= 1.0 })
|
||||
#expect((bins.max() ?? 0) > 0.5)
|
||||
}
|
||||
|
||||
// MARK: - Fixtures
|
||||
|
||||
/// Minimal Apple CAF header (big-endian) with a Linear PCM `desc` chunk and a `data` chunk
|
||||
/// claiming `claimedDataBytes` while carrying only a handful of actual payload bytes.
|
||||
private func makeCraftedCAF(claimedDataBytes: Int64) -> Data {
|
||||
var data = Data()
|
||||
// File header: "caff" + version (1) + flags (0)
|
||||
data.append(contentsOf: Array("caff".utf8))
|
||||
appendBE(&data, UInt16(1))
|
||||
appendBE(&data, UInt16(0))
|
||||
|
||||
// Audio Description chunk ("desc", 32 bytes): 16 kHz, lpcm, 2 bytes/packet, 1 frame/packet, 1 ch, 16-bit
|
||||
data.append(contentsOf: Array("desc".utf8))
|
||||
appendBE(&data, Int64(32))
|
||||
appendBE(&data, Float64(16_000).bitPattern) // mSampleRate
|
||||
data.append(contentsOf: Array("lpcm".utf8)) // mFormatID
|
||||
appendBE(&data, UInt32(0)) // mFormatFlags
|
||||
appendBE(&data, UInt32(2)) // mBytesPerPacket
|
||||
appendBE(&data, UInt32(1)) // mFramesPerPacket
|
||||
appendBE(&data, UInt32(1)) // mChannelsPerFrame
|
||||
appendBE(&data, UInt32(16)) // mBitsPerChannel
|
||||
|
||||
// Audio Data chunk ("data"): editCount (4 bytes) + claimed data bytes
|
||||
data.append(contentsOf: Array("data".utf8))
|
||||
appendBE(&data, claimedDataBytes)
|
||||
appendBE(&data, UInt32(0)) // mEditCount
|
||||
data.append(Data(repeating: 0, count: 200))
|
||||
return data
|
||||
}
|
||||
|
||||
private func makeCraftedWAV(sampleRate: UInt32, sampleCount: Int) -> Data {
|
||||
let dataBytes = UInt32(sampleCount * 2)
|
||||
var data = Data()
|
||||
// RIFF header
|
||||
data.append(contentsOf: Array("RIFF".utf8))
|
||||
appendLE(&data, dataBytes &+ 36)
|
||||
data.append(contentsOf: Array("WAVE".utf8))
|
||||
|
||||
// fmt chunk (16 bytes, PCM, mono, 16-bit)
|
||||
data.append(contentsOf: Array("fmt ".utf8))
|
||||
appendLE(&data, UInt32(16))
|
||||
appendLE(&data, UInt16(1)) // PCM
|
||||
appendLE(&data, UInt16(1)) // mono
|
||||
appendLE(&data, sampleRate)
|
||||
appendLE(&data, sampleRate * 2) // byte rate
|
||||
appendLE(&data, UInt16(2)) // block align
|
||||
appendLE(&data, UInt16(16)) // bits per sample
|
||||
|
||||
// data chunk
|
||||
data.append(contentsOf: Array("data".utf8))
|
||||
appendLE(&data, dataBytes)
|
||||
data.append(Data(repeating: 0, count: Int(dataBytes)))
|
||||
return data
|
||||
}
|
||||
|
||||
private func makeValidM4A(durationSeconds: Double) throws -> URL {
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("valid-waveform-\(UUID().uuidString).m4a")
|
||||
let pcmFormat = try #require(PTTAudioFormat.pcmFormat)
|
||||
let frameCount = AVAudioFrameCount(durationSeconds * PTTAudioFormat.sampleRate)
|
||||
let buffer = try #require(AVAudioPCMBuffer(pcmFormat: pcmFormat, frameCapacity: frameCount))
|
||||
buffer.frameLength = frameCount
|
||||
if let channel = buffer.floatChannelData?[0] {
|
||||
for index in 0..<Int(frameCount) {
|
||||
let phase = 2.0 * Float.pi * 440.0 * Float(index) / Float(PTTAudioFormat.sampleRate)
|
||||
channel[index] = 0.5 * sinf(phase)
|
||||
}
|
||||
}
|
||||
do {
|
||||
let file = try AVAudioFile(forWriting: url, settings: PTTAudioFormat.voiceNoteFileSettings)
|
||||
try file.write(from: buffer)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
private func appendBE<T: FixedWidthInteger>(_ data: inout Data, _ value: T) {
|
||||
var big = value.bigEndian
|
||||
withUnsafeBytes(of: &big) { data.append(contentsOf: $0) }
|
||||
}
|
||||
|
||||
private func appendLE<T: FixedWidthInteger>(_ data: inout Data, _ value: T) {
|
||||
var little = value.littleEndian
|
||||
withUnsafeBytes(of: &little) { data.append(contentsOf: $0) }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user