diff --git a/provider-swift/Sources/ProviderCore/Inference/MLXMemoryGuard.swift b/provider-swift/Sources/ProviderCore/Inference/MLXMemoryGuard.swift index 8c7ada0948..f229b180e8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/MLXMemoryGuard.swift +++ b/provider-swift/Sources/ProviderCore/Inference/MLXMemoryGuard.swift @@ -46,11 +46,23 @@ public enum MLXMemoryGuard { ) -> UInt64 { if let explicit { return explicit } if let raw = env["DARKBLOOM_MLX_MEMORY_RESERVE_GB"], let gb = Double(raw), gb >= 0, gb.isFinite { - return UInt64(min(gb * 1_073_741_824, Double(UInt64.max))) + // Saturate WITHOUT `UInt64(Double(UInt64.max))`: that round-trip rounds + // UInt64.max up to 2^64, which is outside UInt64, so `UInt64(...)` traps + // — a huge finite reserve override would crash the provider during + // configureOnce() at startup/model load. `uint64MaxAsDouble` is exactly + // 2^64; anything ≥ it saturates. Mirrors the VLM env clamps. + let scaled = gb * 1_073_741_824 + return scaled >= uint64MaxAsDouble ? UInt64.max : UInt64(scaled) } return saturatingGiBToBytes(defaultReserveGB) } + /// `Double(UInt64.max)` rounded to the nearest representable Double — exactly + /// 2^64 (one more than `UInt64.max`). Used as the saturation threshold so a + /// `>= uint64MaxAsDouble` comparison catches every value that would trap on + /// `UInt64(_:)` conversion. + static let uint64MaxAsDouble = Double(UInt64.max) + private static func saturatingGiBToBytes(_ gib: UInt64) -> UInt64 { let (bytes, overflow) = gib.multipliedReportingOverflow(by: 1_073_741_824) return overflow ? UInt64.max : bytes diff --git a/provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift index 0faca69d6b..73dfdefb34 100644 --- a/provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift @@ -193,6 +193,19 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // batched engine. For VLM models, serve them via the container's // non-batched prepare/generate vision path. if isVLM, let container, VLMRequestInference.hasMedia(request) { + // Decode + validate inline media SYNCHRONOUSLY, before returning the + // stream. A MediaError (oversized/malformed/non-`data:` payload) thrown + // here propagates through this `async throws` to the caller — so both + // the buffered (non-streaming) and the SSE (streaming) HTTP paths, and + // the coordinator WebSocket path, surface the correct 4xx instead of a + // 200 with a truncated/error stream body. (Deferring the decode into + // the generation task would let the HTTP layer commit a 200 first.) + do { + try await VLMRequestInference.validateMedia(request) + } catch { + await releaseBox.fire() + throw error + } let vlmStream = VLMRequestInference.stream( container: container, request: request, defaultMaxTokens: defaultMaxTokens) return AsyncThrowingStream { continuation in diff --git a/provider-swift/Sources/ProviderCore/Inference/VLMRequestInference.swift b/provider-swift/Sources/ProviderCore/Inference/VLMRequestInference.swift index 235db8be03..903e1cf8a2 100644 --- a/provider-swift/Sources/ProviderCore/Inference/VLMRequestInference.swift +++ b/provider-swift/Sources/ProviderCore/Inference/VLMRequestInference.swift @@ -15,8 +15,10 @@ // `VLMRequestInference.hasMedia` and, when true for a VLM model, // delegates to `VLMRequestInference.stream`. +import AVFoundation import CoreImage import Foundation +import ImageIO import MLXLMCommon import MLXLMServer @@ -40,6 +42,7 @@ public enum VLMRequestInference { case imageDecodeFailed case invalidURL(String) case videoWriteFailed(String) + case mediaTooLarge(String) public var description: String { switch self { @@ -59,6 +62,8 @@ public enum VLMRequestInference { return "media must be sent as an inline base64 data: URI (e.g. \"data:image/jpeg;base64,…\") on this end-to-end-encrypted endpoint; remote http(s):// and file:// URLs are rejected. Got: \(shown)" case .videoWriteFailed(let detail): return "failed to write inline video to a temp file (\(detail))" + case .mediaTooLarge(let detail): + return "inline media exceeds a decode limit (\(detail))" } } @@ -95,6 +100,37 @@ public enum VLMRequestInference { /// `.content` chunks during generation, then a final `.info` carrying /// token counts and timing. Inline-video temp files are removed when /// the stream ends (normal completion, error, or cancellation). + /// Validate all inline media for a request UP FRONT, throwing `MediaError` + /// synchronously on any oversized/malformed/non-`data:` payload (or video-cap + /// violation). Callers MUST call this (and propagate the throw) BEFORE + /// returning a streaming response, so the correct 4xx is surfaced instead of + /// a 200 SSE body that only errors mid-iteration — `stream` builds its own + /// `UserInput` inside the generation task (UserInput isn't Sendable, so it + /// can't cross the task boundary), which is why validation is a separate + /// pass here rather than handing the decoded input through. + /// + /// This runs the same decode path as `stream` (`buildUserInput`) purely for + /// its throwing side-effects and discards the result; any inline-video temp + /// file it writes is removed before returning. The decode work is bounded by + /// the very caps it enforces (≤ per-image / aggregate pixels, ≤ byte cap), so + /// the up-front pass can't itself be a DoS, and the eventual rebuild inside + /// `stream` re-validates identically. + public static func validateMedia( + _ request: OpenAIChatCompletionRequest, + maxImagePixels: Int = Self.maxImagePixels, + maxRequestImagePixels: Int = Self.maxRequestImagePixels, + maxVideosPerRequest: Int = Self.maxVideosPerRequest, + maxRequestVideoFramePixels: Int = Self.maxRequestVideoFramePixels + ) async throws { + var tempFiles: [URL] = [] + defer { for url in tempFiles { try? FileManager.default.removeItem(at: url) } } + _ = try await buildUserInput( + from: request, tempFiles: &tempFiles, maxImagePixels: maxImagePixels, + maxRequestImagePixels: maxRequestImagePixels, + maxVideosPerRequest: maxVideosPerRequest, + maxRequestVideoFramePixels: maxRequestVideoFramePixels) + } + public static func stream( container: ModelContainer, request: OpenAIChatCompletionRequest, @@ -103,7 +139,11 @@ public enum VLMRequestInference { AsyncThrowingStream { continuation in let task = Task { // Inline `data:` videos are materialized to temp files for - // AVFoundation; track them so we can clean up on exit. + // AVFoundation; track them so we can clean up on exit. Media was + // already validated up front by `validateMedia` (so an oversized + // payload surfaced its 4xx before this stream was returned); the + // rebuild here re-runs the same decode to produce the UserInput + // (which isn't Sendable and so can't cross the task boundary). var tempFiles: [URL] = [] defer { for url in tempFiles { @@ -113,7 +153,7 @@ public enum VLMRequestInference { let userInput: UserInput do { - userInput = try buildUserInput(from: request, tempFiles: &tempFiles) + userInput = try await buildUserInput(from: request, tempFiles: &tempFiles) } catch { continuation.finish(throwing: error) return @@ -204,12 +244,24 @@ public enum VLMRequestInference { /// remove them when the stream ends. static func buildUserInput( from request: OpenAIChatCompletionRequest, - tempFiles: inout [URL] - ) throws -> UserInput { + tempFiles: inout [URL], + maxImagePixels: Int = Self.maxImagePixels, + maxRequestImagePixels: Int = Self.maxRequestImagePixels, + maxVideosPerRequest: Int = Self.maxVideosPerRequest, + maxRequestVideoFramePixels: Int = Self.maxRequestVideoFramePixels + ) async throws -> UserInput { var chatMessages: [Chat.Message] = [] + var totalPixels = 0 + var totalVideoPixels = 0 + var videoCount = 0 for message in request.messages { - let (text, images, videos) = try parts( - from: message.content, tempFiles: &tempFiles) + let (text, images, videos) = try await parts( + from: message.content, tempFiles: &tempFiles, totalPixels: &totalPixels, + totalVideoPixels: &totalVideoPixels, videoCount: &videoCount, + maxImagePixels: maxImagePixels, + maxRequestImagePixels: maxRequestImagePixels, + maxVideosPerRequest: maxVideosPerRequest, + maxRequestVideoFramePixels: maxRequestVideoFramePixels) switch message.role { case .user: chatMessages.append(.user(text, images: images, videos: videos)) @@ -227,10 +279,18 @@ public enum VLMRequestInference { /// Convenience overload that discards temp-file tracking. Used by /// tests that pass only base64/url images (no inline videos). static func buildUserInput( - from request: OpenAIChatCompletionRequest - ) throws -> UserInput { + from request: OpenAIChatCompletionRequest, + maxImagePixels: Int = Self.maxImagePixels, + maxRequestImagePixels: Int = Self.maxRequestImagePixels, + maxVideosPerRequest: Int = Self.maxVideosPerRequest, + maxRequestVideoFramePixels: Int = Self.maxRequestVideoFramePixels + ) async throws -> UserInput { var sink: [URL] = [] - return try buildUserInput(from: request, tempFiles: &sink) + return try await buildUserInput( + from: request, tempFiles: &sink, maxImagePixels: maxImagePixels, + maxRequestImagePixels: maxRequestImagePixels, + maxVideosPerRequest: maxVideosPerRequest, + maxRequestVideoFramePixels: maxRequestVideoFramePixels) } /// Split a message's content into the concatenated text plus decoded @@ -239,8 +299,15 @@ public enum VLMRequestInference { /// rather than being silently ignored. private static func parts( from content: OpenAIMessageContent, - tempFiles: inout [URL] - ) throws -> (text: String, images: [UserInput.Image], videos: [UserInput.Video]) { + tempFiles: inout [URL], + totalPixels: inout Int, + totalVideoPixels: inout Int, + videoCount: inout Int, + maxImagePixels: Int, + maxRequestImagePixels: Int, + maxVideosPerRequest: Int, + maxRequestVideoFramePixels: Int + ) async throws -> (text: String, images: [UserInput.Image], videos: [UserInput.Video]) { switch content { case .text(let string): return (string, [], []) @@ -255,9 +322,68 @@ public enum VLMRequestInference { case .text(let string): text += string case .imageURL(let uri): - images.append(try decodeImage(uri)) + guard uri.hasPrefix("data:") else { + throw MediaError.invalidURL(uri) + } + let data = try dataFromDataURI(uri) + // Charge the request-wide aggregate from the HEADER pixel count + // BEFORE decoding — CIImage(data:) is the allocation we're + // guarding against, so an over-aggregate request (with prior + // images already retained) must be rejected before this image's + // raster is ever materialized. Overflow-safe (matches + // imagePixelCount). The header read is O(header), ~0 RSS. + // + // When the header is unreadable (imagePixelCount nil), charge + // 0 here and let decodeImageData enforce the per-image cap on + // the realized extent; the post-decode extent is then folded + // into the aggregate below so a nil-header image still counts. + let headerPixels = imagePixelCount(data) ?? 0 + let (preSum, preOverflow) = + totalPixels.addingReportingOverflow(headerPixels) + let projectedTotal = preOverflow ? Int.max : preSum + guard projectedTotal <= maxRequestImagePixels else { + throw MediaError.mediaTooLarge( + "request images total \(projectedTotal) px; aggregate cap is " + + "\(maxRequestImagePixels) px") + } + // Within aggregate: now decode (per-image cap + extent backstop). + let image = try decodeImageData(data, maxImagePixels: maxImagePixels) + // Reconcile the aggregate with the REALIZED extent: when the + // header was readable both are equal; when it was nil the + // extent is the real charge. Re-check so a nil-header image + // can't slip an over-aggregate raster through. + if case .ciImage(let ci) = image { + let realized = safeExtentPixels(ci.extent) + let charge = max(headerPixels, realized) + let (sum, overflow) = + totalPixels.addingReportingOverflow(charge) + totalPixels = overflow ? Int.max : sum + guard totalPixels <= maxRequestImagePixels else { + throw MediaError.mediaTooLarge( + "request images total \(totalPixels) px; aggregate cap is " + + "\(maxRequestImagePixels) px") + } + } + images.append(image) case .videoURL(let uri): - videos.append(try decodeVideo(uri, tempFiles: &tempFiles)) + // Per-request video caps: count + summed per-frame pixels. + // The model samples up to N frames PER video, so a per-video + // cap alone doesn't bound many-tiny-videos amplification. + videoCount += 1 + guard videoCount <= maxVideosPerRequest else { + throw MediaError.mediaTooLarge( + "request has \(videoCount) videos; cap is \(maxVideosPerRequest)") + } + let decoded = try await decodeVideo(uri, tempFiles: &tempFiles) + let (sum, overflow) = + totalVideoPixels.addingReportingOverflow(decoded.framePixels) + totalVideoPixels = overflow ? Int.max : sum + guard totalVideoPixels <= maxRequestVideoFramePixels else { + throw MediaError.mediaTooLarge( + "request video frames total \(totalVideoPixels) px; aggregate cap is " + + "\(maxRequestVideoFramePixels) px") + } + videos.append(decoded.video) case .unsupported: continue } @@ -266,6 +392,145 @@ public enum VLMRequestInference { } } + // MARK: - Media limits (decompression-bomb guard) + + // `CIImage(data:)` eagerly rasterizes (W*H*4 bytes) and has no scaled-decode + // for PNG, so a tiny highly-compressed "bomb" (a uniform 40000x40000 PNG is + // ~5 MB on the wire — well under the 32 MiB WS frame cap) explodes on decode. + // Measured on M-series hardware: even the real resample-to-448 provider path + // peaks at 1.78 GB for a 16000^2 input and 5.73 GB at 32000^2, all *before* + // any KV/token/load admission runs. These caps reject such inputs from the + // format header, before the raster is ever allocated. Defaults are generous + // for genuine media (a 100 MP camera frame is 100 Mpx) yet bound the + // otherwise-unbounded allocation; all are env-tunable. + + /// Per-image pixel ceiling (width × height). Rejected from the header. + public static let maxImagePixels = resolveMaxPixels( + env: "DARKBLOOM_MAX_IMAGE_MEGAPIXELS", defaultMegapixels: 100) + + /// Aggregate pixel ceiling across all image parts in one request — bounds + /// the "pack many max-size images into one frame" amplification. + public static let maxRequestImagePixels = resolveMaxPixels( + env: "DARKBLOOM_MAX_REQUEST_IMAGE_MEGAPIXELS", defaultMegapixels: 384) + + /// Per-part decoded-byte ceiling for a `data:` payload (image or video). + /// Bounds the inline-video temp file + in-RAM buffer too. + public static let maxMediaDecodedBytes = resolveMaxBytes( + env: "DARKBLOOM_MAX_MEDIA_MIB", defaultMiB: 25) + + /// Inline-video duration ceiling (seconds) — bounds how many frames the + /// model samples/decodes from one clip. A video's per-frame pixels are + /// capped at ``maxImagePixels`` (a frame is an image). + public static let maxVideoDurationSeconds = resolveMaxSeconds( + env: "DARKBLOOM_MAX_VIDEO_SECONDS", defaultSeconds: 600) + + /// Max inline video parts per request — bounds the "many tiny valid MP4s" + /// amplification (each video passes per-part checks, but the model samples + /// up to N frames PER video, so aggregate frame/tensor work still explodes). + public static let maxVideosPerRequest = resolveMaxCount( + env: "DARKBLOOM_MAX_VIDEOS_PER_REQUEST", defaultCount: 8) + + /// Aggregate per-frame pixel ceiling summed across every video in a request + /// (the video analog of `maxRequestImagePixels`). + public static let maxRequestVideoFramePixels = resolveMaxPixels( + env: "DARKBLOOM_MAX_REQUEST_VIDEO_FRAME_MEGAPIXELS", defaultMegapixels: 384) + + /// Resolve a megapixel limit from `env` (a positive megapixel count) or fall + /// back to `defaultMegapixels`. Injectable environment for tests. + static func resolveMaxPixels( + env name: String, defaultMegapixels: Int, + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> Int { + if let raw = environment[name], let mp = Double(raw), mp > 0, mp.isFinite { + // Clamp to Int.max WITHOUT `Int(Double(Int.max))`: that round-trip + // rounds 2^63−1 up to 2^63, which is > Int.max, so `Int(...)` traps + // (a single huge env override would crash the provider at static + // init). `intMaxAsDouble` is exactly 2^63; anything ≥ it saturates. + let scaled = mp * 1_000_000 + return scaled >= intMaxAsDouble ? Int.max : Int(scaled) + } + return defaultMegapixels * 1_000_000 + } + + /// `Double(Int.max)` rounded to the nearest representable Double — exactly + /// 2^63 (one more than `Int.max`). Used as the saturation threshold for env + /// clamps so a comparison `>= intMaxAsDouble` catches every value that would + /// trap on `Int(_:)` conversion. + static let intMaxAsDouble = Double(Int.max) + + /// Resolve a byte limit from `env` (a positive MiB count) or `defaultMiB`. + static func resolveMaxBytes( + env name: String, defaultMiB: Int, + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> Int { + if let raw = environment[name], let mib = Int(raw), mib > 0 { + // Saturate instead of trapping: `mib * 1024 * 1024` overflows for a + // large-but-parseable Int, which would crash the provider at static + // init from a single bad byte-limit override. + let (bytes, overflow) = mib.multipliedReportingOverflow(by: 1024 * 1024) + return overflow ? Int.max : bytes + } + return defaultMiB * 1024 * 1024 + } + + /// Resolve a seconds limit from `env` (a positive number) or `defaultSeconds`. + static func resolveMaxSeconds( + env name: String, defaultSeconds: Double, + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> Double { + if let raw = environment[name], let s = Double(raw), s > 0, s.isFinite { + return s + } + return defaultSeconds + } + + /// Resolve a positive integer count from `env` or `defaultCount`. + static func resolveMaxCount( + env name: String, defaultCount: Int, + environment: [String: String] = ProcessInfo.processInfo.environment + ) -> Int { + if let raw = environment[name], let n = Int(raw), n > 0 { return n } + return defaultCount + } + + /// Pixel count (width × height) read from the image's format **header only** + /// — no raster decode (proven O(header): ~0 MB RSS even for a gigapixel + /// bomb). Returns `nil` if ImageIO can't size the data (truncated/unknown + /// format), in which case `CIImage(data:)` fails closed downstream. + static func imagePixelCount(_ data: Data) -> Int? { + guard let src = CGImageSourceCreateWithData(data as CFData, nil), + let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as? [CFString: Any], + let w = props[kCGImagePropertyPixelWidth] as? Int, + let h = props[kCGImagePropertyPixelHeight] as? Int, + w > 0, h > 0 + else { return nil } + let (product, overflow) = w.multipliedReportingOverflow(by: h) + return overflow ? Int.max : product + } + + /// Render a (possibly extreme/untrusted) seconds value for an error message + /// without ever converting to `Int` — `Int(Double)` traps for values beyond + /// `Int.max` or non-finite. Whole numbers print without a decimal point so + /// the common "600s" case reads cleanly. + static func secondsString(_ s: Double) -> String { + guard s.isFinite else { return "\(s)" } // "inf" / "nan" + return s == s.rounded() && abs(s) < 1e15 + ? String(Int64(s)) + : String(format: "%.1f", s) + } + + /// Overflow/NaN-safe pixel count of a realized `CIImage`/track extent. + /// Returns 0 for a non-finite or sub-pixel extent (treated as "no charge"). + static func safeExtentPixels(_ extent: CGRect) -> Int { + guard extent.width.isFinite, extent.height.isFinite, + extent.width >= 1, extent.height >= 1 + else { return 0 } + let w = extent.width >= Double(Int.max) ? Int.max : Int(extent.width) + let h = extent.height >= Double(Int.max) ? Int.max : Int(extent.height) + let (product, overflow) = w.multipliedReportingOverflow(by: h) + return overflow ? Int.max : product + } + // MARK: - Media decode /// Decode an image content part. Inline `data:` URIs are decoded @@ -276,14 +541,42 @@ public enum VLMRequestInference { /// request drive `CIImage(contentsOf:)` into an SSRF / local-file-read /// primitive (the provider is the fetcher), so a non-`data:` URI fails /// closed with `invalidURL`. - static func decodeImage(_ uri: String) throws -> UserInput.Image { + static func decodeImage( + _ uri: String, maxImagePixels: Int = Self.maxImagePixels + ) throws -> UserInput.Image { guard uri.hasPrefix("data:") else { throw MediaError.invalidURL(uri) } let data = try dataFromDataURI(uri) + return try decodeImageData(data, maxImagePixels: maxImagePixels) + } + + /// Decode already-extracted image bytes into a `CIImage`, enforcing the + /// per-image pixel cap from the format header BEFORE `CIImage(data:)` eagerly + /// rasterizes (the allocation happens at decode, not at first use — there is + /// no lazy escape, and the model's downscale doesn't help because CoreImage + /// decodes the full-res source first), plus a post-decode extent backstop. + /// + /// Split out of `decodeImage` so the request-aggregate path (`parts`) can read + /// the header and charge the aggregate BEFORE this allocates the raster. + static func decodeImageData( + _ data: Data, maxImagePixels: Int = Self.maxImagePixels + ) throws -> UserInput.Image { + if let pixels = imagePixelCount(data), pixels > maxImagePixels { + throw MediaError.mediaTooLarge( + "image is \(pixels) px; per-image cap is \(maxImagePixels) px") + } guard let image = CIImage(data: data) else { throw MediaError.imageDecodeFailed } + // Backstop: if ImageIO couldn't size the header (imagePixelCount nil) but + // CIImage still rasterized, enforce the cap on the realized extent so the + // nil-fallthrough can't carry an oversized raster downstream. + let extentPixels = safeExtentPixels(image.extent) + if extentPixels > maxImagePixels { + throw MediaError.mediaTooLarge( + "image extent is \(extentPixels) px; per-image cap is \(maxImagePixels) px") + } return .ciImage(image) } @@ -295,12 +588,15 @@ public enum VLMRequestInference { /// only legitimate media transport on this E2E-encrypted provider is an /// inline `data:` URI, so a non-`data:` URI fails closed with `invalidURL`. static func decodeVideo( - _ uri: String, tempFiles: inout [URL] - ) throws -> UserInput.Video { + _ uri: String, tempFiles: inout [URL], + maxFramePixels: Int = Self.maxImagePixels, + maxVideoDurationSeconds: Double = Self.maxVideoDurationSeconds, + maxMediaDecodedBytes: Int = Self.maxMediaDecodedBytes + ) async throws -> (video: UserInput.Video, framePixels: Int) { guard uri.hasPrefix("data:") else { throw MediaError.invalidURL(uri) } - let data = try dataFromDataURI(uri) + let data = try dataFromDataURI(uri, maxMediaDecodedBytes: maxMediaDecodedBytes) let tempURL = FileManager.default.temporaryDirectory .appendingPathComponent("vlm-\(UUID().uuidString).mp4") do { @@ -308,14 +604,88 @@ public enum VLMRequestInference { } catch { throw MediaError.videoWriteFailed(String(describing: error)) } + // Reject a video bomb (huge frames / very long clip) before the model + // decodes frames — the byte cap alone doesn't bound the decoded raster. + // Read track metadata only; no frame decode. The temp file isn't tracked + // in `tempFiles` until it passes, so remove it on the reject path. + let framePixels: Int + do { + framePixels = try await enforceVideoLimits( + tempURL, maxFramePixels: maxFramePixels, + maxDurationSeconds: maxVideoDurationSeconds) + } catch { + try? FileManager.default.removeItem(at: tempURL) + throw error + } tempFiles.append(tempURL) - return .url(tempURL) + return (.url(tempURL), framePixels) + } + + /// Reject a video bomb using track metadata only (no frame decode). Fails + /// CLOSED: the byte cap does NOT bound decoded frame pixels or the sampled + /// frame count, so a video whose duration or any track's frame dimensions + /// can't be read and proven within cap is rejected. The model samples frames + /// from these same properties, so a video it can actually use is always + /// probeable here — fail-closed never rejects a usable video. + @discardableResult + static func enforceVideoLimits( + _ url: URL, maxFramePixels: Int, maxDurationSeconds: Double + ) async throws -> Int { + let asset = AVURLAsset(url: url) + + // Duration bounds the sampled frame count (frames = duration × fps). + // Unreadable / non-finite / over-cap → reject. + guard let duration = try? await asset.load(.duration), duration.seconds.isFinite else { + throw MediaError.mediaTooLarge("video duration is unreadable") + } + guard duration.seconds <= maxDurationSeconds else { + // Format as Double, not Int: this is untrusted metadata, and a + // duration > Int.max seconds would trap on `Int(_:)` while building + // the rejection message — turning a fail-closed 400 into a crash. + throw MediaError.mediaTooLarge( + "video is \(secondsString(duration.seconds))s; duration cap is " + + "\(secondsString(maxDurationSeconds))s") + } + + guard let tracks = try? await asset.loadTracks(withMediaType: .video), !tracks.isEmpty + else { + throw MediaError.mediaTooLarge("no readable video track") + } + // EVERY track's CODED frame dimensions (what the decoder allocates before + // AVAssetImageGenerator scales to naturalSize) must be readable and ≤ cap. + // A file can understate naturalSize while coding huge frames, so charge + // the larger of naturalSize and the format-description dimensions. + var maxTrackPixels = 0 + for track in tracks { + guard let formats = try? await track.load(.formatDescriptions), !formats.isEmpty else { + throw MediaError.mediaTooLarge("video frame dimensions are unreadable") + } + var framePixels = 0 + if let size = try? await track.load(.naturalSize) { + framePixels = safeExtentPixels(CGRect(origin: .zero, size: size)) + } + for desc in formats { + let dims = CMVideoFormatDescriptionGetDimensions(desc) + framePixels = max( + framePixels, + safeExtentPixels( + CGRect(x: 0, y: 0, width: Int(dims.width), height: Int(dims.height)))) + } + if framePixels > maxFramePixels { + throw MediaError.mediaTooLarge( + "video frame is \(framePixels) px; per-frame cap is \(maxFramePixels) px") + } + maxTrackPixels = max(maxTrackPixels, framePixels) + } + return maxTrackPixels } /// Extract the raw bytes from a `data:` URI. The header before the /// first comma decides the encoding: `;base64` ⇒ base64, otherwise /// the payload is percent-encoded UTF-8 text. - static func dataFromDataURI(_ uri: String) throws -> Data { + static func dataFromDataURI( + _ uri: String, maxMediaDecodedBytes: Int = Self.maxMediaDecodedBytes + ) throws -> Data { guard let commaIndex = uri.firstIndex(of: ",") else { throw MediaError.malformedDataURI("missing ','") } @@ -324,17 +694,42 @@ public enum VLMRequestInference { if header.contains(";base64") { let stripped = payload.filter { !$0.isWhitespace } + // base64 decodes to (len/4)*3 minus the trailing '=' padding. Subtract + // the padding so the cap boundary is exact (Swift rejects unpadded + // base64, so this length is never an underestimate). Reject from the + // length BEFORE allocating the decoded buffer. + let padding = stripped.suffix(2).filter { $0 == "=" }.count + let approxDecoded = stripped.utf8.count / 4 * 3 - padding + guard approxDecoded <= maxMediaDecodedBytes else { + throw MediaError.mediaTooLarge( + "payload ~\(approxDecoded) bytes; cap is \(maxMediaDecodedBytes) bytes") + } guard let data = Data(base64Encoded: stripped) else { throw MediaError.base64DecodeFailed } return data } + // Percent-encoded: each %XX (3 bytes) decodes to 1 byte and every other + // byte is itself, so decoded length = len − 2·(number of '%'). Preflight + // from that length BEFORE allocating the decoded String/Data (mirrors the + // base64 path; the post-decode check below stays as a backstop). + let encoded = payload.utf8 + let percentCount = encoded.lazy.filter { $0 == UInt8(ascii: "%") }.count + let approxDecoded = encoded.count - 2 * percentCount + guard approxDecoded <= maxMediaDecodedBytes else { + throw MediaError.mediaTooLarge( + "payload ~\(approxDecoded) bytes; cap is \(maxMediaDecodedBytes) bytes") + } guard let decoded = payload.removingPercentEncoding, let data = decoded.data(using: .utf8) else { throw MediaError.percentDecodeFailed } + guard data.count <= maxMediaDecodedBytes else { + throw MediaError.mediaTooLarge( + "payload \(data.count) bytes; cap is \(maxMediaDecodedBytes) bytes") + } return data } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift index 869dca7717..d97979ff0d 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift @@ -71,7 +71,8 @@ extension ProviderLoop { .base64DecodeFailed, .percentDecodeFailed, .imageDecodeFailed, - .invalidURL: + .invalidURL, + .mediaTooLarge: return 400 case .videoWriteFailed: return 500 diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift index 7c7d4ab7cb..c4903e47de 100644 --- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift +++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift @@ -147,6 +147,20 @@ public struct CORSResponder: HTTPResponder { ), message: error.localizedDescription ) + } catch let error as VLMRequestInference.MediaError { + // Local HTTP (`darkbloom start --local`) must give the same + // status contract as the coordinator WebSocket path: an + // oversized/malformed/non-`data:` inline-media payload is a client + // fault (400), not a provider 500. Without this catch a MediaError + // raised by the VLM media-cap path escapes as the framework's + // generic 500. Mapping reuses mapInferenceErrorToStatus (400 for + // every case except the provider-side videoWriteFailed → 500). + return Self.openAIErrorResponse( + status: HTTPResponse.Status( + code: Int(ProviderLoop.mapInferenceErrorToStatus(error)) + ), + message: error.localizedDescription + ) } } diff --git a/provider-swift/Tests/ProviderCoreTests/MLXMemoryGuardTests.swift b/provider-swift/Tests/ProviderCoreTests/MLXMemoryGuardTests.swift index 919867ad77..a612a3f410 100644 --- a/provider-swift/Tests/ProviderCoreTests/MLXMemoryGuardTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/MLXMemoryGuardTests.swift @@ -45,6 +45,27 @@ private let gib = 1024 * 1024 * 1024 == MLXMemoryGuard.defaultReserveGB * 1_073_741_824) } +@Test func mlxGuardReserveEnvClampsHugeValueInsteadOfTrapping() { + // A huge-but-finite GB override would, naively, do + // `UInt64(min(gb * 1GiB, Double(UInt64.max)))` — but `Double(UInt64.max)` + // rounds up to 2^64, which is outside UInt64, so `UInt64(...)` traps and + // crashes the provider in configureOnce() at startup. The fix saturates. + #expect(MLXMemoryGuard.resolvedReserveBytes( + explicit: nil, env: ["DARKBLOOM_MLX_MEMORY_RESERVE_GB": "1e308"]) == UInt64.max) + // A value whose ×1GiB lands exactly at the 2^64 boundary also saturates, + // not traps. + let boundaryGB = String(MLXMemoryGuard.uint64MaxAsDouble / 1_073_741_824) + #expect(MLXMemoryGuard.resolvedReserveBytes( + explicit: nil, env: ["DARKBLOOM_MLX_MEMORY_RESERVE_GB": boundaryGB]) == UInt64.max) + // A normal large-but-representable value still converts correctly. + #expect(MLXMemoryGuard.resolvedReserveBytes( + explicit: nil, env: ["DARKBLOOM_MLX_MEMORY_RESERVE_GB": "64"]) + == UInt64(64) * 1_073_741_824) + // Zero is honored (operator's accepted DoS knob; must not trap or fall back). + #expect(MLXMemoryGuard.resolvedReserveBytes( + explicit: nil, env: ["DARKBLOOM_MLX_MEMORY_RESERVE_GB": "0"]) == 0) +} + @Test func mlxGuardConfigureOnceAppliesExactlyOnce() { MLXMemoryGuard._resetForTest() var applied: [MLXMemoryGuard.Limits] = [] diff --git a/provider-swift/Tests/ProviderCoreTests/StandaloneServerTests.swift b/provider-swift/Tests/ProviderCoreTests/StandaloneServerTests.swift index c2ac5473c3..ec4fc9e7c6 100644 --- a/provider-swift/Tests/ProviderCoreTests/StandaloneServerTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/StandaloneServerTests.swift @@ -1,5 +1,7 @@ import Hummingbird import HummingbirdTesting +import Logging +import NIOEmbedded import Testing @testable import ProviderCore @@ -212,6 +214,52 @@ import Testing } } +// MARK: - CORSResponder: VLM media-error mapping (local HTTP path) + +/// Inner responder stub that always throws a fixed error, so we can drive +/// `CORSResponder.respond` directly and assert how it renders that error — +/// without standing up the whole engine/model stack. +private struct ThrowingResponder: HTTPResponder { + typealias Context = BasicRequestContext + let error: E + func respond(to request: Request, context: Context) async throws -> Response { + throw error + } +} + +@Test func corsResponderMapsVLMMediaErrorTo400OnLocalPath() async throws { + // Regression: the coordinator WebSocket path maps VLMRequestInference.MediaError + // to a 400 (ProviderLoop.mapInferenceErrorToStatus), but the local HTTP path's + // CORSResponder previously caught only MultiModelBatchSchedulerEngineError / + // MLXOpenAIServiceError, so a MediaError from the VLM media-cap escaped as the + // framework's generic 500. CORSResponder now catches it too. Drive the + // responder directly with a stub that throws the oversize-media error. + let mediaErr = VLMRequestInference.MediaError.mediaTooLarge( + "image is 1600000000 px; per-image cap is 100000000 px") + let responder = CORSResponder(inner: ThrowingResponder(error: mediaErr)) + + let request = Request( + head: .init(method: .post, scheme: "http", authority: "localhost", path: "/v1/chat/completions"), + body: .init(buffer: ByteBuffer())) + let context = BasicRequestContext( + source: ApplicationRequestContextSource( + channel: EmbeddedChannel(), + logger: Logger(label: #function))) + + let response = try await responder.respond(to: request, context: context) + + #expect(response.status == .badRequest, + "oversized inline media on the local path must map to 400, not a generic 500") + #expect(response.headers[.accessControlAllowOrigin] == "*", + "CORS allow-origin must be set on the rendered error response") + // Client-fault video write IO failure stays a 500. + let writeFail = CORSResponder( + inner: ThrowingResponder(error: VLMRequestInference.MediaError.videoWriteFailed("disk full"))) + let writeResp = try await writeFail.respond(to: request, context: context) + #expect(writeResp.status == .internalServerError, + "provider-side videoWriteFailed must stay a 500") +} + private func standaloneTestServer(models: [ModelInfo] = []) -> StandaloneServer { StandaloneServer( models: models diff --git a/provider-swift/Tests/ProviderCoreTests/VLMDecodeBombTests.swift b/provider-swift/Tests/ProviderCoreTests/VLMDecodeBombTests.swift new file mode 100644 index 0000000000..f091f535b3 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/VLMDecodeBombTests.swift @@ -0,0 +1,256 @@ +import Compression +import CoreImage +import Foundation +import ImageIO +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +// Decompression-bomb regression suite for the VLM media-decode path. +// +// This is the automated form of an on-hardware OOM repro (originally a manual +// spike). `CIImage(data:)` eagerly rasterizes a PNG (W·H·4 bytes, no lazy +// decode, no scaled decode), so a tiny highly-compressed "bomb" explodes on +// decode — measured on an M5 Max (128 GB, 0-swap, provider co-resident at +// ~63 GB) BEFORE any KV/token/load admission: +// +// input mode on-wire decoded peak RSS +// 16000² decode-only 757 KiB 256 Mpx 0.96 GB +// 16000² mlxpath (real) 757 KiB 256 Mpx 1.78 GB +// 32000² mlxpath (real) 3.0 MB 1024 Mpx 5.73 GB +// 40000² header (the fix) 4.7 MB 40000×40000 ~0 GB +// +// CIImage(data:) is NOT lazy for PNG (decode RSS scales linearly with pixels), +// and the model's downscale does NOT help — CoreImage decodes the full-res +// source before resampling. Reading dimensions from the format header is the +// only O(header) escape, so the guard rejects from the header BEFORE the raster +// is allocated. +// +// Rather than ship a multi-MB binary fixture or a Python generator, these tests +// synthesize a real, header-readable PNG bomb in-process via streaming zlib: a +// uniform-color WxH image that is a few KB on the wire but declares a huge +// raster. The guard reads the declared dimensions and rejects it as +// `MediaError.mediaTooLarge` at ~0 RSS. A CI-safe bomb that is *rejected from +// the header* is exactly the right shape: it would OOM if the guard regressed, +// and stays flat while the guard holds. + +// MARK: - In-process PNG decompression-bomb generator + +/// Build a uniform mid-gray RGB PNG of `width`x`height` by streaming scanlines +/// through zlib, so the generator itself holds ~one scanline (not the full +/// raster). The output is a real, ImageIO-sizeable PNG: tiny on the wire, but +/// its IHDR declares `width`x`height` and `CIImage(data:)` WOULD allocate +/// width·height·4 bytes if it decoded. +enum PNGBomb { + private static let crcTable: [UInt32] = (0..<256).map { i -> UInt32 in + var c = UInt32(i) + for _ in 0..<8 { c = (c & 1) != 0 ? 0xEDB8_8320 ^ (c >> 1) : c >> 1 } + return c + } + + private static func crc32(_ bytes: [UInt8]) -> UInt32 { + var crc: UInt32 = 0xFFFF_FFFF + for b in bytes { crc = crcTable[Int((crc ^ UInt32(b)) & 0xFF)] ^ (crc >> 8) } + return crc ^ 0xFFFF_FFFF + } + + private static func be32(_ v: UInt32) -> [UInt8] { + [UInt8(v >> 24 & 0xFF), UInt8(v >> 16 & 0xFF), UInt8(v >> 8 & 0xFF), UInt8(v & 0xFF)] + } + + private static func chunk(_ type: String, _ data: [UInt8]) -> [UInt8] { + let t = Array(type.utf8) + return be32(UInt32(data.count)) + t + data + be32(crc32(t + data)) + } + + static func make(width: Int, height: Int) -> Data { + let sig: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] + let ihdr = be32(UInt32(width)) + be32(UInt32(height)) + [8, 2, 0, 0, 0] // 8-bit RGB + + // One raw scanline: filter byte 0 + uniform mid-gray RGB. + var row = [UInt8](repeating: 0x7f, count: 1 + width * 3) + row[0] = 0 + + // Adler-32 over the uncompressed scanlines (zlib trailer). + var a: UInt32 = 1, b: UInt32 = 0 + func adler(_ bytes: [UInt8]) { + for byte in bytes { + a = (a + UInt32(byte)) % 65521 + b = (b + a) % 65521 + } + } + + // Apple's COMPRESSION_ZLIB is raw DEFLATE (no header/trailer); we add the + // zlib wrapper (0x78 0x01 + adler32) manually for a valid PNG IDAT. + var stream = compression_stream( + dst_ptr: UnsafeMutablePointer(bitPattern: 1)!, dst_size: 0, + src_ptr: UnsafeMutablePointer(bitPattern: 1)!, src_size: 0, state: nil) + compression_stream_init(&stream, COMPRESSION_STREAM_ENCODE, COMPRESSION_ZLIB) + defer { compression_stream_destroy(&stream) } + + var deflate: [UInt8] = [0x78, 0x01] + let outCap = 1 << 16 + var outBuf = [UInt8](repeating: 0, count: outCap) + + func drain(finalize: Bool) { + outBuf.withUnsafeMutableBufferPointer { ob in + stream.dst_ptr = ob.baseAddress! + stream.dst_size = outCap + while true { + let flags = finalize ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0 + let status = compression_stream_process(&stream, flags) + let produced = outCap - stream.dst_size + if produced > 0 { deflate.append(contentsOf: ob[0.. String { + "data:image/png;base64,\(make(width: width, height: height).base64EncodedString())" + } +} + +// MARK: - Test helper + +/// Assert `body` threw `MediaError.mediaTooLarge` (file-local copy; the sibling +/// test file's helper is `private`). `MediaError` is not `Equatable`, so we +/// pattern-match the case rather than comparing values. +private func expectMediaTooLarge( + _ body: () async throws -> Void +) async { + do { + try await body() + Issue.record("expected MediaError.mediaTooLarge but no error was thrown") + } catch let error as VLMRequestInference.MediaError { + guard case .mediaTooLarge = error else { + Issue.record("expected .mediaTooLarge, got \(error)") + return + } + } catch { + Issue.record("expected MediaError.mediaTooLarge, got \(error)") + } +} + +// MARK: - Generator self-checks + +@Test("PNGBomb produces a real PNG that is tiny on the wire but declares a huge raster") +func vlmBombGeneratorProducesHeaderReadableTinyPNG() throws { + // 2000x2000 = 4 Mpx: would rasterize to ~16 MB, but compresses to a few KB. + let data = PNGBomb.make(width: 2000, height: 2000) + + // Tiny on the wire (uniform color compresses hard) — well under the 32 MiB + // WS frame cap, like a real malicious payload. + #expect(data.count < 256 * 1024, "bomb should be small on the wire, was \(data.count) bytes") + + // PNG magic. + #expect(Array(data.prefix(8)) == [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) + + // ImageIO reads the declared dimensions from the header WITHOUT decoding the + // raster — this is the exact mechanism the provider's guard relies on. + #expect(VLMRequestInference.imagePixelCount(data) == 4_000_000) +} + +// MARK: - The bomb is rejected before the raster is allocated + +@Test("decodeImage rejects a real PNG decompression bomb from the header") +func vlmDecodeImageRejectsRealBomb() async { + // A header-declared 4 Mpx image against a 1 Mpx cap. If the guard regressed, + // CIImage(data:) would allocate the full raster here; because it rejects from + // the header, RSS stays flat. (On real hardware the same branch rejects a + // 40000² / 1.6 Gpx bomb at ~0 RSS — see the measurement table above.) + let uri = PNGBomb.dataURI(width: 2000, height: 2000) + await expectMediaTooLarge { + _ = try VLMRequestInference.decodeImage(uri, maxImagePixels: 1_000_000) + } +} + +@Test("decodeImage accepts the same bomb when its pixels are within the cap (no regression)") +func vlmDecodeImageAcceptsBombWithinCap() throws { + // The bomb is a genuine PNG; with a cap above its pixel count it decodes + // normally — proving the reject is about size, not a malformed-file false + // positive. 2000x2000 = 4 Mpx, decodes to ~16 MB (CI-affordable). + let uri = PNGBomb.dataURI(width: 2000, height: 2000) + let image = try VLMRequestInference.decodeImage(uri, maxImagePixels: 8_000_000) + guard case .ciImage(let ci) = image else { + Issue.record("expected a decoded .ciImage") + return + } + #expect(ci.extent.width == 2000) + #expect(ci.extent.height == 2000) +} + +@Test("buildUserInput rejects an over-aggregate bomb BEFORE decoding the over-limit image") +func vlmBuildUserInputRejectsAggregateBombBeforeDecode() async { + // Two 2000x2000 (4 Mpx each) bombs with a 5 Mpx aggregate cap. The first is + // within cap and decodes; the second pushes the aggregate to 8 Mpx and MUST + // be rejected from its header BEFORE CIImage(data:) allocates its raster + // (the P2 fix: charge the header pixel count to the aggregate pre-decode). + let uri = PNGBomb.dataURI(width: 2000, height: 2000) + let request = OpenAIChatCompletionRequest( + model: "vlm", + messages: [ + .init(role: .user, content: .parts([.imageURL(uri), .imageURL(uri)])) + ]) + await expectMediaTooLarge { + _ = try await VLMRequestInference.buildUserInput( + from: request, maxImagePixels: 8_000_000, maxRequestImagePixels: 5_000_000) + } +} + +@Test("validateMedia throws MediaError synchronously (before any stream is returned)") +func vlmValidateMediaThrowsUpFront() async { + // The streaming HTTP path (sseResponse) returns a 200 SSE Response and only + // surfaces a generation error mid-iteration — too late for a 4xx. So the + // engine calls validateMedia(request) and propagates its throw BEFORE + // returning the stream. This asserts validateMedia actually throws on an + // oversized payload, so the engine's `try await` surfaces the MediaError to + // the HTTP/WS layer. Uses a small (fast-to-generate) bomb + a low injected + // cap rather than a real >100 Mpx image. + let uri = PNGBomb.dataURI(width: 2000, height: 2000) // 4 Mpx + let request = OpenAIChatCompletionRequest( + model: "vlm", + messages: [.init(role: .user, content: .parts([.imageURL(uri)]))]) + await expectMediaTooLarge { + try await VLMRequestInference.validateMedia(request, maxImagePixels: 1_000_000) + } +} + +@Test("validateMedia passes a within-cap request (no false positive)") +func vlmValidateMediaAcceptsWithinCap() async throws { + // A normal small image must validate cleanly so genuine requests aren't + // rejected before they ever reach generation. + let request = OpenAIChatCompletionRequest( + model: "vlm", + messages: [.init(role: .user, content: .parts([ + .text("describe"), .imageURL(PNGBomb.dataURI(width: 64, height: 64)), + ]))]) + try await VLMRequestInference.validateMedia(request) +} diff --git a/provider-swift/Tests/ProviderCoreTests/VLMRequestInferenceTests.swift b/provider-swift/Tests/ProviderCoreTests/VLMRequestInferenceTests.swift index b154c593c9..671521ae00 100644 --- a/provider-swift/Tests/ProviderCoreTests/VLMRequestInferenceTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/VLMRequestInferenceTests.swift @@ -1,8 +1,10 @@ import CoreImage import Foundation +import ImageIO import MLXLMCommon import MLXLMServer import Testing +import UniformTypeIdentifiers @testable import ProviderCore @@ -22,6 +24,25 @@ private let tinyPNGBase64 = private let tinyPNGDataURI = "data:image/png;base64,\(tinyPNGBase64)" +// A real, round-trip-verified 64x64 H.264 mp4 (3 solid-gray frames, ~955 +// bytes), base64 with no whitespace. naturalSize = 64x64 = 4096 px, so it is +// rejected by a per-frame cap < 4096 and accepted by one >= 4096. Generated via +// AVAssetWriter. Used by the video frame-cap tests. +private let tinyMP4Base64 = + "AAAAHGZ0eXBtcDQyAAAAAWlzb21tcDQxbXA0MgAAAAFtZGF0AAAAAAAAAK4AAAA7BgUyR1ZK3FxMQz+U78URPNFDqAEAAAMAAQMAAAMAAQIAAeYACwAAAwAA" + + "AwAAAwAUDAOJJAEN/////4AAAAAxJbggH4AuSqwRNmYXSACJwyG5akafRwrPDoFqVCtjHBP+QvRWhyAAGk1PzfAEsEedgAAAABEh4QhfAoAvQrFXFN4ACQ7CtgA" + + "AABEBqIGK/1jQw/VufW+ACvdnuAAAAvFtb292AAAAbG12aGQAAAAA5lOws+ZTsLMAAAJYAAACWAABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAA" + + "AAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACfXRyYWsAAABcdGtoZAAAAAHmU7Cz5lOwswAAAAEAAAAAAAACWAAAAAAAAAAA" + + "AAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAQAAAAEAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAlgAAADIAAEAAAAAAfV" + + "tZGlhAAAAIG1kaGQAAAAA5lOws+ZTsLMAAAJYAAACWFXEAAAAAAAxaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAENvcmUgTWVkaWEgVmlkZW8AAAABnG1pbm" + + "YAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAVxzdGJsAAAAoXN0c2QAAAAAAAAAAQAAAJFhdmMxAAAAAA" + + "AAAAEAAAAAAAAAAAAAAAAAAAAAAEAAQABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAAJ2F2Y0MBZAAL/+EADCdkAA" + + "usVlDDeBBhFAEABCjuPLD9+PgAAAAACmZpZWwBAAAAAApjaHJtAAAAAAAYc3R0cwAAAAAAAAABAAAAAwAAAMgAAAAoY3R0cwAAAAAAAAADAAAAAQAAAMgAAAABAA" + + "ABkAAAAAEAAAAAAAAAFHN0c3MAAAAAAAAAAQAAAAEAAAAPc2R0cAAAAAAgEBgAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAMAAAABAAAAIHN0c3oAAAAAAAAAAAAAAA" + + "MAAAB0AAAAFQAAABUAAAAUc3RjbwAAAAAAAAABAAAALA==" + +private let tinyMP4DataURI = "data:video/mp4;base64,\(tinyMP4Base64)" + // MARK: - Test helpers /// Run a throwing media-decode body and assert it threw @@ -132,11 +153,11 @@ func vlmDecodeImageGarbageThrows() { // MARK: - decodeVideo @Test("decodeVideo writes an inline data: URI to a tracked temp file") -func vlmDecodeVideoDataURIWritesTempFile() throws { +func vlmDecodeVideoDataURIWritesTempFile() async throws { var tempFiles: [URL] = [] - let payload = Data("fake mp4 bytes".utf8).base64EncodedString() - let uri = "data:video/mp4;base64,\(payload)" - let video = try VLMRequestInference.decodeVideo(uri, tempFiles: &tempFiles) + // A real, probeable 64x64 video passes the limits and is written + tracked. + let (video, _) = try await VLMRequestInference.decodeVideo( + tinyMP4DataURI, tempFiles: &tempFiles) guard case .url(let url) = video else { Issue.record("expected .url, got \(video)") return @@ -144,17 +165,28 @@ func vlmDecodeVideoDataURIWritesTempFile() throws { #expect(tempFiles == [url]) #expect(FileManager.default.fileExists(atPath: url.path)) #expect(url.pathExtension == "mp4") - let written = try Data(contentsOf: url) - #expect(String(data: written, encoding: .utf8) == "fake mp4 bytes") + #expect((try Data(contentsOf: url)).count > 0) // cleanup (production code removes these when the stream ends) try? FileManager.default.removeItem(at: url) } +@Test("decodeVideo fails closed when video metadata is unprobeable") +func vlmDecodeVideoUnreadableMetadataRejected() async { + // Bytes that aren't a real video: duration/tracks can't be proven within + // cap, so it's rejected — the byte cap doesn't bound decoded frames. + var tempFiles: [URL] = [] + let uri = "data:video/mp4;base64,\(Data("not a real video".utf8).base64EncodedString())" + await expectMediaTooLarge { + _ = try await VLMRequestInference.decodeVideo(uri, tempFiles: &tempFiles) + } + #expect(tempFiles.isEmpty) // rejected -> temp file cleaned up, not tracked +} + @Test("decodeVideo rejects an http:// URI with invalidURL (no SSRF)") -func vlmDecodeVideoHTTPRejected() { +func vlmDecodeVideoHTTPRejected() async { var tempFiles: [URL] = [] - expectInvalidURL("https://example.com/clip.mp4") { - _ = try VLMRequestInference.decodeVideo( + await expectInvalidURLAsync("https://example.com/clip.mp4") { + _ = try await VLMRequestInference.decodeVideo( "https://example.com/clip.mp4", tempFiles: &tempFiles) } // A rejected URI must not have spawned a temp file. @@ -162,10 +194,10 @@ func vlmDecodeVideoHTTPRejected() { } @Test("decodeVideo rejects a file:// URI with invalidURL (no local-file read)") -func vlmDecodeVideoFileRejected() { +func vlmDecodeVideoFileRejected() async { var tempFiles: [URL] = [] - expectInvalidURL("file:///etc/passwd") { - _ = try VLMRequestInference.decodeVideo( + await expectInvalidURLAsync("file:///etc/passwd") { + _ = try await VLMRequestInference.decodeVideo( "file:///etc/passwd", tempFiles: &tempFiles) } #expect(tempFiles.isEmpty) @@ -221,7 +253,7 @@ func vlmHasMediaTextPartsFalse() { // MARK: - buildUserInput @Test("buildUserInput collects text + one image into the user message") -func vlmBuildUserInputTextAndImage() throws { +func vlmBuildUserInputTextAndImage() async throws { let request = OpenAIChatCompletionRequest( model: "vlm", messages: [ @@ -235,7 +267,7 @@ func vlmBuildUserInputTextAndImage() throws { ])), ]) - let userInput = try VLMRequestInference.buildUserInput(from: request) + let userInput = try await VLMRequestInference.buildUserInput(from: request) // UserInput aggregates media across all chat messages. #expect(userInput.images.count == 1) @@ -257,12 +289,12 @@ func vlmBuildUserInputTextAndImage() throws { } @Test("buildUserInput keeps a text-only request media-free") -func vlmBuildUserInputTextOnly() throws { +func vlmBuildUserInputTextOnly() async throws { let request = OpenAIChatCompletionRequest( model: "vlm", messages: [.init(role: .user, content: .text("just text"))]) - let userInput = try VLMRequestInference.buildUserInput(from: request) + let userInput = try await VLMRequestInference.buildUserInput(from: request) #expect(userInput.images.isEmpty) #expect(userInput.videos.isEmpty) guard case .chat(let messages) = userInput.prompt else { @@ -292,6 +324,7 @@ func vlmMediaErrorMapsTo400() { .base64DecodeFailed, .percentDecodeFailed, .imageDecodeFailed, + .mediaTooLarge("image is 1600000000 px; per-image cap is 100000000 px"), ] for err in clientFaults { #expect( @@ -321,3 +354,309 @@ func vlmMediaErrorLocalizedDescription() { #expect(err.localizedDescription == "media must be sent as an inline base64 data: URI (e.g. \"data:image/jpeg;base64,…\") on this end-to-end-encrypted endpoint; remote http(s):// and file:// URLs are rejected. Got: file:///etc/passwd") #expect(!err.localizedDescription.contains("couldn’t be completed")) } + +// MARK: - Decompression-bomb / media-size caps + +/// Assert `body` threw `MediaError.mediaTooLarge` (async: `decodeVideo` / +/// `buildUserInput` are async; sync bodies satisfy the closure type too). +private func expectMediaTooLarge(_ body: () async throws -> Void) async { + do { + try await body() + Issue.record("expected MediaError.mediaTooLarge but no error was thrown") + } catch let error as VLMRequestInference.MediaError { + guard case .mediaTooLarge = error else { + Issue.record("expected .mediaTooLarge, got \(error)") + return + } + } catch { + Issue.record("expected MediaError.mediaTooLarge, got \(error)") + } +} + +/// Async variant of `expectInvalidURL` for the now-async `decodeVideo`. +private func expectInvalidURLAsync( + _ expectedURI: String, _ body: () async throws -> Void +) async { + do { + try await body() + Issue.record("expected MediaError.invalidURL(\(expectedURI)) but nothing was thrown") + } catch let error as VLMRequestInference.MediaError { + guard case .invalidURL(let uri) = error else { + Issue.record("expected .invalidURL, got \(error)") + return + } + #expect(uri == expectedURI) + } catch { + Issue.record("expected MediaError.invalidURL, got \(error)") + } +} + +@Test("decodeImage rejects an image whose pixel count exceeds the per-image cap") +func vlmDecodeImageRejectsOverPixelCap() async { + // The 1x1 tiny PNG is 1 px; a 0-px cap makes any real image over-cap, so we + // hit the header-read reject path without allocating a multi-GB raster. On + // hardware a real 40000x40000 bomb (256 Mpx–1.6 Gpx) takes this same branch + // — measured peak 1.78 GB at 16000^2 on the real path before this fix. + await expectMediaTooLarge { + _ = try VLMRequestInference.decodeImage(tinyPNGDataURI, maxImagePixels: 0) + } +} + +@Test("decodeImage accepts an image within the per-image cap (no regression)") +func vlmDecodeImageWithinPixelCapPasses() throws { + let image = try VLMRequestInference.decodeImage(tinyPNGDataURI, maxImagePixels: 100) + guard case .ciImage = image else { + Issue.record("expected a decoded .ciImage") + return + } +} + +@Test("imagePixelCount reads dimensions from the header (no raster decode)") +func vlmImagePixelCountReadsHeader() throws { + let data = try VLMRequestInference.dataFromDataURI(tinyPNGDataURI) + #expect(VLMRequestInference.imagePixelCount(data) == 1) // 1x1 + // Non-image bytes can't be sized -> nil (decodeImage then fails closed). + #expect(VLMRequestInference.imagePixelCount(Data("not an image".utf8)) == nil) +} + +@Test("dataFromDataURI rejects a payload over the decoded-byte cap") +func vlmDataFromDataURIRejectsOverByteCap() async { + // 0-byte cap: any non-empty payload is over-cap, rejected from the base64 + // length before the decoded buffer is ever allocated. + await expectMediaTooLarge { + _ = try VLMRequestInference.dataFromDataURI(tinyPNGDataURI, maxMediaDecodedBytes: 0) + } +} + +@Test("buildUserInput rejects images whose aggregate pixels exceed the request cap") +func vlmBuildUserInputRejectsAggregatePixels() async { + // Two 1x1 images = 2 px total; a 1-px aggregate cap trips on the second, + // bounding the "pack many max-size images into one frame" amplification. + let request = OpenAIChatCompletionRequest( + model: "vlm", + messages: [ + .init( + role: .user, + content: .parts([ + .imageURL(tinyPNGDataURI), + .imageURL(tinyPNGDataURI), + ])) + ]) + await expectMediaTooLarge { + _ = try await VLMRequestInference.buildUserInput(from: request, maxRequestImagePixels: 1) + } +} + +@Test("buildUserInput accepts images within the aggregate cap (no regression)") +func vlmBuildUserInputWithinAggregatePasses() async throws { + let request = OpenAIChatCompletionRequest( + model: "vlm", + messages: [ + .init( + role: .user, + content: .parts([.imageURL(tinyPNGDataURI), .imageURL(tinyPNGDataURI)])) + ]) + _ = try await VLMRequestInference.buildUserInput(from: request, maxRequestImagePixels: 10) +} + +@Test("resolveMaxPixels honors a valid env override and falls back otherwise") +func vlmResolveMaxPixels() { + let key = "DARKBLOOM_MAX_IMAGE_MEGAPIXELS" + #expect( + VLMRequestInference.resolveMaxPixels( + env: key, defaultMegapixels: 100, environment: [key: "8"]) == 8_000_000) + #expect( + VLMRequestInference.resolveMaxPixels( + env: key, defaultMegapixels: 100, environment: [:]) == 100_000_000) + #expect( + VLMRequestInference.resolveMaxPixels( + env: key, defaultMegapixels: 100, environment: [key: "-1"]) == 100_000_000) + #expect( + VLMRequestInference.resolveMaxPixels( + env: key, defaultMegapixels: 100, environment: [key: "abc"]) == 100_000_000) +} + +@Test("resolveMaxPixels clamps a huge env value to Int.max instead of trapping") +func vlmResolveMaxPixelsClampsHuge() { + // A very large finite megapixel value would, naively, do + // `Int(min(mp*1e6, Double(Int.max)))` — but `Double(Int.max)` rounds up to + // 2^63 (> Int.max), so `Int(...)` traps at the boundary, crashing the + // provider at static init. The fix saturates to Int.max. + let key = "DARKBLOOM_MAX_IMAGE_MEGAPIXELS" + #expect( + VLMRequestInference.resolveMaxPixels( + env: key, defaultMegapixels: 100, environment: [key: "1e308"]) == Int.max) + // A value whose ×1e6 lands exactly at the 2^63 boundary also saturates, + // not traps. + let boundaryMP = String(VLMRequestInference.intMaxAsDouble / 1_000_000) + #expect( + VLMRequestInference.resolveMaxPixels( + env: key, defaultMegapixels: 100, environment: [key: boundaryMP]) == Int.max) + // A normal large-but-representable value still scales correctly. + #expect( + VLMRequestInference.resolveMaxPixels( + env: key, defaultMegapixels: 100, environment: [key: "1000"]) == 1_000_000_000) +} + +@Test("resolveMaxBytes honors a valid env override and falls back otherwise") +func vlmResolveMaxBytes() { + let key = "DARKBLOOM_MAX_MEDIA_MIB" + #expect( + VLMRequestInference.resolveMaxBytes( + env: key, defaultMiB: 25, environment: [key: "4"]) == 4 * 1024 * 1024) + #expect( + VLMRequestInference.resolveMaxBytes( + env: key, defaultMiB: 25, environment: [:]) == 25 * 1024 * 1024) + #expect( + VLMRequestInference.resolveMaxBytes( + env: key, defaultMiB: 25, environment: [key: "0"]) == 25 * 1024 * 1024) +} + +@Test("resolveMaxBytes clamps an overflowing MiB env value to Int.max instead of trapping") +func vlmResolveMaxBytesClampsOverflow() { + // A MiB value that parses as Int but whose `* 1024 * 1024` overflows would + // trap during static init. The fix saturates to Int.max. + let key = "DARKBLOOM_MAX_MEDIA_MIB" + let hugeMiB = String(Int.max) + #expect( + VLMRequestInference.resolveMaxBytes( + env: key, defaultMiB: 25, environment: [key: hugeMiB]) == Int.max) + // Just past the overflow threshold (Int.max / 1 MiB + 1) also saturates. + let overThreshold = String((Int.max / (1024 * 1024)) + 1) + #expect( + VLMRequestInference.resolveMaxBytes( + env: key, defaultMiB: 25, environment: [key: overThreshold]) == Int.max) +} + +@Test("secondsString renders extreme/non-finite durations without trapping on Int(_:)") +func vlmSecondsStringNeverTraps() { + // Whole numbers print cleanly (the common "600s" case). + #expect(VLMRequestInference.secondsString(600) == "600") + #expect(VLMRequestInference.secondsString(0) == "0") + // Fractional values keep one decimal. + #expect(VLMRequestInference.secondsString(12.5) == "12.5") + // A duration far beyond Int.max seconds (untrusted video metadata) must NOT + // trap — it would if formatted via `Int(duration.seconds)`. Just assert it + // produces some non-empty string without crashing. + #expect(!VLMRequestInference.secondsString(1e300).isEmpty) + #expect(!VLMRequestInference.secondsString(Double.infinity).isEmpty) + #expect(!VLMRequestInference.secondsString(Double.nan).isEmpty) +} + +@Test("media-limit defaults are the documented values") +func vlmMediaLimitDefaults() { + #expect(VLMRequestInference.maxImagePixels == 100_000_000) + #expect(VLMRequestInference.maxRequestImagePixels == 384_000_000) + #expect(VLMRequestInference.maxMediaDecodedBytes == 25 * 1024 * 1024) + #expect(VLMRequestInference.maxVideoDurationSeconds == 600) + #expect(VLMRequestInference.maxVideosPerRequest == 8) + #expect(VLMRequestInference.maxRequestVideoFramePixels == 384_000_000) +} + +/// Build a real PNG of the given dimensions (uniform gray) via ImageIO — to +/// exercise the header pixel-read on a genuine multi-pixel image (not the 1x1). +private func makePNGDataURI(width: Int, height: Int) -> String { + let ctx = CGContext( + data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + ctx.setFillColor(CGColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1)) + ctx.fill(CGRect(x: 0, y: 0, width: width, height: height)) + let out = NSMutableData() + let dest = CGImageDestinationCreateWithData( + out, UTType.png.identifier as CFString, 1, nil)! + CGImageDestinationAddImage(dest, ctx.makeImage()!, nil) + _ = CGImageDestinationFinalize(dest) + return "data:image/png;base64,\((out as Data).base64EncodedString())" +} + +@Test("dataFromDataURI rejects an over-cap percent-encoded payload") +func vlmDataFromDataURIRejectsOverByteCapPercentEncoded() async { + // The non-base64 (percent-encoded) branch enforces the cap after decode. + let uri = "data:text/plain," + String(repeating: "x", count: 64) + await expectMediaTooLarge { + _ = try VLMRequestInference.dataFromDataURI(uri, maxMediaDecodedBytes: 8) + } +} + +@Test("decodeVideo applies the byte cap before writing a temp file") +func vlmDecodeVideoRejectsOverByteCap() async { + var tempFiles: [URL] = [] + await expectMediaTooLarge { + _ = try await VLMRequestInference.decodeVideo( + tinyMP4DataURI, tempFiles: &tempFiles, maxMediaDecodedBytes: 0) + } + #expect(tempFiles.isEmpty) // rejected before any temp file is written +} + +@Test("decodeVideo rejects a video whose frame exceeds the per-frame pixel cap") +func vlmDecodeVideoRejectsOverFrameCap() async { + // The 64x64 fixture = 4096 px; a 1000-px per-frame cap rejects it, probed + // from track metadata (naturalSize) without decoding frames. + var tempFiles: [URL] = [] + await expectMediaTooLarge { + _ = try await VLMRequestInference.decodeVideo( + tinyMP4DataURI, tempFiles: &tempFiles, maxFramePixels: 1000) + } + #expect(tempFiles.isEmpty) // rejected -> temp file cleaned up, not tracked +} + +@Test("decodeVideo accepts a video within the per-frame cap (no regression)") +func vlmDecodeVideoWithinFrameCapPasses() async throws { + var tempFiles: [URL] = [] + let (video, _) = try await VLMRequestInference.decodeVideo( + tinyMP4DataURI, tempFiles: &tempFiles, maxFramePixels: 10_000) + guard case .url(let url) = video else { + Issue.record("expected .url, got \(video)") + return + } + #expect(tempFiles == [url]) + try? FileManager.default.removeItem(at: url) +} + +@Test("imagePixelCount + decodeImage reject a real multi-pixel image over the cap") +func vlmDecodeImageRealMultiPixelRejected() async throws { + let uri = makePNGDataURI(width: 200, height: 150) // 30000 px, ~120 KB raster + let data = try VLMRequestInference.dataFromDataURI(uri) + #expect(VLMRequestInference.imagePixelCount(data) == 30_000) + await expectMediaTooLarge { + _ = try VLMRequestInference.decodeImage(uri, maxImagePixels: 1_000) + } +} + +@Test("buildUserInput rejects more videos than the per-request count cap") +func vlmBuildUserInputRejectsVideoCount() async { + // Three tiny valid videos with a 2-video cap -> rejected on the third, + // bounding the "many tiny MP4s" aggregate-frame amplification. + var tempFiles: [URL] = [] + let request = OpenAIChatCompletionRequest( + model: "vlm", + messages: [ + .init( + role: .user, + content: .parts([ + .videoURL(tinyMP4DataURI), + .videoURL(tinyMP4DataURI), + .videoURL(tinyMP4DataURI), + ])) + ]) + await expectMediaTooLarge { + _ = try await VLMRequestInference.buildUserInput( + from: request, tempFiles: &tempFiles, maxVideosPerRequest: 2) + } + for u in tempFiles { try? FileManager.default.removeItem(at: u) } +} + +@Test("buildUserInput rejects videos whose aggregate frame pixels exceed the cap") +func vlmBuildUserInputRejectsVideoFramePixels() async { + // One 64x64 video = 4096 frame px; a 1-px aggregate cap trips it. + var tempFiles: [URL] = [] + let request = OpenAIChatCompletionRequest( + model: "vlm", + messages: [.init(role: .user, content: .parts([.videoURL(tinyMP4DataURI)]))]) + await expectMediaTooLarge { + _ = try await VLMRequestInference.buildUserInput( + from: request, tempFiles: &tempFiles, maxRequestVideoFramePixels: 1) + } + for u in tempFiles { try? FileManager.default.removeItem(at: u) } +}