Repository Public License
1import Compression2import CryptoKit3import Foundation4import NavigatorCore5import Persistence6import Testing7@testable import SyncEngine89@Suite struct CapsuleRoundTripTests {10 @Test func exportThenImportIntoAnEmptyDatabaseReproducesTheSelection() async throws {11 let world = try await World.populated()12 var selection = world.everything13 selection.includeHistory = true14 let (data, report) = try await world.exporter.export(selection, createdAt: day(5))15 #expect(report.omissions.isEmpty && !report.isEncrypted && report.byteCount == data.count)16 #expect(report.manifest.includesHistory && report.manifest.appVersion == "1.0 (test)" && report.manifest.formatVersion == 1)17 #expect(Set(report.manifest.items.map(\.kind)) == [.bookmarks, .notes, .canvases, .workflows, .spaces, .history, .archives, .archiveFile, .canvasAttachment])18 #expect(report.manifest.items.map(\.name) == report.manifest.items.map(\.name).sorted())19 #expect(!CapsuleReader.isEncrypted(data))2021 let contents = try CapsuleReader.open(data)22 #expect(contents.manifest == report.manifest && !contents.wasEncrypted)23 #expect(contents.count(of: .bookmarks) == 5 && contents.count(of: .notes) == 1 && contents.count(of: .history) == 2)24 #expect(contents.count(of: .archiveFile) == 1 && contents.count(of: .canvasAttachment) == 1)2526 let (target, profile) = try await World.empty(name: "Other device")27 let root = temporaryDirectory()28 let options = CapsuleImportOptions(profileID: profile.id, policy: .skip, importHistory: true, archiveDirectory: root.appending(path: "archives"),29 canvasAttachmentDirectory: root.appending(path: "attachments"))30 let importer = CapsuleImporter(database: target)31 // The preview is computed before anything is written.32 let preview = try await importer.preview(contents, options: options)33 #expect(preview.kinds[.bookmarks] == CapsuleKindSummary(total: 5, new: 5, identical: 0, conflicting: 0))34 #expect(preview.kinds[.history]?.new == 2 && preview.kinds[.spaces]?.new == 1 && preview.kinds[.archives]?.new == 1)35 #expect(!preview.hasConflicts && preview.fileCount == 2 && preview.notes.isEmpty && preview.totalBytes > 0)36 #expect(try await target.bookmarks.all(profile: profile.id).isEmpty)37 #expect(try await target.notes.notes().isEmpty)38 #expect(!FileManager.default.fileExists(atPath: root.appending(path: "archives").path))3940 let result = try await importer.apply(contents, options: options)41 #expect(result.kinds[.bookmarks]?.imported == 5 && result.kinds[.notes]?.imported == 1 && result.kinds[.canvases]?.imported == 1)42 #expect(result.kinds[.workflows]?.imported == 1 && result.kinds[.spaces]?.imported == 1 && result.kinds[.archives]?.imported == 1)43 #expect(result.kinds[.history]?.imported == 2 && result.filesWritten == 2 && result.totalWritten == 12)4445 // Bookmarks: same tree, same content, now owned by the destination profile.46 let original = try await world.database.bookmarks.all(profile: world.profile.id)47 let imported = try await target.bookmarks.all(profile: profile.id)48 #expect(imported.map { var b = $0; b.profileID = world.profile.id; return b }.sorted { $0.id < $1.id } == original.sorted { $0.id < $1.id })49 #expect(try await target.bookmarks.bookmark(world.nested.id)?.parentID == world.nested.parentID)50 #expect(try await target.notes.note(world.note.id) == world.note)51 #expect(try await target.canvases.document(world.canvas.id) == world.canvas)52 #expect(try await target.workflows.workflow(world.workflow.id) == world.workflow)53 // The space arrives with its tab list: address, title, pinned — and nothing else.54 let space = try #require(try await target.spaces.space(world.space.id))55 #expect(space.name == "Research" && space.tint == .ocean && space.profileID == profile.id)56 let tabs = try await target.tabs.tabs(space: space.id)57 #expect(tabs.map(\.url?.absoluteString) == ["https://example.org/one", "https://example.org/two"] && tabs.map(\.isPinned) == [true, false])58 #expect(tabs.allSatisfy { $0.sessionState == nil && $0.lifecycle == .dormant })59 // Files land inside the given directories, under names the importer chose.60 let archive = try #require(try await target.archives.archive(world.archive.id))61 #expect(archive.relativePath == "capsule/\(world.archive.id.string)/page_one.html" && archive.contentHash == world.archive.contentHash)62 #expect(try Data(contentsOf: root.appending(path: "archives").appending(path: archive.relativePath)) == Data("<html><body>archived page</body></html>".utf8))63 #expect(FileManager.default.fileExists(atPath: root.appending(path: "attachments/\(world.canvas.id.string)/\(World.attachmentName)").path))64 #expect(try await target.history.visitCount(profile: profile.id) == 2)6566 // Importing the same capsule again changes nothing.67 let again = try await importer.preview(contents, options: options)68 #expect(again.kinds[.bookmarks] == CapsuleKindSummary(total: 5, new: 0, identical: 5, conflicting: 0))69 #expect(again.kinds.values.allSatisfy { $0.new == 0 && $0.conflicting == 0 })70 let second = try await importer.apply(contents, options: options)71 #expect(second.totalWritten == 0 && second.filesWritten == 0 && second.kinds[.history]?.identical == 2)72 #expect(try await target.history.visitCount(profile: profile.id) == 2)73 #expect(try await target.spaces.spaces(profile: profile.id).count == 1)74 await world.database.close(); await target.close()75 }7677 @Test func clearCapsulesAreDeterministicAndFilesRoundTripThroughDisk() async throws {78 let world = try await World.populated()79 let first = try await world.exporter.export(world.everything, createdAt: day(5)).data80 let second = try await world.exporter.export(world.everything, createdAt: day(5)).data81 #expect(first == second)82 #expect(try await world.exporter.export(world.everything, createdAt: day(6)).data != first)83 let file = temporaryDirectory().appending(path: "backup.orixcapsule")84 let report = try await world.exporter.export(world.everything, to: file, createdAt: day(5))85 #expect(try Data(contentsOf: file) == first && report.byteCount == first.count)86 // Compressible content is stored smaller than it is.87 let total = report.manifest.items.reduce(0) { $0 + $1.byteSize }88 #expect(first.count < total + 1_500)89 await world.database.close()90 }9192 @Test func selectionsExportOnlyWhatWasTicked() async throws {93 let world = try await World.populated()94 var selection = CapsuleSelection(profileID: world.profile.id)95 await #expect(throws: CapsuleError.emptySelection) { try await world.exporter.export(selection) }96 // A folder brings its subtree; nothing else comes along.97 selection.bookmarks = .only([world.folder.id])98 let folderOnly = try CapsuleReader.open(try await world.exporter.export(selection).data)99 #expect(Set(folderOnly.bookmarks.map(\.title)) == ["Reading", "Swift", "Deep", "Nested"])100 #expect(folderOnly.manifest.items.map(\.kind) == [.bookmarks] && !folderOnly.includesHistory)101 selection.bookmarks = .only([world.nested.id])102 selection.notes = .only([NoteID()])103 selection.workflows = .all104 let mixed = try CapsuleReader.open(try await world.exporter.export(selection).data)105 #expect(mixed.bookmarks.map(\.title) == ["Nested"] && mixed.notes.isEmpty && mixed.workflows.count == 1)106 // A child whose folder is not in the capsule lands at the top level on import.107 let (target, profile) = try await World.empty()108 _ = try await CapsuleImporter(database: target).apply(mixed, options: CapsuleImportOptions(profileID: profile.id, policy: .skip))109 #expect(try await target.bookmarks.bookmark(world.nested.id)?.parentID == nil)110 // Without an archive directory the exporter says what it left out.111 var archives = CapsuleSelection(profileID: world.profile.id)112 archives.archives = .all113 let bare = try await CapsuleExporter(database: world.database, appVersion: "1").export(archives)114 #expect(bare.report.omissions.count == 1 && bare.report.manifest.items.map(\.kind) == [.archives])115 let opened = try CapsuleReader.open(bare.data)116 let preview = try await CapsuleImporter(database: target).preview(opened, options: CapsuleImportOptions(profileID: profile.id, policy: .skip, archiveDirectory: temporaryDirectory()))117 #expect(preview.notes.contains { $0.contains("has no file") })118 await world.database.close(); await target.close()119 }120121 @Test func historyTravelsOnlyWhenAskedOnBothSides() async throws {122 let world = try await World.populated()123 let without = try await world.exporter.export(world.everything).data124 #expect(try CapsuleReader.open(without).includesHistory == false)125 var selection = world.everything126 selection.includeHistory = true127 let with = try CapsuleReader.open(try await world.exporter.export(selection).data)128 #expect(with.includesHistory && with.manifest.includesHistory)129 let (target, profile) = try await World.empty()130 let importer = CapsuleImporter(database: target)131 // The capsule has history, the importing user did not tick it: it stays out, and the preview says so.132 let cautious = CapsuleImportOptions(profileID: profile.id, policy: .skip)133 #expect(try await importer.preview(with, options: cautious).notes.contains { $0.contains("browsing history") })134 let report = try await importer.apply(with, options: cautious)135 #expect(report.kinds[.history] == nil && report.notes.contains { $0.contains("browsing history") })136 #expect(try await target.history.visitCount(profile: profile.id) == 0)137 await world.database.close(); await target.close()138 }139}140141@Suite struct CapsuleConflictTests {142 /// A second device that already has the same items, some of them edited.143 func diverged() async throws -> (World, CapsuleContents, NavigatorDatabase, Profile) {144 let world = try await World.populated()145 let contents = try CapsuleReader.open(try await world.exporter.export(world.everything).data)146 let (target, profile) = try await World.empty()147 _ = try await CapsuleImporter(database: target).apply(contents, options: CapsuleImportOptions(profileID: profile.id, policy: .skip))148 var link = try #require(try await target.bookmarks.bookmark(world.link.id))149 link.title = "Swift (edited here)"150 try await target.bookmarks.save(link)151 var note = world.note152 note.spaceID = try await target.spaces.space(world.space.id)?.id153 note.body = "Edited on this device."154 try await target.notes.save(note)155 var workflow = world.workflow156 workflow.source += "# local change\n"157 try await target.workflows.save(workflow)158 var canvas = world.canvas159 canvas.title = "Board (local)"160 try await target.canvases.save(canvas)161 return (world, contents, target, profile)162 }163164 @Test func previewCountsConflictsAndSkipKeepsLocalVersions() async throws {165 let (world, contents, target, profile) = try await diverged()166 let importer = CapsuleImporter(database: target)167 let options = CapsuleImportOptions(profileID: profile.id, policy: .skip)168 let preview = try await importer.preview(contents, options: options)169 #expect(preview.hasConflicts)170 #expect(preview.kinds[.bookmarks] == CapsuleKindSummary(total: 5, new: 0, identical: 4, conflicting: 1))171 #expect(preview.kinds[.notes]?.conflicting == 1 && preview.kinds[.workflows]?.conflicting == 1 && preview.kinds[.canvases]?.conflicting == 1)172 let report = try await importer.apply(contents, options: options)173 #expect(report.totalWritten == 0 && report.kinds[.bookmarks]?.skipped == 1 && report.kinds[.notes]?.skipped == 1)174 #expect(try await target.bookmarks.bookmark(world.link.id)?.title == "Swift (edited here)")175 #expect(try await target.notes.note(world.note.id)?.body == "Edited on this device.")176 #expect(try await target.bookmarks.all(profile: profile.id).count == 5)177 await world.database.close(); await target.close()178 }179180 @Test func keepBothAddsCopiesAndNeverOverwrites() async throws {181 let (world, contents, target, profile) = try await diverged()182 let report = try await CapsuleImporter(database: target).apply(contents, options: CapsuleImportOptions(profileID: profile.id, policy: .keepBoth))183 #expect(report.kinds[.bookmarks]?.duplicated == 1 && report.kinds[.notes]?.duplicated == 1 && report.kinds[.workflows]?.duplicated == 1)184 #expect(report.kinds[.canvases]?.duplicated == 1 && report.kinds[.bookmarks]?.identical == 4)185 let bookmarks = try await target.bookmarks.all(profile: profile.id)186 #expect(bookmarks.count == 6)187 #expect(Set(bookmarks.filter { $0.url?.host == "www.swift.org" }.map(\.title)) == ["Swift", "Swift (edited here)"])188 // The copy sits in the same folder as the original.189 #expect(bookmarks.filter { $0.url?.host == "www.swift.org" }.allSatisfy { $0.parentID == world.folder.id })190 #expect(try await target.notes.note(world.note.id)?.body == "Edited on this device.")191 #expect(Set(try await target.notes.notes().map(\.body)) == ["Edited on this device.", "Remember this."])192 #expect(try await target.workflows.all().count == 2)193 #expect(try await target.canvases.documents().count == 2)194 await world.database.close(); await target.close()195 }196197 @Test func replaceOverwritesOnlyWhenAsked() async throws {198 let (world, contents, target, profile) = try await diverged()199 let report = try await CapsuleImporter(database: target).apply(contents, options: CapsuleImportOptions(profileID: profile.id, policy: .replace))200 #expect(report.kinds[.bookmarks]?.replaced == 1 && report.kinds[.notes]?.replaced == 1 && report.kinds[.workflows]?.replaced == 1)201 #expect(try await target.bookmarks.bookmark(world.link.id)?.title == "Swift")202 #expect(try await target.notes.note(world.note.id)?.body == "Remember this.")203 #expect(try await target.workflows.workflow(world.workflow.id)?.source == world.workflow.source)204 #expect(try await target.canvases.document(world.canvas.id)?.title == "Board")205 #expect(try await target.bookmarks.all(profile: profile.id).count == 5)206 await world.database.close(); await target.close()207 }208209 @Test func anExistingSpaceIsNeverReplaced() async throws {210 let (world, contents, target, profile) = try await diverged()211 // The destination opened another tab in that space since.212 let window = try #require(try await target.windows.openWindows(space: world.space.id).first)213 try await target.tabs.save(Tab(windowID: window.id, spaceID: world.space.id, url: URL(string: "https://example.org/three"), title: "Three", order: 2))214 let importer = CapsuleImporter(database: target)215 let options = CapsuleImportOptions(profileID: profile.id, policy: .replace)216 #expect(try await importer.preview(contents, options: options).notes.contains { $0.contains("never replaced") })217 let report = try await importer.apply(contents, options: options)218 #expect(report.kinds[.spaces]?.duplicated == 1)219 let spaces = try await target.spaces.spaces(profile: profile.id)220 #expect(Set(spaces.map(\.name)) == ["Research", "Research (imported)"])221 #expect(try await target.tabs.tabs(space: world.space.id).count == 3)222 // A stored profile is required: an unknown or ghost profile cannot receive a capsule.223 await #expect(throws: PersistenceError.self) {224 try await importer.apply(contents, options: CapsuleImportOptions(profileID: ProfileID(), policy: .skip))225 }226 await world.database.close(); await target.close()227 }228}229230@Suite struct CapsuleSecurityTests {231 @Test func nothingSecretOrUnselectedIsInTheBytes() async throws {232 let world = try await World.populated()233 let database = world.database234 // Things a capsule must never carry, each with a recognisable marker.235 try await database.settings.set(SettingKey<String>("provider.endpoint", default: ""), to: "MARKER-SETTING-VALUE")236 try await database.settings.set(SettingKey<String>("MARKER-SETTING-KEY", default: ""), to: "x")237 try await database.permissions.set(PermissionDecision(profileID: world.profile.id, origin: WebOrigin(scheme: "https", host: "marker-permission.example"),238 kind: PermissionKind.allCases[0], verdict: .allow))239 try await database.downloads.save(Download(profileID: world.profile.id, sourceURL: URL(string: "https://downloads.example/MARKER-DOWNLOAD.zip")!, filename: "MARKER-DOWNLOAD.zip"))240 try await database.agentRuns.save(AgentRun(spaceID: world.space.id, goal: "MARKER-AGENT-GOAL", providerID: "p", model: "m"))241 try await database.sync.recordChange(entity: .note, entityID: "MARKER-SYNC-RECORD", deviceID: "MARKER-DEVICE-ID")242 try await database.snapshots.save(PageSnapshot(profileID: world.profile.id, url: URL(string: "https://example.org/s")!, title: "s", text: "MARKER-SNAPSHOT-TEXT"))243 let markers = ["MARKER-SETTING-VALUE", "MARKER-SETTING-KEY", "marker-permission.example", "MARKER-DOWNLOAD", "MARKER-AGENT-GOAL", "MARKER-SYNC-RECORD",244 "MARKER-DEVICE-ID", "MARKER-SNAPSHOT-TEXT", "MARKER-SESSION-STATE", "MARKER-HISTORY", "provider.endpoint", world.profile.name]245 func leaks(_ data: Data) throws -> [String] {246 // Look in the file as written and in every entry once decompressed.247 var haystacks = [data]248 haystacks += try CapsuleContainer.read(data, password: nil, limits: CapsuleLimits()).map(\.data)249 return markers.filter { marker in haystacks.contains { $0.range(of: Data(marker.utf8)) != nil } }250 }251 let everything = try await world.exporter.export(world.everything).data252 #expect(try leaks(everything) == [])253 // The check can see a marker when one is there: history, once explicitly included.254 var withHistory = world.everything255 withHistory.includeHistory = true256 #expect(try leaks(try await world.exporter.export(withHistory).data) == ["MARKER-HISTORY"])257 // Cookies and website storage are not in the database at all; the capsule has no entry kind for them.258 #expect(Set(CapsuleItemKind.allCases.map(\.rawValue)) == ["bookmarks", "notes", "canvases", "workflows", "spaces", "history", "archives", "archiveFile", "canvasAttachment"])259 await database.close()260 }261262 @Test func aPasswordProtectedCapsuleNeedsItsPassword() async throws {263 let world = try await World.populated()264 let clear = try await world.exporter.export(world.everything, createdAt: day(5)).data265 let (sealed, report) = try await world.exporter.export(world.everything, password: "correct horse battery staple", createdAt: day(5))266 #expect(report.isEncrypted && CapsuleReader.isEncrypted(sealed))267 // Random salt and nonce: two exports differ, and nothing readable is left in the file.268 #expect(try await world.exporter.export(world.everything, password: "correct horse battery staple", createdAt: day(5)).data != sealed)269 for needle in ["manifest.json", "bookmarks", "Swift", "example.org", "Remember this"] { #expect(sealed.range(of: Data(needle.utf8)) == nil, "\(needle)") }270 let header = String(decoding: sealed[16..<(16 + Int(sealed[15]) + Int(sealed[14]) * 256)], as: UTF8.self)271 #expect(header.contains("\"kdf\":\"PBKDF2-HMAC-SHA256\"") && header.contains("\"iterations\":600000") && header.contains("\"cipher\":\"AES-256-GCM\""))272273 let opened = try CapsuleReader.open(sealed, password: "correct horse battery staple")274 let reference = try CapsuleReader.open(clear)275 #expect(opened.wasEncrypted)276 #expect(opened.bookmarks == reference.bookmarks)277 #expect(throws: CapsuleError.passwordRequired) { try CapsuleReader.open(sealed) }278 #expect(throws: CapsuleError.wrongPasswordOrCorrupted) { try CapsuleReader.open(sealed, password: "correct horse battery stapl") }279 #expect(throws: CapsuleError.wrongPasswordOrCorrupted) { try CapsuleReader.open(sealed, password: "") }280 #expect(throws: CapsuleError.wrongPasswordOrCorrupted) { try CapsuleReader.open(sealed, password: "Correct horse battery staple") }281 // A clear capsule ignores a password that was not needed.282 #expect(try CapsuleReader.open(clear, password: "anything").bookmarks.count == 5)283 // The same password typed in another Unicode form (é as one or two code points) opens the capsule.284 let accented = try await world.exporter.export(world.everything, password: "caf\u{E9} noir").data285 #expect(try CapsuleReader.open(accented, password: "cafe\u{301} noir").notes.count == 1)286 await world.database.close()287 }288289 @Test func anyFlippedByteOfAClearCapsuleIsDetected() async throws {290 let (database, profile) = try await World.empty()291 try await database.bookmarks.save(Bookmark(profileID: profile.id, title: "One", url: URL(string: "https://example.org/1"), createdAt: day(), updatedAt: day()))292 try await database.workflows.save(Workflow(name: "w", source: String(repeating: "notify \"hello\"\n", count: 20), createdAt: day(), updatedAt: day()))293 var selection = CapsuleSelection(profileID: profile.id)294 selection.bookmarks = .all; selection.workflows = .all295 let data = try await CapsuleExporter(database: database, appVersion: "1").export(selection, createdAt: day()).data296 #expect(try CapsuleReader.open(data).bookmarks.count == 1)297 var accepted = 0298 for index in data.indices {299 for bit in [UInt8(0x01), 0x80] {300 var copy = data301 copy[index] ^= bit302 if (try? CapsuleReader.open(copy)) != nil { accepted += 1 }303 }304 }305 #expect(accepted == 0)306 // Truncation at any length and appended bytes are refused too.307 for length in 0..<data.count { #expect((try? CapsuleReader.open(data.prefix(length))) == nil, "prefix \(length)") }308 #expect((try? CapsuleReader.open(data + Data([0]))) == nil)309 #expect((try? CapsuleReader.open(data + data)) == nil)310 await database.close()311 }312313 @Test func tamperingWithAnEncryptedCapsuleIsDetected() async throws {314 let (database, profile) = try await World.empty()315 try await database.bookmarks.save(Bookmark(profileID: profile.id, title: "One", url: URL(string: "https://example.org/1")))316 var selection = CapsuleSelection(profileID: profile.id)317 selection.bookmarks = .all318 let data = try await CapsuleExporter(database: database, appVersion: "1").export(selection, password: "pw").data319 #expect(try CapsuleReader.open(data, password: "pw").bookmarks.count == 1)320 // Every byte of the prefix and header (authenticated as associated data), then a spread of the ciphertext321 // and every byte of the tag. Each attempt costs a full key derivation, hence the sampling of the body.322 let headerEnd = 16 + Int(data[15]) + Int(data[14]) * 256323 var positions = Array(0..<headerEnd) + Array(stride(from: headerEnd, to: data.count - 16, by: 23)) + Array((data.count - 16)..<data.count)324 positions.append(headerEnd + 11) // inside the nonce325 var accepted = 0326 for index in positions {327 var copy = data328 copy[index] ^= 0x04329 if (try? CapsuleReader.open(copy, password: "pw")) != nil { accepted += 1 }330 }331 #expect(accepted == 0, "\(positions.count) positions tried")332 // Dropping the encryption flag does not turn the ciphertext into a readable capsule.333 var unflagged = data334 unflagged[11] = 0335 #expect((try? CapsuleReader.open(unflagged, password: "pw")) == nil)336 await database.close()337 }338339 @Test func weakOrAbsurdEncryptionParametersAreRefused() throws {340 func sealed(_ header: String) -> Data { RawCapsule.build([], flags: 1, header: Data(header.utf8)) }341 let salt = Data(repeating: 7, count: 16).base64EncodedString()342 func parameters(iterations: Int, kdf: String = "PBKDF2-HMAC-SHA256", cipher: String = "AES-256-GCM", salt: String = salt, keyLength: Int = 32) -> String {343 "{\"cipher\":\"\(cipher)\",\"iterations\":\(iterations),\"kdf\":\"\(kdf)\",\"keyLength\":\(keyLength),\"salt\":\"\(salt)\"}"344 }345 #expect(throws: CapsuleError.weakParameters("1 iterations")) { try CapsuleReader.open(sealed(parameters(iterations: 1)), password: "p") }346 #expect(throws: CapsuleError.weakParameters("99999 iterations")) { try CapsuleReader.open(sealed(parameters(iterations: 99_999)), password: "p") }347 // A header asking for billions of iterations must not stall the app.348 let clock = ContinuousClock()349 let elapsed = clock.measure {350 #expect(throws: CapsuleError.weakParameters("2000000000 iterations")) { try CapsuleReader.open(sealed(parameters(iterations: 2_000_000_000)), password: "p") }351 }352 #expect(elapsed < .seconds(1))353 #expect(throws: CapsuleError.weakParameters("unsupported cipher or key derivation")) { try CapsuleReader.open(sealed(parameters(iterations: 600_000, kdf: "MD5")), password: "p") }354 #expect(throws: CapsuleError.weakParameters("unsupported cipher or key derivation")) { try CapsuleReader.open(sealed(parameters(iterations: 600_000, cipher: "NONE")), password: "p") }355 #expect(throws: CapsuleError.weakParameters("unsupported cipher or key derivation")) { try CapsuleReader.open(sealed(parameters(iterations: 600_000, keyLength: 8)), password: "p") }356 #expect(throws: CapsuleError.weakParameters("salt")) { try CapsuleReader.open(sealed(parameters(iterations: 600_000, salt: "AAAA")), password: "p") }357 #expect(throws: CapsuleError.malformed("encryption header")) { try CapsuleReader.open(sealed("{}"), password: "p") }358 }359360 @Test func oversizedClaimsAreRefusedBeforeAnyAllocation() throws {361 let manifest = RawCapsule.Entry("manifest.json", Data("{}".utf8))362 let clock = ContinuousClock()363 // An entry that claims a petabyte, backed by a few bytes.364 let claims: [(RawCapsule.Entry, String)] = [365 (RawCapsule.Entry("data/notes.json", Data("x".utf8), compression: 1, originalLength: 1 << 50), "claims a petabyte, compressed"),366 (RawCapsule.Entry("data/notes.json", Data("x".utf8), compression: 0, originalLength: 1 << 50), "claims a petabyte, stored"),367 (RawCapsule.Entry("data/notes.json", Data("x".utf8), compression: 1, originalLength: UInt64.max), "claims 2^64-1 bytes"),368 ]369 for (entry, label) in claims {370 let elapsed = clock.measure { #expect((try? CapsuleReader.open(RawCapsule.build([manifest, entry]))) == nil, "\(label)") }371 #expect(elapsed < .seconds(1), "\(label)")372 }373 #expect(throws: CapsuleError.limitExceeded("entry data/notes.json declares 1125899906842624 bytes")) { try CapsuleReader.open(RawCapsule.build([manifest, claims[0].0])) }374 // A stored length larger than the file.375 var lying = Data(RawCapsule.build([manifest]).dropLast(32 + 6))376 lying += RawCapsule.big(UInt16(15)) + Data("data/notes.json".utf8) + Data([0]) + RawCapsule.big(UInt64(1 << 40)) + RawCapsule.big(UInt64(1_000))377 lying += Data(SHA256.hash(data: lying))378 #expect(throws: CapsuleError.malformed("entry data/notes.json is truncated")) { try CapsuleReader.open(lying) }379380 // A real decompression bomb: 64 MiB of zeros deflate to a few dozen kilobytes.381 let zeros = Data(count: 64 * 1024 * 1024)382 var deflated = Data(count: 1024 * 1024)383 let written = deflated.withUnsafeMutableBytes { destination in384 zeros.withUnsafeBytes { source in385 compression_encode_buffer(destination.bindMemory(to: UInt8.self).baseAddress!, 1024 * 1024, source.bindMemory(to: UInt8.self).baseAddress!, zeros.count, nil, COMPRESSION_ZLIB)386 }387 }388 deflated.count = written389 #expect(written > 0 && written < 200_000)390 var limits = CapsuleLimits()391 limits.maximumEntryBytes = 8 * 1024 * 1024392 // Honest about its size: over the per-entry limit.393 #expect(throws: CapsuleError.self) {394 try CapsuleReader.open(RawCapsule.build([manifest, RawCapsule.Entry("data/notes.json", deflated, compression: 1, originalLength: UInt64(zeros.count))]), limits: limits)395 }396 // Lying about its size (claims 1 KiB, inflates to 64 MiB): only claim + 1 bytes are ever produced.397 #expect(throws: CapsuleError.malformed("entry data/notes.json does not inflate to its declared size")) {398 try CapsuleReader.open(RawCapsule.build([manifest, RawCapsule.Entry("data/notes.json", deflated, compression: 1, originalLength: 1_024)]), limits: limits)399 }400 // Many entries that are each fine but together exceed the total.401 limits.maximumTotalBytes = 10 * 1024 * 1024402 let small = Data(count: 4 * 1024 * 1024)403 let many = (0..<4).map { RawCapsule.Entry("data/part\($0).json", small) }404 #expect(throws: CapsuleError.limitExceeded("total uncompressed size")) { try CapsuleReader.open(RawCapsule.build([manifest] + many), limits: limits) }405 limits.maximumEntries = 3406 #expect(throws: CapsuleError.limitExceeded("number of entries")) { try CapsuleReader.open(RawCapsule.build([manifest] + many), limits: limits) }407 limits.maximumFileBytes = 1_000408 #expect(throws: CapsuleError.limitExceeded("file size")) { try CapsuleReader.open(RawCapsule.build([manifest] + many), limits: limits) }409 }410411 @Test func entryNamesCannotEscape() throws {412 let hostile = ["../evil", "../../etc/passwd", "/etc/passwd", "data/../../evil", "data/./x", "data//x", "a/b/../c", ".hidden", "data/.hidden", "..", ".",413 "data\\evil", "C:\\evil", "data/evil\u{0}.json", "data/é.json", "data/a b.json", "~/evil", "data/%2e%2e/evil", "-rf", "data/-x",414 "a/b/c/d/e/f/g", String(repeating: "a", count: 300), "data/evil\n.json", "data/evil:stream", "data/*.json", "files/archives/../../x"]415 for name in hostile {416 let file = RawCapsule.build([RawCapsule.Entry("manifest.json", Data("{}".utf8)), RawCapsule.Entry(name, Data("x".utf8))])417 #expect((try? CapsuleReader.open(file)) == nil, "\(name.debugDescription)")418 #expect(!CapsuleContainer.isSafeName(name, limits: CapsuleLimits()), "\(name.debugDescription)")419 }420 #expect(throws: CapsuleError.unsafeName("../evil")) { try CapsuleReader.open(RawCapsule.build([RawCapsule.Entry("manifest.json", Data("{}".utf8)), RawCapsule.Entry("../evil", Data("x".utf8))])) }421 for name in ["manifest.json", "data/bookmarks.json", "files/archives/8D3A1D5E-0000-4000-8000-000000000000/page_one.html"] {422 #expect(CapsuleContainer.isSafeName(name, limits: CapsuleLimits()))423 }424 #expect(CapsuleContainer.sanitisedFileName("../../etc/pass wd") == "pass_wd")425 #expect(CapsuleContainer.sanitisedFileName("..") == "file" && CapsuleContainer.sanitisedFileName("-x.html") == "x.html" && CapsuleContainer.sanitisedFileName("é/ü.html") == "_.html")426 // Paths resolved for reading or writing never leave their directory.427 let root = temporaryDirectory()428 for path in ["../x", "a/../../x", "/etc/passwd", "a//b", "", "a/./b", "a\\..\\b", "a\u{0}b"] { #expect(CapsuleExporter.contained(path, in: root) == nil, "\(path.debugDescription)") }429 #expect(CapsuleExporter.contained("a/b.html", in: root) != nil)430 }431432 @Test func capsulesWhoseContentDoesNotMatchTheirManifestAreRejectedWhole() async throws {433 let id = UUID().uuidString, other = UUID().uuidString434 let profile = UUID().uuidString435 func bookmark(_ url: String, id: String = UUID().uuidString) -> String {436 "{\"createdAt\":1800000000,\"id\":\"\(id)\",\"isFavorite\":false,\"kind\":\"link\",\"order\":0,\"profileID\":\"\(profile)\",\"tags\":[],\"title\":\"t\",\"updatedAt\":1800000000,\"url\":\"\(url)\"}"437 }438 let good = Data("[\(bookmark("https://example.org/"))]".utf8)439 #expect(try CapsuleReader.open(RawCapsule.consistent([("data/bookmarks.json", "bookmarks", 1, good)])).bookmarks.count == 1)440 func rejected(_ file: Data, _ label: String, sourceLocation: SourceLocation = #_sourceLocation) {441 #expect((try? CapsuleReader.open(file)) == nil, "\(label)", sourceLocation: sourceLocation)442 }443 rejected(Data(), "empty file")444 rejected(Data("PK\u{3}\u{4} this is a zip".utf8), "foreign file")445 #expect(throws: CapsuleError.notACapsule) { try CapsuleReader.open(Data("not a capsule at all, just some text".utf8)) }446 #expect(throws: CapsuleError.unsupportedVersion(2)) { try CapsuleReader.open(RawCapsule.build([], version: 2)) }447 #expect(throws: CapsuleError.unsupportedVersion(7)) { try CapsuleReader.open(RawCapsule.consistent([("data/bookmarks.json", "bookmarks", 1, good)], formatVersion: 7)) }448 #expect(throws: CapsuleError.notACapsule) { try CapsuleReader.open(RawCapsule.consistent([("data/bookmarks.json", "bookmarks", 1, good)], format: "other.format")) }449 rejected(RawCapsule.build([], flags: 0x8000), "unknown flag")450 rejected(RawCapsule.build([]), "no manifest")451 rejected(RawCapsule.build([RawCapsule.Entry("data/bookmarks.json", good)]), "manifest not first")452 rejected(RawCapsule.build([RawCapsule.Entry("manifest.json", Data("{}".utf8)), RawCapsule.Entry("manifest.json", Data("{}".utf8))]), "duplicate entry")453 rejected(RawCapsule.build([RawCapsule.Entry("manifest.json", Data("{}".utf8))], declaredCount: 5), "wrong entry count")454 rejected(RawCapsule.build([RawCapsule.Entry("manifest.json", Data("{}".utf8))], trailing: Data("extra".utf8)), "trailing bytes")455 rejected(RawCapsule.build([RawCapsule.Entry("manifest.json", Data("{}".utf8), compression: 9)]), "unknown compression")456 rejected(RawCapsule.build([RawCapsule.Entry("manifest.json", Data("{}".utf8))], header: Data("{\"x\":1}".utf8)), "unexpected header")457 // The manifest lists something that is not there, or misses something that is.458 let manifestOnly = "{\"appVersion\":\"t\",\"createdAt\":1800000000,\"format\":\"orix.capsule\",\"formatVersion\":1,\"includesHistory\":false,\"items\":[{\"byteSize\":3,\"count\":1,\"kind\":\"notes\",\"name\":\"data/notes.json\",\"sha256\":\"00\"}]}"459 rejected(RawCapsule.build([RawCapsule.Entry("manifest.json", Data(manifestOnly.utf8))]), "listed but absent")460 let emptyManifest = "{\"appVersion\":\"t\",\"createdAt\":1800000000,\"format\":\"orix.capsule\",\"formatVersion\":1,\"includesHistory\":false,\"items\":[]}"461 rejected(RawCapsule.build([RawCapsule.Entry("manifest.json", Data(emptyManifest.utf8)), RawCapsule.Entry("data/bookmarks.json", good)]), "present but unlisted")462 // A payload swapped after the manifest was written (the digest is recomputed by the attacker).463 let swapped = "{\"appVersion\":\"t\",\"createdAt\":1800000000,\"format\":\"orix.capsule\",\"formatVersion\":1,\"includesHistory\":false,\"items\":[{\"byteSize\":\(good.count),\"count\":1,\"kind\":\"bookmarks\",\"name\":\"data/bookmarks.json\",\"sha256\":\"\(RawCapsule.sha(good))\"}]}"464 var altered = good465 altered[altered.count - 20] ^= 1466 #expect(throws: CapsuleError.hashMismatch("data/bookmarks.json")) {467 try CapsuleReader.open(RawCapsule.build([RawCapsule.Entry("manifest.json", Data(swapped.utf8)), RawCapsule.Entry("data/bookmarks.json", altered)]))468 }469 rejected(RawCapsule.consistent([("data/bookmarks.json", "bookmarks", 2, good)]), "record count differs from the manifest")470 rejected(RawCapsule.consistent([("data/other.json", "bookmarks", 1, good)]), "kind under the wrong name")471 rejected(RawCapsule.consistent([("data/bookmarks.json", "bookmarks", 1, Data("{\"not\":\"an array\"}".utf8))]), "payload of the wrong shape")472 rejected(RawCapsule.consistent([("data/bookmarks.json", "bookmarks", 2, Data("[\(bookmark("https://a.example/", id: id)),\(bookmark("https://b.example/", id: id))]".utf8))]), "duplicate identifiers")473 rejected(RawCapsule.consistent([("data/history.json", "history", 1, Data("[{\"title\":\"t\",\"transition\":\"link\",\"url\":\"https://example.org/\",\"visitedAt\":1800000000}]".utf8))]), "history not declared")474 // Content that must not be imported.475 for scheme in ["javascript:alert(1)", "data:text/html,<script>1</script>", "vbscript:x", "orix://settings", "about:blank", "blob:https://example.org/1"] {476 #expect(throws: CapsuleError.self) { try CapsuleReader.open(RawCapsule.consistent([("data/bookmarks.json", "bookmarks", 1, Data("[\(bookmark(scheme))]".utf8))])) }477 }478 // Files must belong to an item of the capsule and sit where their kind says.479 rejected(RawCapsule.consistent([("files/archives/\(other)/page.html", "archiveFile", 1, Data("x".utf8))]), "file without its archive")480 rejected(RawCapsule.consistent([("files/archives/not-a-uuid/page.html", "archiveFile", 1, Data("x".utf8))]), "file under a non-identifier")481 rejected(RawCapsule.consistent([("data/page.html", "archiveFile", 1, Data("x".utf8))]), "file outside files/")482 rejected(RawCapsule.consistent([("files/canvas/\(other)/evil.sh", "canvasAttachment", 1, Data("x".utf8))]), "attachment with a free name")483 let canvas = "[{\"cards\":[{\"content\":{\"image\":{\"relativePath\":\"../../Library/x.png\"}},\"id\":\"\(id)\",\"origin\":{\"x\":0,\"y\":0},\"size\":{\"height\":10,\"width\":10},\"zIndex\":0}],\"connections\":[],\"createdAt\":1800000000,\"id\":\"\(other)\",\"title\":\"c\",\"updatedAt\":1800000000,\"viewport\":{\"center\":{\"x\":0,\"y\":0},\"scale\":1}}]"484 #expect(throws: CapsuleError.unsafeName("../../Library/x.png")) { try CapsuleReader.open(RawCapsule.consistent([("data/canvases.json", "canvases", 1, Data(canvas.utf8))])) }485 // An archive whose metadata points at a path of its own choosing.486 let archive = "[{\"byteSize\":1,\"capturedAt\":1800000000,\"contentHash\":\"h\",\"format\":\"html\",\"id\":\"\(other)\",\"isComplete\":true,\"missing\":[],\"profileID\":\"\(profile)\",\"relativePath\":\"../../../Library/Preferences/evil.plist\",\"title\":\"a\",\"url\":\"https://example.org/\"}]"487 #expect(throws: CapsuleError.unsafeName("../../../Library/Preferences/evil.plist")) { try CapsuleReader.open(RawCapsule.consistent([("data/archives.json", "archives", 1, Data(archive.utf8))])) }488 // Nothing above ever reached a database: `open` has no database to write to.489 }490}491