SPB Git

Repository Public License

CanvasStorageTests.swift 15.7 KB 254 lines swift

1import Foundation2import NavigatorCore3import Persistence4import Testing5@testable import CanvasEngine67@Suite struct CanvasAttachmentTests {8    @Test func sniffingUsesMagicBytesOnly() {9        #expect(CanvasAttachmentKind.sniff(pngData()) == .png)10        #expect(CanvasAttachmentKind.sniff(Data([0xFF, 0xD8, 0xFF, 0xE0, 0, 0])) == .jpeg)11        #expect(CanvasAttachmentKind.sniff(Data("GIF89a....".utf8)) == .gif)12        #expect(CanvasAttachmentKind.sniff(Data("RIFF\u{1}\u{2}\u{3}\u{4}WEBPVP8 ".utf8)) == .webp)13        #expect(CanvasAttachmentKind.sniff(Data([0, 0, 0, 0x18]) + Data("ftypheic".utf8)) == .heic)14        #expect(CanvasAttachmentKind.sniff(Data([0x49, 0x49, 0x2A, 0x00, 8])) == .tiff)15        #expect(CanvasAttachmentKind.sniff(pdfData()) == .pdf)16        #expect(CanvasAttachmentKind.sniff(Data("<svg xmlns='http://www.w3.org/2000/svg'><script/></svg>".utf8)) == nil)17        #expect(CanvasAttachmentKind.sniff(Data("<html>".utf8)) == nil)18        #expect(CanvasAttachmentKind.sniff(Data("RIFF\u{1}\u{2}\u{3}\u{4}WAVEfmt ".utf8)) == nil)19        #expect(CanvasAttachmentKind.sniff(Data([0, 0, 0, 0x18]) + Data("ftypisom".utf8)) == nil)20        #expect(CanvasAttachmentKind.sniff(Data([0x4D, 0x5A, 0x90])) == nil)21        #expect(CanvasAttachmentKind.sniff(Data()) == nil)22        #expect(CanvasAttachmentKind.sniff(Data([0x89])) == nil)23    }2425    @Test func importStoresUnderTheContentHashAndIsIdempotent() async throws {26        let root = temporaryDirectory()27        defer { try? FileManager.default.removeItem(at: root) }28        let store = CanvasAttachmentStore(root: root)29        let canvas = CanvasID()30        let first = try await store.importData(pngData("one"), into: canvas)31        let again = try await store.importData(pngData("one"), into: canvas)32        let pdf = try await store.importData(pdfData(), into: canvas)33        #expect(first == again)34        #expect(first.relativePath == first.sha256 + ".png" && first.sha256.count == 64)35        #expect(pdf.kind == .pdf && pdf.relativePath.hasSuffix(".pdf"))36        #expect(try await store.storedFiles(of: canvas).count == 2)37        #expect(try await store.data(for: first.relativePath, canvas: canvas) == pngData("one"))38        #expect(try await store.verify(first.relativePath, canvas: canvas))39        #expect(try await store.totalSize(of: canvas) == pngData("one").count + pdfData().count)40        // A file imported from disk is typed by its bytes, whatever its name says.41        let disguised = root.appending(path: "holiday.png")42        try pdfData("disguised").write(to: disguised)43        #expect(try await store.importFile(at: disguised, into: canvas).kind == .pdf)44        let script = root.appending(path: "picture.png")45        try Data("#!/bin/sh\nrm -rf ~\n".utf8).write(to: script)46        await #expect(throws: CanvasAttachmentError.unsupportedType) { try await store.importFile(at: script, into: canvas) }47    }4849    @Test func rejectsEmptyWrongTypeAndOversizedData() async throws {50        let root = temporaryDirectory()51        defer { try? FileManager.default.removeItem(at: root) }52        var limits = CanvasAttachmentStore.Limits()53        limits.maximumImageBytes = 6454        limits.maximumPDFBytes = 12855        limits.maximumCanvasBytes = 15056        let store = CanvasAttachmentStore(root: root, limits: limits)57        let canvas = CanvasID()58        await #expect(throws: CanvasAttachmentError.empty) { try await store.importData(Data(), into: canvas) }59        await #expect(throws: CanvasAttachmentError.unsupportedType) { try await store.importData(Data("plain text".utf8), into: canvas) }60        let bigImage = pngData(String(repeating: "x", count: 100))61        await #expect(throws: CanvasAttachmentError.tooLarge(limit: 64, actual: bigImage.count)) { try await store.importData(bigImage, into: canvas) }62        // The same size is fine for a PDF, whose limit is higher.63        _ = try await store.importData(pdfData(String(repeating: "x", count: 100)), into: canvas)64        await #expect(throws: CanvasAttachmentError.quotaExceeded(limit: 150)) { try await store.importData(pngData(String(repeating: "y", count: 50)), into: canvas) }65        let huge = root.appending(path: "huge.pdf")66        try Data(count: 4_096).write(to: huge)67        await #expect(throws: CanvasAttachmentError.tooLarge(limit: 128, actual: 4_096)) { try await store.importFile(at: huge, into: canvas) }68        #expect(try await store.storedFiles(of: canvas).count == 1)69    }7071    @Test func pathTraversalNamesAreRefused() async throws {72        let root = temporaryDirectory()73        defer { try? FileManager.default.removeItem(at: root) }74        let secret = root.appending(path: "secret.png")75        try pngData("secret").write(to: secret)76        let store = CanvasAttachmentStore(root: root.appending(path: "attachments"))77        let canvas = CanvasID()78        let valid = try await store.importData(pngData(), into: canvas)79        let hash = valid.sha25680        let hostile = ["../secret.png", "../../secret.png", "/etc/passwd", "secret.png", "", ".", "..", "\(hash).png/../../secret.png",81                       "\(hash)", "\(hash).exe", "\(hash).PNG", "\(hash.uppercased()).png", "\(hash.dropLast()).png", "%2e%2e/secret.png",82                       "\(hash).png\u{0}.txt", "sub/\(hash).png", "\(hash).png ", "..\\secret.png", "\(hash).p.ng"]83        for name in hostile {84            #expect(!CanvasAttachmentStore.isSafeRelativePath(name), "\(name)")85            #expect(throws: CanvasAttachmentError.unsafePath(name)) { try store.url(for: name, canvas: canvas) }86            await #expect(throws: CanvasAttachmentError.unsafePath(name)) { try await store.data(for: name, canvas: canvas) }87        }88        #expect(CanvasAttachmentStore.isSafeRelativePath(valid.relativePath))89        let location = try store.url(for: valid.relativePath, canvas: canvas)90        #expect(location.standardizedFileURL.path.hasPrefix(store.directory(for: canvas).standardizedFileURL.path))91        let missing = String(repeating: "0", count: 64) + ".png"92        await #expect(throws: CanvasAttachmentError.notFound(missing)) { try await store.data(for: missing, canvas: canvas) }93        // A document smuggling a path is invalid.94        let document = CanvasDocument(title: "x", cards: [CanvasCard(content: .image(relativePath: "../secret.png"), origin: .zero)])95        #expect(CanvasEditor.validate(document).contains(.unsafeAttachmentPath(document.cards[0].id)))96    }9798    @Test func orphanCleanupKeepsReferencedFilesOnly() async throws {99        let root = temporaryDirectory()100        defer { try? FileManager.default.removeItem(at: root) }101        let store = CanvasAttachmentStore(root: root)102        var (editor, _) = makeEditor()103        let canvas = editor.document.id104        let kept = try await store.importData(pngData("kept"), into: canvas)105        let orphan = try await store.importData(pngData("orphan"), into: canvas)106        let pdf = try await store.importData(pdfData("kept"), into: canvas)107        try editor.addCard(.image(relativePath: kept.relativePath), at: .zero)108        try editor.addCard(.pdf(relativePath: pdf.relativePath, page: 3), at: .zero)109        // Files that are not attachments are never touched by the cleanup.110        let foreign = store.directory(for: canvas).appending(path: "notes.txt")111        try Data("mine".utf8).write(to: foreign)112        #expect(CanvasAttachmentStore.referencedPaths(in: editor.document) == [kept.relativePath, pdf.relativePath])113        #expect(try await store.removeOrphans(of: editor.document) == [orphan.relativePath])114        #expect(try await store.storedFiles(of: canvas) == [kept.relativePath, pdf.relativePath].sorted())115        #expect(FileManager.default.fileExists(atPath: foreign.path))116        #expect(try await store.removeOrphans(of: editor.document).isEmpty)117        try await store.removeAll(of: canvas)118        #expect(!FileManager.default.fileExists(atPath: store.directory(for: canvas).path))119        try await store.removeAll(of: canvas)120    }121}122123@Suite struct CanvasPersistenceTests {124    func sampleDocument() throws -> CanvasDocument {125        var (editor, ids) = makeEditor(cards: 3)126        try editor.addCard(.page(url: URL(string: "https://example.org/a_(b)?q=1")!, title: "Example [page]"), at: CanvasPoint(x: 40, y: 400), tint: .ocean)127        try editor.addCard(.image(relativePath: String(repeating: "a", count: 64) + ".png"), at: CanvasPoint(x: 400, y: 400))128        try editor.addCard(.pdf(relativePath: String(repeating: "b", count: 64) + ".pdf", page: 2), at: CanvasPoint(x: 800, y: 400))129        editor.setContent(.note(text: "First line\nsecond *line*"), of: ids[0])130        try editor.connect(from: ids[0], to: ids[1], label: "leads to")131        try editor.connect(from: ids[0], to: ids[2])132        editor.zoom(to: 1.5, around: CanvasPoint(x: 10, y: 10), viewSize: CanvasSize(width: 800, height: 600))133        return editor.document134    }135136    @Test func saveAndLoadThroughTheDatabaseAreEqual() async throws {137        let database = try await NavigatorDatabase.inMemory()138        let document = try sampleDocument()139        try await database.canvases.save(document)140        let loaded = try #require(try await database.canvases.document(document.id))141        #expect(loaded == document)142        #expect(CanvasEditor(document: loaded).validate().isEmpty)143        await database.close()144    }145146    @Test func autosaverDebouncesAndStampsTheDate() async throws {147        let database = try await NavigatorDatabase.inMemory()148        let saver = CanvasAutosaver(database: database, delay: .milliseconds(60))149        var (editor, ids) = makeEditor(cards: 2)150        for step in 1...25 {151            editor.move([ids[0]], by: CanvasPoint(x: 20, y: 0))152            await saver.schedule(editor.document, at: Date(timeIntervalSince1970: 2_000 + Double(step)))153        }154        #expect(await saver.hasPendingChanges)155        #expect(try await database.canvases.document(editor.document.id) == nil)156        let deadline = ContinuousClock.now + .seconds(5)157        while await saver.hasPendingChanges, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }158        let stored = try #require(try await database.canvases.document(editor.document.id))159        #expect(stored.cards == editor.document.cards)160        #expect(stored.updatedAt == Date(timeIntervalSince1970: 2_025))161        #expect(await saver.savedCount == 1)162        // flush writes at once.163        editor.setTitle("Flushed")164        await saver.schedule(editor.document)165        try await saver.flush()166        #expect(try await database.canvases.document(editor.document.id)?.title == "Flushed")167        #expect(await saver.lastError == nil)168        await database.close()169    }170171    @Test func autosaverKeepsADocumentItCouldNotSaveAndReportsTheError() async throws {172        let database = try await NavigatorDatabase.inMemory()173        let saver = CanvasAutosaver(database: database, delay: .seconds(60))174        var document = try sampleDocument()175        document.spaceID = SpaceID()   // not stored: the save is refused176        await saver.schedule(document)177        await #expect(throws: PersistenceError.self) { try await saver.flush() }178        #expect(await saver.hasPendingChanges)179        #expect(await saver.lastError != nil)180        await saver.discard(document.id)181        try await saver.flush()182        #expect(await saver.lastError == nil)183        await database.close()184    }185186    @Test func jsonExportRoundTripsAndIsStable() throws {187        let document = try sampleDocument()188        let date = Date(timeIntervalSince1970: 1_800_000_000)189        let data = try CanvasExport.json(document, exportedAt: date)190        #expect(data == (try CanvasExport.json(document, exportedAt: date)))191        let text = String(decoding: data, as: UTF8.self)192        #expect(text.contains("\"format\" : \"orix.canvas\"") && text.contains("\"version\" : 1"))193        var expected = document194        // ISO 8601 keeps whole seconds; the fixture dates are whole seconds.195        expected.createdAt = document.createdAt196        #expect(try CanvasExport.document(fromJSON: data) == expected)197        let copy = try CanvasExport.document(fromJSON: data, assigningNewIDs: true)198        #expect(copy.id != document.id && copy.cards.count == document.cards.count)199        #expect(Set(copy.cards.map(\.id)).isDisjoint(with: Set(document.cards.map(\.id))))200        #expect(copy.connections.count == document.connections.count)201        #expect(CanvasEditor.validate(copy).isEmpty)202        #expect(copy.cards.map(\.content) == document.cards.map(\.content))203    }204205    @Test func jsonImportRejectsForeignNewerAndInvalidFiles() throws {206        #expect(throws: CanvasExportError.notACanvasFile) { try CanvasExport.document(fromJSON: Data("{}".utf8)) }207        #expect(throws: CanvasExportError.notACanvasFile) { try CanvasExport.document(fromJSON: Data("not json".utf8)) }208        #expect(throws: CanvasExportError.notACanvasFile) { try CanvasExport.document(fromJSON: Data(#"{"format":"orix.canvas","version":1}"#.utf8)) }209        var object = try #require(try JSONSerialization.jsonObject(with: try CanvasExport.json(try sampleDocument())) as? [String: Any])210        object["version"] = 2211        #expect(throws: CanvasExportError.unsupportedVersion(2)) {212            try CanvasExport.document(fromJSON: try JSONSerialization.data(withJSONObject: object))213        }214        var broken = try sampleDocument()215        broken.connections.append(CanvasConnection(from: broken.cards[0].id, to: CanvasCardID()))216        broken.cards[1].content = .image(relativePath: "../../etc/passwd")217        let data = try CanvasExport.json(broken)218        #expect(throws: CanvasExportError.invalidDocument(issueCount: 2)) { try CanvasExport.document(fromJSON: data) }219    }220221    @Test func markdownOutline() throws {222        let outline = CanvasExport.markdownOutline(try sampleDocument())223        let lines = outline.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)224        #expect(lines[0] == "# Test")225        #expect(lines.contains("- First line"))226        #expect(lines.contains("  second \\*line\\*"))227        #expect(lines.contains("  - → card 1 — leads to"))228        #expect(lines.contains("  - → card 2"))229        #expect(lines.contains("- [Example \\[page\\]](https://example.org/a_(b%29?q=1)"))230        #expect(lines.contains { $0.hasPrefix("- PDF `bbbb") && $0.hasSuffix("page 2") })231        // Reading order: the row at y = 0 comes before the row at y = 400.232        #expect(lines.firstIndex(of: "- card 2")! < lines.firstIndex { $0.hasPrefix("- [Example") }!)233        #expect(CanvasExport.markdownOutline(CanvasDocument(title: "")) == "# Untitled canvas\n\n")234    }235236    @Test func renderPlanPlacesEverythingInOutputCoordinates() throws {237        let document = try sampleDocument()238        let plan = try #require(CanvasExport.renderPlan(document, margin: 20, scale: 2))239        #expect(plan.sourceBounds == CanvasRect(x: -20, y: -20, width: 1_100, height: 620))240        #expect(plan.size == CanvasSize(width: 2_200, height: 1_240))241        #expect(plan.cards.count == 6 && plan.routes.count == 2)242        #expect(plan.cards[0].frame == CanvasRect(x: 40, y: 40, width: 400, height: 200))243        let page = CanvasRect(origin: .zero, size: plan.size)244        #expect(plan.cards.allSatisfy { page.contains($0.frame) })245        #expect(plan.routes.allSatisfy { page.contains($0.start) && page.contains($0.end) })246        // The scale is lowered to respect the maximum dimension.247        let small = try #require(CanvasExport.renderPlan(document, margin: 0, scale: 4, maximumDimension: 530))248        #expect(abs(small.size.width - 530) < 1e-9 && small.scale < 1)249        let subset = try #require(CanvasExport.renderPlan(document, ids: [document.cards[0].id, document.cards[1].id]))250        #expect(subset.cards.count == 2 && subset.routes.count == 1)251        #expect(CanvasExport.renderPlan(CanvasDocument(title: "empty")) == nil)252    }253}254
Files main
Menu

Theme