Files prepared on the device: sizes checked first, HEIC to JPEG, from what
Task 16 of the native slice 2 part 1 plan (spec 7.6, P10, S10). - AttachmentFile.convertedFrom says what an image became a JPEG from (HEIC, TIFF, PNG…), for the chip's "from HEIC"; nil when a JPEG is only made smaller. - AttachmentFile.prepare(url:) checks the file's size before reading anything: over 128 MiB, or not named as an image and over 10 MiB, is refused from its size alone. An image is decoded from the file by ImageIO; anything else is read bounded at 10 MiB. - The draft prepares a file source from its URL, off the main actor, behind Task 14's gate (it read up to 128 MiB into memory first). Tests (AttachmentFileTests, fixtures drawn with CGImageDestination): HEIC and TIFF become JPEG and say so (ImageIO can't write a bare HEIF here; it takes the same branch); over 2560 px is scaled, keeping its aspect; converted output has no location; a PNG or JPEG at 2000 px goes up byte for byte, GPS and all (Equipo strips it on arrival); a 7952 x 5304 JPEG comes out under 10 MiB and 40 MP; an unreadable 10 MiB + 1 non-image and a 128 MiB + 1 image are refused from their sizes; an unknown type gets the web's types line. Gate: swift test -j 4 --filter 'AttachmentFileTests|Attachment|MacAttachment': 21 XCTests and 20 Swift Testing tests passed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Task 16: files prepared on the device
3 files changed,
+177
−4
native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift+7 −3native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift+33 −1native/apple/Tests/BaseKitTests/AttachmentFileTests.swift+137 −0
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift| index c4da224..b4a7ace 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentDraft.swift |
| @@ -144,10 +144,14 @@ import Observation |
| let token = background.begin { [weak self] in self?.expire(id, item.generation) } |
| defer { background.end(token) } |
| do { |
| + // Off the main actor, behind the gate; a file from its URL, its |
| + // size checked before anything is read (Task 16). |
| let file = try await Task.detached { |
| - let bytes: Data |
| - switch item.source { case .data(let data): bytes = data; case .file(let url): bytes = try AttachmentFile.read(url); case .load(let load): bytes = try await load() } |
| - return try AttachmentFile.prepare(bytes, name: item.name) |
| + switch item.source { |
| + case .data(let data): return try AttachmentFile.prepare(data, name: item.name) |
| + case .file(let url): return try AttachmentFile.prepare(url: url, name: item.name) |
| + case .load(let load): return try AttachmentFile.prepare(try await load(), name: item.name) |
| + } |
| }.value |
| try Task.checkCancellation() |
| guard let i = index(id, item.generation) else { return } |
diff --git a/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift b/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift| index bc6ab29..63165e7 100644 |
| --- a/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift |
| +++ b/native/apple/Sources/BaseKit/Attachments/AttachmentFile.swift |
| @@ -44,6 +44,10 @@ public struct AttachmentFile: Sendable { |
| public let mediaType: String |
| public let width: Int |
| public let height: Int |
| + /// Base (Task 16): what an image was converted to JPEG from ("HEIC", |
| + /// "TIFF", "PNG"), for the chip's "from HEIC"; nil when its type is |
| + /// kept (a JPEG made smaller is still a JPEG). |
| + public var convertedFrom: String? = nil |
| public static func prepare(_ data: Data, name: String) throws -> Self { |
| try prepare(data, name: name, maximumBytes: AttachmentLimits.maxBytes) |
| @@ -96,7 +100,8 @@ public struct AttachmentFile: Sendable { |
| CGImageDestinationAddImage(destination, flattened, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary) |
| guard CGImageDestinationFinalize(destination) else { throw AttachmentFailure.type } |
| guard output.length <= maximumBytes else { throw AttachmentFailure.tooLarge } |
| - return Self(data: output as Data, name: (name as NSString).deletingPathExtension + ".jpg", mediaType: "image/jpeg", width: image.width, height: image.height) |
| + return Self(data: output as Data, name: (name as NSString).deletingPathExtension + ".jpg", mediaType: "image/jpeg", width: image.width, height: image.height, |
| + convertedFrom: type == .jpeg ? nil : type.preferredFilenameExtension.map { $0 == "tif" ? "TIFF" : $0.uppercased() }) |
| } |
| try AttachmentLimits.checkDimensions(width: width, height: height) |
| let data = try original() |
| @@ -116,6 +121,33 @@ public struct AttachmentFile: Sendable { |
| guard try access.isRegularFile(url) else { throw AttachmentFailure.type } |
| } |
| + /// Base (Task 16, P10): a file prepared from its URL, its size checked |
| + /// before anything is read. A file over 128 MiB, or one that isn't named |
| + /// as an image and is over 10 MiB, is refused from its size alone. An |
| + /// image is decoded from the file by ImageIO, never read whole first. |
| + public static func prepare(url: URL, name: String? = nil, access: any AttachmentFileAccess = SystemAttachmentFileAccess()) throws -> Self { |
| + guard url.isFileURL else { throw AttachmentFailure.type } |
| + let started = access.start(url) |
| + defer { if started { access.stop(url) } } |
| + guard try access.isRegularFile(url) else { throw AttachmentFailure.type } |
| + let filename = URL(fileURLWithPath: name ?? url.lastPathComponent).lastPathComponent |
| + let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 |
| + let namedImage = UTType(filenameExtension: (filename as NSString).pathExtension)?.conforms(to: .image) ?? false |
| + guard size <= AttachmentLimits.maxInputBytes, namedImage || size <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| + func bounded() throws -> Data { |
| + let handle = try FileHandle(forReadingFrom: url) |
| + defer { try? handle.close() } |
| + let data = try handle.read(upToCount: AttachmentLimits.maxBytes + 1) ?? Data() |
| + guard data.count <= AttachmentLimits.maxBytes else { throw AttachmentFailure.tooLarge } |
| + return data |
| + } |
| + if let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), |
| + let image = try prepareImage(source, name: filename, maximumBytes: AttachmentLimits.maxBytes, original: bounded) { |
| + return image |
| + } |
| + return try prepare(bounded(), name: filename) |
| + } |
| + |
| public static func read(_ url: URL) throws -> Data { |
| let access = url.startAccessingSecurityScopedResource() |
| defer { if access { url.stopAccessingSecurityScopedResource() } } |
diff --git a/native/apple/Tests/BaseKitTests/AttachmentFileTests.swift b/native/apple/Tests/BaseKitTests/AttachmentFileTests.swift| new file mode 100644 |
| index 0000000..2a8a60f |
| --- /dev/null |
| +++ b/native/apple/Tests/BaseKitTests/AttachmentFileTests.swift |
| @@ -0,0 +1,137 @@ |
| +@testable import BaseKit |
| +import Foundation |
| +import ImageIO |
| +import UniformTypeIdentifiers |
| +import XCTest |
| + |
| +/// Task 16: files prepared on the device (spec 7.6, P10, S10). Every |
| +/// fixture is drawn here; nothing large is committed. |
| +final class AttachmentFileTests: XCTestCase { |
| + var scratch: URL! |
| + override func setUpWithError() throws { |
| + scratch = FileManager.default.temporaryDirectory.appendingPathComponent("AttachmentFileTests-" + UUID().uuidString) |
| + try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true) |
| + } |
| + override func tearDownWithError() throws { |
| + // Unreadable fixtures first get their permissions back. |
| + for case let url as URL in FileManager.default.enumerator(at: scratch, includingPropertiesForKeys: nil) ?? .init() { |
| + try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) |
| + } |
| + try? FileManager.default.removeItem(at: scratch) |
| + } |
| + |
| + /// An image of `type`, `width` × `height`, with GPS when asked. |
| + func image(_ type: UTType, width: Int, height: Int, gps: Bool = false, quality: Double = 0.9) throws -> Data { |
| + let context = try XCTUnwrap(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, |
| + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)) |
| + // Something to compress: bands and a gradient. |
| + for band in 0..<8 { |
| + context.setFillColor(CGColor(red: Double(band) / 8, green: 0.5, blue: 1 - Double(band) / 8, alpha: 1)) |
| + context.fill(CGRect(x: 0, y: band * height / 8, width: width, height: height / 8 + 1)) |
| + } |
| + let data = NSMutableData() |
| + let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil)) |
| + var properties: [CFString: Any] = [kCGImageDestinationLossyCompressionQuality: quality] |
| + if gps { |
| + properties[kCGImagePropertyGPSDictionary] = [kCGImagePropertyGPSLatitude: 53.34, kCGImagePropertyGPSLatitudeRef: "N", |
| + kCGImagePropertyGPSLongitude: 6.26, kCGImagePropertyGPSLongitudeRef: "W"] |
| + } |
| + CGImageDestinationAddImage(destination, try XCTUnwrap(context.makeImage()), properties as CFDictionary) |
| + XCTAssertTrue(CGImageDestinationFinalize(destination)) |
| + return data as Data |
| + } |
| + |
| + func properties(_ data: Data) throws -> [CFString: Any] { |
| + let source = try XCTUnwrap(CGImageSourceCreateWithData(data as CFData, nil)) |
| + return try XCTUnwrap(CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]) |
| + } |
| + |
| + func write(_ data: Data, _ name: String) throws -> URL { |
| + let url = scratch.appendingPathComponent(name) |
| + try data.write(to: url) |
| + return url |
| + } |
| + |
| + /// A sparse file of `bytes`, which no one may read. |
| + func unreadable(_ name: String, bytes: Int) throws -> URL { |
| + let url = scratch.appendingPathComponent(name) |
| + FileManager.default.createFile(atPath: url.path, contents: nil) |
| + let handle = try FileHandle(forWritingTo: url) |
| + try handle.truncate(atOffset: UInt64(bytes)); try handle.close() |
| + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: url.path) |
| + return url |
| + } |
| + |
| + func testHEICHEIFAndTIFFBecomeJPEGAndSaySo() throws { |
| + // ImageIO can't write a bare public.heif here to make a fixture; |
| + // AttachmentFile converts .heif by the same branch as .heic. |
| + for (type, from) in [(UTType.heic, "HEIC"), (.tiff, "TIFF")] { |
| + let file = try AttachmentFile.prepare(image(type, width: 400, height: 300), name: "IMG_4021.\(type.preferredFilenameExtension ?? "x")") |
| + XCTAssertEqual(file.mediaType, "image/jpeg", from) |
| + XCTAssertEqual(file.name, "IMG_4021.jpg", from) |
| + XCTAssertEqual(file.convertedFrom, from) |
| + XCTAssertEqual(file.width, 400) |
| + } |
| + } |
| + |
| + func testOver2560IsScaledKeepingItsAspect() throws { |
| + let file = try AttachmentFile.prepare(image(.png, width: 4000, height: 1000), name: "wide.png") |
| + XCTAssertEqual(file.width, 2560) |
| + XCTAssertEqual(file.height, 640) |
| + XCTAssertEqual(file.mediaType, "image/jpeg") |
| + XCTAssertEqual(file.convertedFrom, "PNG") |
| + let scaled = try AttachmentFile.prepare(image(.jpeg, width: 3000, height: 3000), name: "square.jpg") |
| + XCTAssertEqual(scaled.width, 2560) |
| + XCTAssertNil(scaled.convertedFrom, "a JPEG made smaller is still a JPEG") |
| + } |
| + |
| + func testConvertedOutputHasNoLocation() throws { |
| + for (type, name) in [(UTType.tiff, "scan.tiff"), (.png, "big.png")] { |
| + let width = type == .png ? 3000 : 600 |
| + let file = try AttachmentFile.prepare(image(type, width: width, height: 400, gps: true), name: name) |
| + XCTAssertNil(try properties(file.data)[kCGImagePropertyGPSDictionary], name) |
| + } |
| + } |
| + |
| + /// At or under 2560 px a PNG or JPEG goes up as it is: Equipo strips its |
| + /// location on arrival (attachments spec §1). |
| + func testASmallPNGOrJPEGGoesUpByteForByte() throws { |
| + for (type, name) in [(UTType.png, "map.png"), (.jpeg, "map.jpg")] { |
| + let original = try image(type, width: 2000, height: 1500, gps: true) |
| + let file = try AttachmentFile.prepare(original, name: name) |
| + XCTAssertEqual(file.data, original, name) |
| + XCTAssertNil(file.convertedFrom) |
| + } |
| + } |
| + |
| + func testA48MegapixelPhotoComesOutUnderTheLimits() throws { |
| + let photo = try image(.jpeg, width: 7952, height: 5304, quality: 1) |
| + let file = try AttachmentFile.prepare(url: try write(photo, "IMG_0001.JPG")) |
| + XCTAssertLessThan(file.data.count, AttachmentLimits.maxBytes) |
| + XCTAssertLessThanOrEqual(file.width * file.height, AttachmentLimits.maxPixels) |
| + XCTAssertEqual(file.width, 2560) |
| + } |
| + |
| + func testAFileIsPreparedFromItsURL() throws { |
| + let file = try AttachmentFile.prepare(url: try write(image(.heic, width: 300, height: 200), "photo.heic")) |
| + XCTAssertEqual(file.convertedFrom, "HEIC") |
| + let text = try AttachmentFile.prepare(url: try write(Data("a,b\n1,2\n".utf8), "Orders.csv")) |
| + XCTAssertEqual(text.mediaType, "text/csv") |
| + } |
| + |
| + func testANonImageOver10MiBIsRefusedFromItsSizeWithoutBeingRead() throws { |
| + let url = try unreadable("Ledger.csv", bytes: AttachmentLimits.maxBytes + 1) |
| + XCTAssertThrowsError(try AttachmentFile.prepare(url: url)) { XCTAssertEqual($0 as? AttachmentFailure, .tooLarge) } |
| + } |
| + |
| + func testAnImageOver128MiBIsRefused() throws { |
| + let url = try unreadable("huge.png", bytes: AttachmentLimits.maxInputBytes + 1) |
| + XCTAssertThrowsError(try AttachmentFile.prepare(url: url)) { XCTAssertEqual($0 as? AttachmentFailure, .tooLarge) } |
| + } |
| + |
| + func testAnUnknownTypeGetsTheWebsTypesLine() throws { |
| + XCTAssertThrowsError(try AttachmentFile.prepare(url: try write(Data([0, 1, 2, 3, 0xff]), "tool.exe"))) { |
| + XCTAssertEqual(($0 as? AttachmentFailure)?.words, "Attach images (PNG, JPEG, WebP or GIF) or text, Markdown, CSV, JSON or PDF files.") |
| + } |
| + } |
| +} |