SPB Git

Repository Public License

SecurityAndRobustnessTests.swift 22.4 KB 281 lines swift

1// ORIX Convert — Packages/EnginePDF/Tests/EnginePDFTests/SecurityAndRobustnessTests.swift2// Description: Protected PDFs (passwords, permission flags, protection carried to results), malformed input,3//              cancellation, a 2 000-page document, inspection, preflight and the declared-path inventory.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import CoreGraphics7import PDFKit8import Testing9import ConvertCore10@testable import EnginePDF1112extension PDFEngineTests {13    @Suite struct Protection {14        typealias Op = PDFEngine.Operation1516        func expectEncrypted(_ request: ConversionRequest, _ fragment: String, sourceLocation: SourceLocation = #_sourceLocation) async {17            do {18                _ = try await Fx.run(request)19                Issue.record("expected a protection error", sourceLocation: sourceLocation)20            } catch ConversionError.encryptedInput(let message) {21                #expect(message.contains(fragment), "\(message)", sourceLocation: sourceLocation)22            } catch {23                Issue.record("unexpected error \(error)", sourceLocation: sourceLocation)24            }25        }2627        @Test func lockedDocumentNeedsItsPassword() async throws {28            let pdf = Fx.protect(Fx.simplePDF("secret.pdf", pages: 3, word: "Secret"), name: "locked.pdf", user: "user-pw", owner: "owner-pw", permissions: Fx.printOnly)29            await expectEncrypted(Fx.request(pdf, to: .txt), "needs a password")30            await expectEncrypted(Fx.request(pdf, to: .txt, ["password": .string("wrong")]), "not correct")31            #expect(Fx.engine.preflight(Fx.request(pdf, to: .txt), inspection: nil).contains { $0.code == "password-needed" })32            #expect(Fx.engine.preflight(Fx.request(pdf, to: .txt, ["password": .string("wrong")]), inspection: nil).contains { $0.code == "password-wrong" })33            let inspection = try await Fx.engine.inspect(pdf, format: .pdf)34            #expect(inspection.isEncrypted == true && inspection.pageCount == nil && !inspection.notes.isEmpty)35            #expect(throws: ConversionError.self) { try PDFPreview.pageCount(of: pdf) }36            #expect(try PDFPreview.pageCount(of: pdf, password: "user-pw") == 3)37            #expect(try PDFPreview.thumbnail(of: pdf, maxPixelSize: 100, password: "user-pw").height == 100)3839            // The user password opens the file but the owner's restrictions hold: printing only.40            let user: [String: OptionValue] = ["password": .string("user-pw")]41            await expectEncrypted(Fx.request(pdf, to: .txt, user), "copying")42            await expectEncrypted(Fx.request(pdf, to: .docx, user), "copying")43            await expectEncrypted(Fx.request(pdf, to: .folder, op: Op.extractImages, user), "copying")44            await expectEncrypted(Fx.request(pdf, to: .pdf, op: Op.extractPages, user.merging(["pages": .string("1")]) { a, _ in a }), "assembling")45            await expectEncrypted(Fx.request(pdf, to: .pdf, op: Op.merge, user, more: [Fx.simplePDF("plain.pdf", pages: 1)]), "assembling")46            await expectEncrypted(Fx.request(pdf, to: .folder, op: Op.split, user), "assembling")47            await expectEncrypted(Fx.request(pdf, to: .pdf, op: Op.rotate, user), "assembling")48            await expectEncrypted(Fx.request(pdf, to: .pdf, op: Op.compress, user), "changing")49            await expectEncrypted(Fx.request(pdf, to: .pdf, op: Op.ocr, user), "changing")50            await expectEncrypted(Fx.request(pdf, to: .pdf, op: Op.setMetadata, user.merging(["metadata.title": .string("x")]) { a, _ in a }), "changing")51            #expect(Fx.engine.preflight(Fx.request(pdf, to: .txt, user), inspection: nil).contains { $0.code == "not-permitted" })52            let printed = try await Fx.run(Fx.request(pdf, to: .png, user.merging(["pages": .string("1"), "resolution.dpi": .int(72)]) { a, _ in a }))53            #expect(Fx.load(printed.file)?.width == 612)5455            // The owner password lifts the restrictions.56            let owner: [String: OptionValue] = ["password": .string("owner-pw")]57            #expect(Fx.text(try await Fx.run(Fx.request(pdf, to: .txt, owner)).file).contains("SecretPAGE2"))58            let extracted = try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.extractPages, owner.merging(["pages": .string("2")]) { a, _ in a }))59            #expect(PDFDocument(url: extracted.file)?.isEncrypted == false && extracted.hasWarning("encryption-not-carried"))60            #expect(Fx.pdfText(extracted.file, page: 0).contains("SecretPAGE2"))61            let reprotected = try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.extractPages, owner.merging(["pages": .string("2"), "output.password.user": .string("new-pw")]) { a, _ in a }))62            let reopened = try #require(PDFDocument(url: reprotected.file))63            #expect(reopened.isLocked && !reopened.unlock(withPassword: "user-pw") && reopened.unlock(withPassword: "new-pw"))64        }6566        @Test func restrictedDocumentKeepsItsRestrictions() async throws {67            let assemble = Fx.printOnly | PDFAccessPermissions.allowsDocumentAssembly.rawValue68            let plain = Fx.simplePDF("restricted-source.pdf", pages: 3, word: "Guard")69            let pdf = Fx.protect(plain, name: "restricted.pdf", user: nil, owner: "owner-pw", permissions: assemble)70            let source = try #require(PDFDocument(url: pdf))71            #expect(source.isEncrypted && !source.isLocked && !source.allowsCopying && source.allowsDocumentAssembly)72            await expectEncrypted(Fx.request(pdf, to: .txt), "copying")73            let inspection = try await Fx.engine.inspect(pdf, format: .pdf)74            #expect(inspection.fields.contains { $0.key == "Copying content" && $0.value == "not allowed" } && inspection.fields.contains { $0.key == "Assembling pages" && $0.value == "allowed" })7576            // Allowed by the flags, without the owner password: the results stay protected with the same restrictions.77            func stillRestricted(_ url: URL) -> Bool {78                guard let d = PDFDocument(url: url) else { return false }79                return d.isEncrypted && !d.allowsCopying && d.allowsPrinting && d.permissionsStatus != .owner80            }81            let rotated = try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.rotate))82            #expect(stillRestricted(rotated.file) && PDFDocument(url: rotated.file)?.page(at: 0)?.rotation == 90)83            let extracted = try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.extractPages, ["pages": .string("3,1")]))84            #expect(stillRestricted(extracted.file) && Fx.structure(extracted.file).pages == 2)85            let attempt = try #require(PDFDocument(url: extracted.file))86            _ = attempt.unlock(withPassword: "owner-pw")87            #expect(attempt.permissionsStatus != .owner && !attempt.allowsCopying)                       // new random owner password88            let kept = try #require(PDFDocument(url: rotated.file))89            _ = kept.unlock(withPassword: "owner-pw")90            #expect(kept.permissionsStatus == .owner)                                                    // a plain rewrite keeps the original protection91            let merged = try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.merge, more: [plain]))92            #expect(stillRestricted(merged.file) && Fx.structure(merged.file).pages == 6)93            let parts = try await Fx.run(Fx.request(pdf, to: .folder, op: Op.split))94            #expect(parts.files.count == 3 && parts.files.allSatisfy(stillRestricted))95            await expectEncrypted(Fx.request(extracted.file, to: .txt), "copying")96            #expect(Fx.engine.preflight(Fx.request(pdf, to: .pdf, op: Op.rotate), inspection: nil).contains { $0.code == "protection-kept" })97            // New passwords need the owner password.98            await #expect(throws: ConversionError.self) { try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.rotate, ["output.password.user": .string("x")])) }99            // With the owner password everything is allowed.100            #expect(Fx.text(try await Fx.run(Fx.request(pdf, to: .txt, ["password": .string("owner-pw")])).file).contains("GuardPAGE1"))101        }102103        @Test func resultsCanBeEncrypted() async throws {104            let a = Fx.simplePDF("enc-a.pdf", pages: 2, word: "Enc"), b = Fx.simplePDF("enc-b.pdf", pages: 1, word: "Enc")105            let merged = try await Fx.run(Fx.request(a, to: .pdf, op: Op.merge, ["output.password.user": .string("open"), "output.password.owner": .string("own")], more: [b]))106            let document = try #require(PDFDocument(url: merged.file))107            #expect(document.isLocked && document.unlock(withPassword: "open") && document.pageCount == 3)108            #expect(merged.output.facts["encrypted"] == "yes")109            let ownerOnly = try await Fx.run(Fx.request(a, to: .pdf, op: Op.rotate, ["output.password.owner": .string("own")]))110            #expect(PDFDocument(url: ownerOnly.file)?.isEncrypted == true && PDFDocument(url: ownerOnly.file)?.isLocked == false)111        }112    }113114    @Suite struct Robustness {115        typealias Op = PDFEngine.Operation116117        @Test func malformedAndTruncatedFiles() async throws {118            let dir = Fx.dir("bad")119            let garbage = dir.appendingPathComponent("garbage.pdf"), empty = dir.appendingPathComponent("empty.pdf"), headerOnly = dir.appendingPathComponent("header.pdf")120            let missing = dir.appendingPathComponent("missing.pdf"), truncated = dir.appendingPathComponent("truncated.pdf"), tail = dir.appendingPathComponent("tail.pdf")121            var noise = Data(count: 20_000)122            for i in 0..<noise.count { noise[i] = UInt8((i &* 2654435761) >> 7 & 0xFF) }123            try noise.write(to: garbage)124            try Data().write(to: empty)125            try Data("%PDF-1.7\n".utf8).write(to: headerOnly)126            let good = try Data(contentsOf: Fx.richPDF("to-truncate.pdf"))127            try good.prefix(good.count / 2).write(to: truncated)128            try good.suffix(good.count / 2).write(to: tail)129            for url in [garbage, empty, headerOnly, missing, tail] {130                for request in [Fx.request(url, to: .png), Fx.request(url, to: .txt), Fx.request(url, to: .docx), Fx.request(url, to: .pdf, op: Op.ocr),131                                Fx.request(url, to: .pdf, op: Op.compress), Fx.request(url, to: .folder, op: Op.split), Fx.request(url, to: .folder, op: Op.extractImages),132                                Fx.request(Fx.simplePDF("ok.pdf", pages: 1), to: .pdf, op: Op.merge, more: [url])] {133                    await #expect(throws: ConversionError.self, "\(url.lastPathComponent) \(request.operation ?? request.destinationFormat.rawValue)") { try await Fx.run(request) }134                }135                await #expect(throws: ConversionError.self) { try await Fx.engine.inspect(url, format: .pdf) }136                #expect(throws: ConversionError.self) { try PDFPreview.pageCount(of: url) }137                _ = Fx.engine.preflight(Fx.request(url, to: .txt), inspection: nil)        // must not crash138            }139            // A file cut in half: either a clean error, or whatever PDFKit can repair must still validate.140            for request in [Fx.request(truncated, to: .txt), Fx.request(truncated, to: .png, ["resolution.dpi": .int(36)]), Fx.request(truncated, to: .folder, op: Op.split)] {141                do { _ = try await Fx.run(request) } catch is ConversionError {}142            }143            // A page tree that points at itself, and absurd page sizes.144            func s(_ t: String) -> Data { Data(t.utf8) }145            let loop = dir.appendingPathComponent("loop.pdf")146            try Fx.rawPDF([(1, s("<< /Type /Catalog /Pages 2 0 R >>")), (2, s("<< /Type /Pages /Kids [2 0 R 3 0 R] /Count 2 >>")),147                           (3, s("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 1e12 -5] /Resources << /XObject << /X 4 0 R >> >> /Contents 5 0 R >>")),148                           (4, Fx.stream("/Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /XObject << /X 4 0 R >> >>", s("/X Do"))),149                           (5, Fx.stream("", s("/X Do q q q Q Q Q Q Q 1 0 0 cm (unbalanced")))], root: 1).write(to: loop)150            for request in [Fx.request(loop, to: .png, ["resolution.dpi": .int(36)]), Fx.request(loop, to: .txt, ["ocr": .string("off")]), Fx.request(loop, to: .folder, op: Op.extractImages), Fx.request(loop, to: .pdf, op: Op.compress)] {151                do { _ = try await Fx.run(request, validate: false) } catch is ConversionError {}152            }153            _ = try? await Fx.engine.inspect(loop, format: .pdf)154        }155156        @Test func cancellationStopsTheWork() async throws {157            let pdf = Fx.simplePDF("cancel.pdf", pages: 3_000, word: "Cancel")158            let cases: [(ConversionRequest, Int)] = [159                (Fx.request(pdf, to: .png, ["resolution.dpi": .int(300)]), 150), (Fx.request(pdf, to: .txt), 30), (Fx.request(pdf, to: .pdf, op: Op.compress), 60),160                (Fx.request(pdf, to: .folder, op: Op.split), 150), (Fx.request(pdf, to: .pdf, op: Op.ocr, ["ocr.pages": .string("all")]), 300),161                (Fx.request(pdf, to: .docx), 60), (Fx.request(pdf, to: .folder, op: Op.extractImages), 20),162            ]163            for (request, delay) in cases {164                let work = Fx.dir("cancel")165                let started = Date()166                let task = Task { try await Fx.engine.convert(request, context: ConversionContext(workDirectory: work)) }167                try await Task.sleep(for: .milliseconds(delay))168                task.cancel()169                do {170                    _ = try await task.value171                    Issue.record("\(request.operation ?? "export") finished before it could be cancelled")172                } catch is CancellationError {173                    #expect(Date().timeIntervalSince(started) < 20)174                }175                // Nothing usable is left behind for a cancelled PDF rewrite.176                if request.destinationFormat == .pdf { #expect(!FileManager.default.fileExists(atPath: work.appendingPathComponent("cancel.pdf").path)) }177            }178            let already = Task { () -> ConversionOutput in179                withUnsafeCurrentTask { $0?.cancel() }180                return try await Fx.engine.convert(Fx.request(pdf, to: .txt), context: ConversionContext(workDirectory: Fx.dir("cancel")))181            }182            await #expect(throws: CancellationError.self) { try await already.value }183        }184185        @Test func twoThousandPages() async throws {186            func timed<T>(_ label: String, _ body: () async throws -> T) async rethrows -> T {187                let start = Date()188                let value = try await body()189                print("MEASURE 2000-pages \(label): \(String(format: "%.2f", Date().timeIntervalSince(start))) s, peak RSS so far \(String(format: "%.0f", Fx.peakRSSMegabytes())) MB")190                return value191            }192            let pdf = await timed("generate fixture") { Fx.simplePDF("big.pdf", pages: 2_000, word: "Big") }193            print("MEASURE 2000-pages fixture size: \(Fx.size(pdf)) bytes")194            let inspection = try await timed("inspect") { try await Fx.engine.inspect(pdf, format: .pdf) }195            #expect(inspection.pageCount == 2_000)196            let text = try await timed("text export (2000 pages)") { try await Fx.run(Fx.request(pdf, to: .txt, ["text.page-separator": .string("marker")])) }197            let exported = Fx.text(text.file)198            #expect(exported.contains("BigPAGE1 ") && exported.contains("BigPAGE2000") && exported.contains("----- Page 2000 -----"))199            let extracted = try await timed("extract 21 pages") { try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.extractPages, ["pages": .string("1-10,1990-")])) }200            #expect(Fx.structure(extracted.file).pages == 21 && Fx.pdfText(extracted.file, page: 20).contains("BigPAGE2000"))201            let parts = try await timed("split every 500") { try await Fx.run(Fx.request(pdf, to: .folder, op: Op.split, ["split.mode": .string("every-n"), "split.every": .int(500)])) }202            #expect(parts.files.count == 4)203            let single = try await timed("split every page (2000 files)") { try await Fx.run(Fx.request(pdf, to: .folder, op: Op.split)) }204            #expect(single.files.count == 2_000 && single.files[1_999].lastPathComponent == "big-2000.pdf")205            let merged = try await timed("merge with itself (4000 pages)") { try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.merge, more: [pdf])) }206            #expect(Fx.structure(merged.file).pages == 4_000 && Fx.pdfText(merged.file, page: 2_000).contains("BigPAGE1 "))207            let rotated = try await timed("rotate all") { try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.rotate, ["rotate.angle": .string("180")])) }208            #expect(PDFDocument(url: rotated.file)?.page(at: 1_234)?.rotation == 180)209            let rendered = try await timed("render 3 pages at 72 dpi") { try await Fx.run(Fx.request(pdf, to: .png, ["pages": .string("1,1000,2000"), "resolution.dpi": .int(72)])) }210            #expect(rendered.files.map(\.lastPathComponent) == ["big-0001.png", "big-1000.png", "big-2000.png"])211            _ = try await timed("compress attempt (2000 pages)") { try await Fx.run(Fx.request(pdf, to: .pdf, op: Op.compress)) }212            #expect(Fx.engine.preflight(Fx.request(pdf, to: .png), inspection: nil).contains { $0.code == "many-pages" })213            #expect(Fx.engine.preflight(Fx.request(pdf, to: .pdf, op: Op.compress), inspection: nil).contains { $0.code == "many-pages" })214            #expect(Fx.peakRSSMegabytes() < 4_096)215        }216217        @Test func inspectionReportsWhatIsInTheFile() async throws {218            let rich = try await Fx.engine.inspect(Fx.richPDF("inspect-rich.pdf"), format: .pdf)219            func value(_ inspection: FileInspection, _ key: String) -> String? { inspection.fields.first { $0.key == key }?.value }220            #expect(rich.pageCount == 4 && rich.isEncrypted == false && rich.hasMetadata == true)221            #expect(value(rich, "Outline entries") == "4" && value(rich, "Annotations") == "4" && value(rich, "Title") == "Rich Fixture")222            #expect(value(rich, "First page size") == "612 × 792 pt (215.9 × 279.4 mm)" && value(rich, "Distinct page sizes") == "1")223            #expect(value(rich, "Text layer") == "yes (4 of all 4 pages)" && value(rich, "Attachments") == "no" && value(rich, "Linearised (fast web view)") == "no")224            #expect(value(rich, "PDF version") != nil)225            #expect(rich.fields.contains { $0.group == "Fonts" && $0.key.contains("Helvetica") })226227            let features = try await Fx.engine.inspect(Fx.featurePDF("inspect-features.pdf"), format: .pdf)228            #expect(value(features, "Attachments") == "yes" && value(features, "Tagged (accessibility structure)") == "yes" && value(features, "XMP packet") == "yes")229            #expect(value(features, "Form fields") == "1 top-level" && value(features, "Linearised (fast web view)") == "yes" && value(features, "JavaScript") != nil)230            #expect(value(features, "Keywords") == "alpha, beta" && value(features, "PDF version") == "1.7")231            #expect(features.fields.contains { $0.group == "Fonts" && $0.key == "Helvetica" && $0.value == "Type1, not embedded" })232            #expect(value(features, "Images drawn") == "1 (all 1 pages), plus 1 inline")233234            let (imagePDF, _) = Fx.imageHeavyPDF("inspect-images.pdf")235            let images = try await Fx.engine.inspect(imagePDF, format: .pdf)236            #expect(value(images, "Images drawn") == "2 (all 2 pages)" && value(images, "Highest image resolution") == "500 dpi (all 2 pages)")237            #expect(images.fields.contains { $0.group == "Fonts" && $0.value.contains("embedded") && !$0.value.contains("not embedded") })238239            let scanned = try await Fx.engine.inspect(Fx.scannedPDF("inspect-scan.pdf", dpi: 100, variants: true), format: .pdf)240            #expect(value(scanned, "Text layer") == "none found (all 3 pages)" && scanned.notes.contains { $0.contains("OCR") })241            #expect(value(scanned, "Distinct page sizes") == "2" && value(scanned, "Rotated pages") == "1")242        }243244        @Test func everyDeclaredPathIsListedOnceWithSettings() {245            let engines = makeEngines()246            #expect(engines.count == 1 && engines[0].id == "pdf" && engines[0].availability() == .available)247            let paths = Fx.engine.paths248            #expect(Set(paths.map(\.id)).count == paths.count)249            let expected: Set<String> = [250                "pdf:pdf>png", "pdf:pdf>jpeg", "pdf:pdf>tiff", "pdf:pdf>txt", "pdf:pdf>markdown", "pdf:pdf>docx", "pdf:pdf>rtf",251                "pdf:png>pdf", "pdf:jpeg>pdf", "pdf:heic>pdf", "pdf:tiff>pdf", "pdf:gif>pdf", "pdf:bmp>pdf", "pdf:webp>pdf",252                "pdf:pdf>pdf#pdf.ocr", "pdf:pdf>pdf#pdf.merge", "pdf:pdf>folder#pdf.split", "pdf:pdf>pdf#pdf.extract-pages", "pdf:pdf>pdf#pdf.delete-pages",253                "pdf:pdf>pdf#pdf.reorder-pages", "pdf:pdf>pdf#pdf.rotate", "pdf:pdf>pdf#pdf.compress", "pdf:pdf>folder#pdf.extract-images", "pdf:pdf>pdf#pdf.set-metadata",254            ]255            #expect(Set(paths.map(\.id)) == expected)256            for path in paths {257                let options = Fx.engine.options(for: path)258                #expect(!options.isEmpty && Set(options.map(\.id)).count == options.count, "\(path.id)")259                for option in options {260                    #expect(option.id.wholeMatch(of: /[a-z0-9]+([.\-][a-z0-9]+)*/) != nil, "\(option.id)")261                    #expect(!option.label.isEmpty)262                }263                #expect(!path.limitations.isEmpty, "\(path.id)")264                #expect(path.acceptsMultipleSources == (path.destination == .pdf && (path.source != .pdf || path.operation == "pdf.merge")))265                #expect((path.status == .experimental) == (path.destination == .docx || path.destination == .rtf))266            }267            // Regression (2026-11-21): the image formats accepted by images → PDF must not be claimed for inspection268            // (the image engine inspects them; this engine reported them without the image engine's facts).269            #expect(Fx.engine.inspectableFormats == [.pdf])270        }271272        @Test func undeclaredRequestsAreRefused() async throws {273            let pdf = Fx.simplePDF("undeclared.pdf", pages: 1)274            let context = ConversionContext(workDirectory: Fx.dir("out"))275            await #expect(throws: ConversionError.self) { try await Fx.engine.convert(Fx.request(pdf, to: .html), context: context) }276            await #expect(throws: ConversionError.self) { try await Fx.engine.convert(Fx.request(pdf, to: .pdf, op: "pdf.sign"), context: context) }277            await #expect(throws: ConversionError.self) { try await Fx.engine.convert(Fx.request(pdf, to: .pdf, from: .psd), context: context) }278        }279    }280}281
Files main
Menu

Theme