SPB Git

Repository Public BSD-3-Clause

ContainerTests.swift 28.6 KB 484 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXMapPackage/Tests/ORIXMapPackageTests/ContainerTests.swift10// Module           : ORIXMapPackageTests11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import CryptoKit89import Foundation90import ORIXGeoCore91import Testing92@testable import ORIXMapPackage9394@Suite struct ContainerTests {95    let key = Curve25519.Signing.PrivateKey()96    let tmp = TempDir("container")97    var verifier: PackageVerifier { PackageVerifier(trustStore: Fixture.trust(key)) }9899    func small() throws -> (data: Data, header: PackageHeader, manifest: PackageManifest) {100        let p = try Fixture.makePackage(in: tmp.url, key: key)101        let data = try Data(contentsOf: p.url)102        return (data, try PackageHeader.parse(data), p.manifest)103    }104105    func verify(_ data: Data, _ v: PackageVerifier? = nil) -> PackageError? {106        let url = tmp.file("case-\(UUID().uuidString).orixmap")107        try! data.write(to: url)108        defer { try? FileManager.default.removeItem(at: url) }109        return packageError { _ = try (v ?? self.verifier).verify(at: url) }110    }111112    func patched(_ data: Data, at offset: Int, _ bytes: [UInt8]) -> Data {113        var d = data114        d.replaceSubrange(offset..<(offset + bytes.count), with: bytes)115        return d116    }117118    func le<T: FixedWidthInteger>(_ v: T) -> [UInt8] { withUnsafeBytes(of: v.littleEndian) { Array($0) } }119120    // MARK: Round trip121122    @Test func roundTripWithMultiMegabyteComponents() throws {123        let p = try Fixture.makePackage(in: tmp.url, sizes: [(.map, 6_300_000), (.search, 2_100_001), (.routing, 3_000_000), (.terrain, 4097)], key: key)124        let verified = try verifier.verify(at: p.url)125        #expect(verified.manifest == p.manifest)126        #expect(verified.manifest.capabilities == ["map", "search", "routing", "terrain"])127        #expect(verified.ignoredComponents.isEmpty)128        let size = try #require(try p.url.resourceValues(forKeys: [.fileSizeKey]).fileSize)129        #expect(UInt64(size) == verified.manifest.downloadSize)130        #expect(verified.preamble.header.totalLength == UInt64(size))131132        // Layout: aligned, in order, contiguous, and the bytes at each offset are the component.133        let file = try Data(contentsOf: p.url)134        for c in verified.manifest.components {135            #expect(c.offset % 4096 == 0)136            let bytes = file.subdata(in: Int(c.offset)..<Int(c.offset + c.length))137            #expect(bytes == p.components[c.id])138            #expect(sha256Hex(bytes) == c.sha256)139        }140141        // Extraction writes the fixed file names with the exact content.142        let out = tmp.file("extracted")143        _ = try verifier.extract(p.url, into: out)144        #expect(Set(try FileManager.default.contentsOfDirectory(atPath: out.path))145            == ["map.pmtiles", "search.sqlite", "routing.orixgraph", "terrain.pmtiles", "manifest.json", "manifest.sig"])146        #expect(try Data(contentsOf: out.appendingPathComponent("map.pmtiles")) == p.components[.map])147        #expect(try Data(contentsOf: out.appendingPathComponent("search.sqlite")) == p.components[.search])148        #expect(try Data(contentsOf: out.appendingPathComponent("routing.orixgraph")) == p.components[.routing])149        #expect(try Data(contentsOf: out.appendingPathComponent("terrain.pmtiles")) == p.components[.terrain])150        #expect(try Data(contentsOf: out.appendingPathComponent("manifest.json")) == verified.preamble.manifestBytes)151152        // Container overhead: everything that is not component bytes.153        let overhead = UInt64(size) - verified.manifest.installedSize154        #expect(overhead < 4096 * 5)155    }156157    @Test func preambleAloneIsEnoughToAuthenticateTheManifest() throws {158        let (data, header, manifest) = try small()159        #expect(try verifier.preambleLength(fromPrefix: data.prefix(64)) == header.preambleLength)160        let preamble = try verifier.verifyPreamble(data.prefix(Int(header.preambleLength)))161        #expect(preamble.manifest == manifest)162        #expect(preamble.signingKey.keyId == TrustedKey(key.publicKey).keyId)163        // A slice that does not start at index 0 works too.164        let shifted = (Data([1, 2, 3]) + data).dropFirst(3)165        #expect(try verifier.verifyPreamble(shifted).manifest == manifest)166        #expect(packageError { _ = try self.verifier.verifyPreamble(data.prefix(Int(header.preambleLength) - 1)) }167            == .truncated(section: .signature, needed: header.preambleLength, available: header.preambleLength - 1))168    }169170    @Test func writerIsDeterministicAndRefusesInvalidInput() throws {171        let a = try Fixture.makePackage(in: tmp.url, key: key)172        let b = try Fixture.makePackage(in: tmp.url, key: key)173        // CryptoKit Ed25519 signatures are randomized: two builds differ in the 64 signature bytes and nowhere else.174        var da = try Data(contentsOf: a.url), db = try Data(contentsOf: b.url)175        let h = try PackageHeader.parse(da)176        #expect(da != db)177        da.replaceSubrange(Int(h.signatureOffset)..<Int(h.preambleLength), with: Data(count: 64))178        db.replaceSubrange(Int(h.signatureOffset)..<Int(h.preambleLength), with: Data(count: 64))179        #expect(da == db, "same inputs and key give the same bytes outside the signature")180        let src = tmp.file("c.bin"); try Data([1, 2, 3]).write(to: src)181        var description = Fixture.description()182        description.regionId = "../evil"183        #expect(throws: PackageError.invalidManifest(.invalidRegionId("../evil"))) {184            try PackageWriter.write(description: description, components: [.init(id: .map, url: src, formatVersion: 3)], signingKey: self.key, to: self.tmp.file("x.orixmap"))185        }186        #expect(throws: PackageError.invalidManifest(.invalidComponentId("../map"))) {187            try PackageWriter.write(description: Fixture.description(), components: [.init(id: ComponentID(rawValue: "../map"), url: src, formatVersion: 3)],188                                    signingKey: self.key, to: self.tmp.file("x.orixmap"))189        }190        #expect(!FileManager.default.fileExists(atPath: tmp.file("x.orixmap").path))191        #expect(try FileManager.default.contentsOfDirectory(atPath: tmp.url.path).allSatisfy { !$0.contains(".tmp-") }, "no temporary file left")192    }193194    // MARK: Header195196    @Test func headerRejections() throws {197        let (data, header, _) = try small()198        #expect(verify(patched(data, at: 0, [0x50, 0x4B, 0x03, 0x04])) == .badMagic)199        #expect(verify(patched(data, at: 7, [0x00])) == .badMagic)200        #expect(verify(patched(data, at: 8, le(UInt16(2)))) == .unsupportedFormatVersion(major: 2, minor: 0))201        #expect(verify(patched(data, at: 8, le(UInt16(0)))) == .unsupportedFormatVersion(major: 0, minor: 0))202        #expect(verify(patched(data, at: 12, le(UInt32(63)))) == .invalidHeaderLength(63))203        #expect(verify(patched(data, at: 12, le(UInt32(4097)))) == .invalidHeaderLength(4097))204        #expect(verify(patched(data, at: 12, le(UInt32.max))) == .invalidHeaderLength(.max))205        #expect(verify(patched(data, at: 16, le(UInt32(0)))) == .emptyManifest)206        #expect(verify(patched(data, at: 16, le(UInt32((1 << 20) + 1)))) == .manifestTooLarge(size: (1 << 20) + 1, limit: 1 << 20))207        #expect(verify(patched(data, at: 16, le(UInt32.max))) == .manifestTooLarge(size: UInt64(UInt32.max), limit: 1 << 20))208        #expect(verify(patched(data, at: 20, le(UInt32(63)))) == .invalidSignatureLength(63))209        #expect(verify(patched(data, at: 20, le(UInt32.max))) == .invalidSignatureLength(.max))210        #expect(verify(patched(data, at: 24, le(UInt16(2)))) == .unsupportedSignatureAlgorithm(2))211        #expect(verify(patched(data, at: 40, le(UInt64.max))) == .invalidLayout(.totalTooLarge(length: .max, limit: 64 << 30)))212        #expect(verify(patched(data, at: 40, le(UInt64(10)))) == .truncated(section: .signature, needed: header.preambleLength, available: 10))213        // The total length of the header is bound to the signed manifest.214        #expect(verify(patched(data, at: 40, le(header.totalLength + 1)))215            == .invalidLayout(.totalLengthMismatch(header: header.totalLength + 1, manifest: header.totalLength)))216        // A manifest length that is wrong by one byte breaks the signature.217        #expect(verify(patched(data, at: 16, le(header.manifestLength - 1))) == .invalidSignature)218    }219220    @Test func unknownMinorVersionFlagsAndReservedBytesAreIgnored() throws {221        let (data, _, manifest) = try small()222        var future = patched(data, at: 10, le(UInt16(7)))223        future = patched(future, at: 28, le(UInt32(0xFFFF_FFFF)))224        future = patched(future, at: 26, [0xAA, 0xBB])225        future = patched(future, at: 48, [UInt8](repeating: 0xEE, count: 16))226        let url = tmp.file("future.orixmap"); try future.write(to: url)227        #expect(try verifier.verify(at: url).manifest == manifest)228    }229230    @Test func extendedHeaderOfALaterMinorVersionIsSkipped() throws {231        // Format 1.1 could append fields to the header: a 1.0 reader skips them thanks to the header length.232        let (data, header, manifest) = try small()233        let manifestBytes = data.subdata(in: 64..<Int(header.signatureOffset))234        var h = header235        h.headerLength = 96236        h.versionMinor = 1237        var out = h.encoded()238        out.replaceSubrange(64..<96, with: [UInt8](repeating: 0x5A, count: 32))239        out.append(manifestBytes)240        out.append(try key.signature(for: manifestBytes))241        #expect(out.count <= 4096)242        out.append(Data(count: 4096 - out.count))243        out.append(data.subdata(in: 4096..<data.count))244        let url = tmp.file("extended.orixmap"); try out.write(to: url)245        let verified = try verifier.verify(at: url)246        #expect(verified.manifest == manifest)247        #expect(verified.preamble.header.headerLength == 96)248    }249250    @Test func unknownOptionalComponentIsVerifiedButNotInstalled() throws {251        let p = try Fixture.makePackage(in: tmp.url, sizes: [(.map, 5000), (ComponentID(rawValue: "transit"), 3000), (.search, 100)], key: key)252        let verified = try verifier.verify(at: p.url)253        #expect(verified.ignoredComponents == [ComponentID(rawValue: "transit")])254        #expect(verified.manifest.capabilities == ["map", "search"])255        let out = tmp.file("out")256        _ = try verifier.extract(p.url, into: out)257        #expect(Set(try FileManager.default.contentsOfDirectory(atPath: out.path)) == ["map.pmtiles", "search.sqlite", "manifest.json", "manifest.sig"])258        // The unknown component is still authenticated.259        var data = try Data(contentsOf: p.url)260        let transit = try #require(verified.manifest.component(ComponentID(rawValue: "transit")))261        data[Int(transit.offset) + 10] ^= 0xFF262        #expect(verify(data) == .componentChecksumMismatch(component: "transit"))263    }264265    // MARK: Truncation266267    @Test func truncatedAtEveryStructuralBoundary() throws {268        let (data, header, manifest) = try small()269        var cuts: Set<Int> = [0, 1, 8, 63, 64, 65, Int(header.signatureOffset) - 1, Int(header.signatureOffset), Int(header.signatureOffset) + 1,270                              Int(header.preambleLength) - 1, Int(header.preambleLength), Int(header.preambleLength) + 1, data.count - 1]271        for c in manifest.components {272            for d in [-1, 0, 1] { cuts.insert(Int(c.offset) + d); cuts.insert(Int(c.offset + c.length) + d) }273        }274        for cut in cuts.sorted() where cut < data.count {275            guard case .truncated(let section, let needed, let available) = verify(data.prefix(cut)) else {276                Issue.record("cut at \(cut): expected a truncation error, got \(String(describing: verify(data.prefix(cut))))"); continue277            }278            #expect(available == UInt64(cut))279            #expect(needed > available)280            switch cut {281            case ..<64: #expect(section == .header)282            case ..<Int(header.signatureOffset): #expect(section == .manifest)283            case ..<Int(header.preambleLength): #expect(section == .signature)284            default: #expect(section == .component)285            }286        }287        // And one byte too many.288        #expect(verify(data + Data([0])) == .invalidLayout(.fileSizeMismatch(declared: header.totalLength, actual: header.totalLength + 1)))289        #expect(verify(data + Data(count: 4096)) == .invalidLayout(.fileSizeMismatch(declared: header.totalLength, actual: header.totalLength + 4096)))290    }291292    // MARK: Tampering293294    @Test func tamperedContentIsRejected() throws {295        let (data, header, manifest) = try small()296        // Any bit of the manifest.297        for offset in stride(from: 64, to: Int(header.signatureOffset), by: 37) {298            var d = data; d[offset] ^= 0x01299            #expect(verify(d) == .invalidSignature, "manifest byte \(offset)")300        }301        // Any bit of the signature.302        for offset in Int(header.signatureOffset)..<Int(header.preambleLength) {303            var d = data; d[offset] ^= 0x80304            #expect(verify(d) == .invalidSignature, "signature byte \(offset)")305        }306        // First, middle and last byte of every component.307        for c in manifest.components {308            for offset in [Int(c.offset), Int(c.offset + c.length / 2), Int(c.offset + c.length) - 1] {309                var d = data; d[offset] ^= 0x01310                #expect(verify(d) == .componentChecksumMismatch(component: c.id.rawValue))311            }312        }313        // Padding is not free space.314        var d = data; d[Int(header.preambleLength) + 5] = 1315        #expect(verify(d) == .invalidLayout(.nonZeroPadding(offset: header.preambleLength + 5)))316        let search = manifest.components[1]317        d = data; d[Int(search.offset) - 1] = 0xFF318        #expect(verify(d) == .invalidLayout(.nonZeroPadding(offset: search.offset - 1)))319        // Swapping two components (same bytes, other place) is detected.320        d = data321        let a = manifest.components[1], b = manifest.components[2]322        let n = Int(min(a.length, b.length))323        let chunkA = d.subdata(in: Int(a.offset)..<Int(a.offset) + n), chunkB = d.subdata(in: Int(b.offset)..<Int(b.offset) + n)324        d.replaceSubrange(Int(a.offset)..<Int(a.offset) + n, with: chunkB)325        d.replaceSubrange(Int(b.offset)..<Int(b.offset) + n, with: chunkA)326        #expect(verify(d) == .componentChecksumMismatch(component: "search"))327    }328329    // MARK: Keys330331    @Test func unknownRevokedAndExpiredKeys() throws {332        let (data, _, _) = try small()333        let keyId = TrustedKey(key.publicKey).keyId334        let other = Curve25519.Signing.PrivateKey()335        #expect(verify(data, PackageVerifier(trustStore: Fixture.trust(other))) == .unknownSigningKey(keyId: keyId))336        #expect(verify(data, PackageVerifier(trustStore: TrustStore(keys: []))) == .unknownSigningKey(keyId: keyId))337        #expect(verify(data, PackageVerifier(trustStore: Fixture.trust(other, key))) == nil, "several keys can be trusted at once (rotation)")338        #expect(verify(data, PackageVerifier(trustStore: TrustStore(keys: [TrustedKey(key.publicKey)], revokedKeyIds: [keyId]))) == .revokedSigningKey(keyId: keyId))339340        // The package was built on 2026-11-25T08:00:00Z.341        let before = Timestamp.parse("2026-11-25T07:59:59Z")!, after = Timestamp.parse("2026-11-25T08:00:01Z")!342        #expect(verify(data, PackageVerifier(trustStore: TrustStore(keys: [TrustedKey(key.publicKey, notAfter: before)])))343            == .expiredSigningKey(keyId: keyId, notAfter: before))344        #expect(verify(data, PackageVerifier(trustStore: TrustStore(keys: [TrustedKey(key.publicKey, notAfter: after)]))) == nil)345        #expect(verify(data, PackageVerifier(trustStore: TrustStore(keys: [TrustedKey(key.publicKey, notBefore: after)])))346            == .signingKeyNotYetValid(keyId: keyId, notBefore: after))347348        // Claiming another key in the header: the signature does not verify under that key.349        let otherId = Hex.decode(TrustedKey(other.publicKey).keyId)!350        #expect(verify(patched(data, at: 32, otherId), PackageVerifier(trustStore: Fixture.trust(other, key))) == .invalidSignature)351    }352353    @Test func manifestSignedByOneKeyButNamingAnother() throws {354        let (data, header, _) = try small()355        let other = Curve25519.Signing.PrivateKey()356        // `other` is trusted and signs a manifest that says it was signed by `key`.357        let manifestBytes = data.subdata(in: 64..<Int(header.signatureOffset))358        let forged = try Fixture.assemble(manifest: manifestBytes, key: other, payloadFrom: data, originalHeader: header, total: header.totalLength)359        #expect(verify(forged, PackageVerifier(trustStore: Fixture.trust(other, key)))360            == .signingKeyMismatch(header: TrustedKey(other.publicKey).keyId, manifest: TrustedKey(key.publicKey).keyId))361    }362363    // MARK: Layout attacks by a signer364365    func layoutCase(_ mutate: @escaping (inout [[String: Any]], inout [String: Any]) -> Void, fixTotal: Bool = false) throws -> PackageError? {366        let (data, _, _) = try small()367        let forged = try Fixture.resigned(data, key: key, fixTotal: fixTotal) { object in368            var components = object["components"] as! [[String: Any]]369            mutate(&components, &object)370            object["components"] = components371        }372        return verify(forged)373    }374375    @Test func overlappingOutOfFileAndMisplacedComponents() throws {376        // Layout of the fixture: map 4096+9000, search 16384+5000, routing 24576+3000, total 27576.377        #expect(try layoutCase { c, _ in c[1]["offset"] = 8192 } == .invalidLayout(.componentsOverlap(first: "map", second: "search")))378        #expect(try layoutCase { c, _ in c[1]["offset"] = 4096 } == .invalidLayout(.componentsOverlap(first: "map", second: "search")))379        #expect(try layoutCase { c, _ in c[0]["offset"] = 0 } == .invalidLayout(.componentOverlapsPreamble(component: "map")))380        #expect(try layoutCase { c, _ in c[2]["offset"] = 28672 } == .invalidLayout(.componentOutOfFile(component: "routing")))381        #expect(try layoutCase { c, _ in c[2]["offset"] = 1 << 40 } == .invalidLayout(.componentOutOfFile(component: "routing")))382        #expect(try layoutCase { c, _ in c[1]["offset"] = 16385 } == .invalidLayout(.componentMisaligned(component: "search", offset: 16385)))383        #expect(try layoutCase { c, _ in c[1]["offset"] = 20480 } == .invalidLayout(.nonCanonical(expectedOffset: 16384, foundOffset: 20480)))384        #expect(try layoutCase { c, _ in c[0]["offset"] = 8192 } == .invalidLayout(.nonCanonical(expectedOffset: 4096, foundOffset: 8192)))385        // Components must be listed in file order.386        #expect(try layoutCase { c, _ in c.swapAt(0, 1) } == .invalidLayout(.nonCanonical(expectedOffset: 4096, foundOffset: 16384)))387        #expect(try layoutCase { c, _ in c.swapAt(1, 2) } == .invalidLayout(.nonCanonical(expectedOffset: 16384, foundOffset: 24576)))388    }389390    @Test func wrongLengths() throws {391        // Longer than the real component: runs into the next one's position.392        #expect(try layoutCase { c, o in c[0]["length"] = 9001; o["installedSize"] = 17001 } == .componentChecksumMismatch(component: "map"))393        #expect(try layoutCase { c, o in c[0]["length"] = 13000; o["installedSize"] = 21000 }394            == .invalidLayout(.componentsOverlap(first: "map", second: "search")))395        // Shorter: the hash does not match (and the gap is not padding).396        #expect(try layoutCase { c, o in c[0]["length"] = 8999; o["installedSize"] = 16999 } == .componentChecksumMismatch(component: "map"))397        // Last component shorter or longer than the file.398        #expect(try layoutCase { c, o in c[2]["length"] = 2999; o["installedSize"] = 16999 }399            == .invalidLayout(.nonCanonical(expectedOffset: 27575, foundOffset: 27576)))400        #expect(try layoutCase { c, o in c[2]["length"] = 3001; o["installedSize"] = 17001 } == .invalidLayout(.componentOutOfFile(component: "routing")))401        // Declared total that does not match the header or the file.402        #expect(try layoutCase { _, o in o["downloadSize"] = 27577 } == .invalidLayout(.totalLengthMismatch(header: 27576, manifest: 27577)))403        #expect(try layoutCase({ c, o in c[2]["length"] = 3001; o["installedSize"] = 17001; o["downloadSize"] = 27577 }, fixTotal: false)404            == .invalidLayout(.totalLengthMismatch(header: 27576, manifest: 27577)))405    }406407    @Test func integerOverflowInOffsetsAndLengths() throws {408        var limits = PackageLimits()409        limits.maxComponentBytes = .max410        limits.maxTotalBytes = .max411        let (data, header, manifest) = try small()412        func check(_ edit: (inout PackageManifest) -> Void) -> PackageError? {413            var m = manifest414            edit(&m)415            return packageError { try PackageLayout.validate(header: header, manifest: m, fileSize: UInt64(data.count), limits: limits) }416        }417        #expect(check { $0.components[2].offset = UInt64.max - 4095; $0.components[2].length = 8192 } == .invalidLayout(.offsetOverflow(component: "routing")))418        #expect(check { $0.components[2].offset = UInt64.max / 4096 * 4096; $0.components[2].length = 4096 } == .invalidLayout(.offsetOverflow(component: "routing")))419        #expect(check { $0.components[0].length = UInt64.max - 4096 } != nil)420        #expect(check { $0.components[1].offset = UInt64.max } != nil)421        #expect(PackageLayout.alignUp(UInt64.max) == nil)422        #expect(PackageLayout.alignUp(UInt64.max - 4094) == nil)423        #expect(PackageLayout.alignUp(4097) == 8192)424        #expect(PackageLayout.alignUp(4096) == 4096)425        #expect(PackageLayout.alignUp(0) == 0)426        // Through the whole reader, with a signed manifest and the standard limits.427        #expect(try layoutCase { c, _ in c[2]["offset"] = UInt64.max - 4095 } != nil)428        #expect(try layoutCase { c, _ in c[2]["length"] = UInt64.max } != nil)429        #expect(try layoutCase { c, o in c[2]["length"] = UInt64.max; o["installedSize"] = UInt64.max } != nil)430    }431432    @Test func signedButInvalidManifests() throws {433        let (data, _, _) = try small()434        func forged(_ mutate: @escaping (inout [String: Any]) -> Void) throws -> PackageError? { verify(try Fixture.resigned(data, key: key, mutate: mutate)) }435        #expect(try forged { $0["regionId"] = "../../etc" } == .invalidManifest(.invalidRegionId("../../etc")))436        #expect(try forged { $0["schemaVersion"] = 2 } == .unsupportedSchemaVersion(found: 2, supported: 1))437        #expect(try forged { o in438            var c = o["components"] as! [[String: Any]]; c[0]["id"] = "../../../tmp/owned"; o["components"] = c439        } == .invalidManifest(.invalidComponentId("../../../tmp/owned")))440        #expect(try forged { o in441            var c = o["components"] as! [[String: Any]]; c[0]["id"] = "map.pmtiles"; o["components"] = c442        } == .invalidManifest(.invalidComponentId("map.pmtiles")))443        #expect(try forged { $0["signingKeyId"] = "0000000000000000" }444            == .signingKeyMismatch(header: TrustedKey(key.publicKey).keyId, manifest: "0000000000000000"))445        #expect(try forged { $0["bbox"] = ["minLat": 0, "minLon": 0, "maxLat": 0, "maxLon": 0] } == .invalidManifest(.invalidBoundingBox))446    }447448    @Test func oversizedManifestInARealFile() throws {449        let (data, _, _) = try small()450        // A signed manifest of 1 MiB + padding member, larger than the limit.451        let forged = try Fixture.resigned(data, key: key, fixTotal: true) { $0["padding"] = String(repeating: "x", count: 1 << 20) }452        #expect(packageError { _ = try PackageHeader.parse(forged) } != nil)453        guard case .manifestTooLarge = verify(forged) else { Issue.record("oversized manifest accepted"); return }454        // The same content passes with a larger limit and fails with a smaller one: the limit is what decides.455        var tight = PackageLimits(); tight.maxManifestBytes = 256456        guard case .manifestTooLarge = verify(data, PackageVerifier(trustStore: Fixture.trust(key), limits: tight)) else {457            Issue.record("limit not applied"); return458        }459    }460461    @Test func nonRegularFilesAndMissingFiles() {462        #expect(packageError { _ = try self.verifier.verify(at: self.tmp.file("missing.orixmap")) } == .io(operation: "open", code: ENOENT))463        #expect(packageError { _ = try self.verifier.verify(at: self.tmp.url) } == .io(operation: "fstat", code: EFTYPE))464        let empty = tmp.file("empty.orixmap"); try! Data().write(to: empty)465        #expect(packageError { _ = try self.verifier.verify(at: empty) } == .truncated(section: .header, needed: 64, available: 0))466    }467468    @Test func extractionNeverLeavesPartialOutputAndNeverOverwrites() throws {469        let (data, _, manifest) = try small()470        var bad = data471        bad[Int(manifest.components[2].offset)] ^= 1          // the last component is corrupted472        let url = tmp.file("bad.orixmap"); try bad.write(to: url)473        let out = tmp.file("staging-x")474        #expect(packageError { _ = try self.verifier.extract(url, into: out) } == .componentChecksumMismatch(component: "routing"))475        #expect(!FileManager.default.fileExists(atPath: out.path), "staging directory removed after a failure")476        // An existing directory is never reused.477        try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)478        let good = tmp.file("good.orixmap"); try data.write(to: good)479        #expect(packageError { _ = try self.verifier.extract(good, into: out) } == .io(operation: "mkdir", code: EEXIST))480        // Cancellation.481        #expect(packageError { _ = try self.verifier.verify(at: good, isCancelled: { true }) } == .cancelled)482    }483}484
Files main
Menu

Theme