Files
VCCPlusOSS/platforms/macos/Tests/SoftwareLibraryArchiveTests.swift

125 lines
8.4 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
final class SoftwareLibraryArchiveTests: XCTestCase {
private var root: URL!
override func setUpWithError() throws {
root = FileManager.default.temporaryDirectory.appendingPathComponent("LibraryArchive-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
}
override func tearDownWithError() throws { try? FileManager.default.removeItem(at: root) }
private struct Entry {
var name: String
var data = Data("HELLO".utf8)
var mode: UInt32 = 0o100777
var flags: UInt16 = 0x800
var method: UInt16 = 0
var crc: UInt32?
var declaredSize: UInt32?
var localName: String?
}
// Synthetic stored ZIPs keep hostile fixtures inspectable and out of the
// software catalog. Central-directory Unix modes exercise link/device checks.
private func zip(_ entries: [Entry]) -> Data {
var body = Data(), central = Data()
for entry in entries {
let name = Data(entry.name.utf8), localName = Data((entry.localName ?? entry.name).utf8)
let offset = UInt32(body.count), crc = entry.crc ?? Self.crc32(entry.data)
let size = entry.declaredSize ?? UInt32(entry.data.count)
body.le32(0x04034b50); body.le16(20); body.le16(entry.flags); body.le16(entry.method)
body.le16(0); body.le16(0); body.le32(crc); body.le32(UInt32(entry.data.count)); body.le32(size)
body.le16(UInt16(localName.count)); body.le16(0); body.append(localName); body.append(entry.data)
central.le32(0x02014b50); central.le16(0x0314); central.le16(20); central.le16(entry.flags); central.le16(entry.method)
central.le16(0); central.le16(0); central.le32(crc); central.le32(UInt32(entry.data.count)); central.le32(size)
central.le16(UInt16(name.count)); central.le16(0); central.le16(0); central.le16(0); central.le16(0)
central.le32(entry.mode << 16); central.le32(offset); central.append(name)
}
let offset = UInt32(body.count); body.append(central)
body.le32(0x06054b50); body.le16(0); body.le16(0); body.le16(UInt16(entries.count)); body.le16(UInt16(entries.count))
body.le32(UInt32(central.count)); body.le32(offset); body.le16(0)
return body
}
private static func crc32(_ bytes: Data) -> UInt32 {
var result: UInt32 = 0xffffffff
for byte in bytes {
result ^= UInt32(byte)
for _ in 0..<8 { result = (result >> 1) ^ (result & 1 == 0 ? 0 : 0xedb88320) }
}
return result ^ 0xffffffff
}
private func extract(_ bytes: Data, limit: UInt64 = 2_147_483_648, entries: UInt = 20_000, cancel: (() -> Bool)? = nil) throws -> (URL, [String]) {
let source = root.appendingPathComponent(UUID().uuidString + ".zip")
try bytes.write(to: source)
let destination = root.appendingPathComponent(UUID().uuidString)
let files = try VCCLibraryArchive.extractZIP(at: source, toNewDirectory: destination, maximumExpandedBytes: limit, maximumEntries: entries, shouldCancel: cancel)
return (destination, files)
}
private func rejected(_ bytes: Data, limit: UInt64 = 2_147_483_648, entries: UInt = 20_000) throws {
let source = root.appendingPathComponent(UUID().uuidString + ".zip")
try bytes.write(to: source)
let destination = root.appendingPathComponent(UUID().uuidString)
XCTAssertThrowsError(try VCCLibraryArchive.extractZIP(at: source, toNewDirectory: destination, maximumExpandedBytes: limit, maximumEntries: entries, shouldCancel: nil)) { error in
XCTAssertEqual((error as NSError).domain, "com.brianholman.vccplus.library.archive")
}
XCTAssertFalse(FileManager.default.fileExists(atPath: destination.path), "Failed extraction must remove only its new staging directory")
}
func testValidNestedFilesPreserveBytesAndRemoveExecutablePermissions() throws {
let payload = Data([0, 1, 2, 255])
let (destination, files) = try extract(zip([Entry(name: "Game/", data: Data(), mode: 0o040777), Entry(name: "Game/hello.dsk", data: payload), Entry(name: "Read me.txt")]))
XCTAssertEqual(files, ["Game/hello.dsk", "Read me.txt"])
XCTAssertEqual(try Data(contentsOf: destination.appendingPathComponent("Game/hello.dsk")), payload)
XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: destination.appendingPathComponent("Game/hello.dsk").path)[.posixPermissions] as? NSNumber, 0o644)
XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: destination.appendingPathComponent("Game").path)[.posixPermissions] as? NSNumber, 0o755)
XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: destination.path)[.posixPermissions] as? NSNumber, 0o755)
}
func testTraversalAbsoluteWindowsAndEmbeddedNULPathsAreRejected() throws {
for path in ["../escaped", "/absolute", "Game/../../escaped", "Game/./file", "Game//file", "C:/Windows/file", "Game\\file", "file\0hidden", "name:stream", "Game/\nfile"] {
try rejected(zip([Entry(name: path)]))
}
XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("escaped").path))
}
func testDuplicatesCaseAndUnicodeCollisionsAreRejectedIncludingParentDirectories() throws {
for names in [["same", "same"], ["Game.dsk", "game.dsk"], ["café.dsk", "cafe\u{301}.dsk"], ["Folder/one", "folder/two"], ["one", "one/two"], ["one/two", "one"]] {
try rejected(zip(names.map { Entry(name: $0) }))
}
}
func testLinksSpecialFilesEncryptionAndUnsupportedCompressionAreRejected() throws {
for mode: UInt32 in [0o120777, 0o020600, 0o060600, 0o010600] { try rejected(zip([Entry(name: "link", mode: mode)])) }
try rejected(zip([Entry(name: "secret", flags: 0x801)]))
try rejected(zip([Entry(name: "compressed", method: 99)]))
}
func testCorruptionTruncationAndHeaderMismatchAreRejected() throws {
try rejected(zip([Entry(name: "bad-crc", crc: 0)]))
try rejected(Data(zip([Entry(name: "file")]).dropLast(8)))
try rejected(zip([Entry(name: "central", localName: "another")]))
try rejected(zip([Entry(name: "bad-size", declaredSize: 1000)]))
try rejected(Data("not a ZIP".utf8))
}
func testSizeAndEntryLimitsAreEnforcedAndPreexistingDestinationsUntouched() throws {
try rejected(zip([Entry(name: "one", data: Data(repeating: 1, count: 100)), Entry(name: "two", data: Data(repeating: 2, count: 100))]), limit: 150)
try rejected(zip([Entry(name: "one"), Entry(name: "two")]), entries: 1)
let source = root.appendingPathComponent("source.zip"), existing = root.appendingPathComponent("existing")
try zip([Entry(name: "new")]).write(to: source)
try FileManager.default.createDirectory(at: existing, withIntermediateDirectories: false)
let marker = existing.appendingPathComponent("personal.txt"), original = Data("KEEP".utf8)
try original.write(to: marker)
XCTAssertThrowsError(try VCCLibraryArchive.extractZIP(at: source, toNewDirectory: existing, maximumExpandedBytes: 1000, maximumEntries: 20, shouldCancel: nil))
XCTAssertEqual(try Data(contentsOf: marker), original)
XCTAssertFalse(FileManager.default.fileExists(atPath: existing.appendingPathComponent("new").path))
}
func testCancellationDuringCopyRemovesStaging() throws {
let source = root.appendingPathComponent("large.zip"), destination = root.appendingPathComponent("cancelled")
try zip([Entry(name: "large", data: Data(repeating: 42, count: 512 * 1024))]).write(to: source)
var checks = 0
XCTAssertThrowsError(try VCCLibraryArchive.extractZIP(at: source, toNewDirectory: destination, maximumExpandedBytes: 2_147_483_648, maximumEntries: 20_000, shouldCancel: {
checks += 1; return checks > 5
})) { error in XCTAssertEqual((error as NSError).code, 6) }
XCTAssertGreaterThan(checks, 5)
XCTAssertFalse(FileManager.default.fileExists(atPath: destination.path))
}
}
private extension Data {
mutating func le16(_ value: UInt16) { append(UInt8(truncatingIfNeeded: value)); append(UInt8(truncatingIfNeeded: value >> 8)) }
mutating func le32(_ value: UInt32) { le16(UInt16(truncatingIfNeeded: value)); le16(UInt16(truncatingIfNeeded: value >> 16)) }
}