Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Packages/ORIXMapPackage/Tests/ORIXMapPackageTests/ManifestTests.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 ManifestTests {95 let key = Curve25519.Signing.PrivateKey()9697 func sample(_ edit: (inout PackageManifest) -> Void = { _ in }) -> PackageManifest {98 let sha = String(repeating: "ab", count: 32)99 var m = PackageManifest(100 regionId: "ca-qc-montreal", names: ["en": "Greater Montréal", "fr": "Grand Montréal"], bbox: Fixture.montrealBox,101 dataVersion: DataVersion("2026.11.24")!, dataTimestamp: "2026-11-24T00:00:00Z", buildDate: "2026-11-25T08:00:00Z",102 mapZoom: ZoomRange(minZoom: 0, maxZoom: 14), languages: ["en", "fr"], licences: Fixture.licences,103 components: [104 ComponentEntry(id: .map, offset: 4096, length: 5000, sha256: sha, mediaType: "application/vnd.pmtiles", formatVersion: 3),105 ComponentEntry(id: .search, offset: 12288, length: 100, sha256: sha, mediaType: "application/vnd.sqlite3", formatVersion: 1),106 ],107 downloadSize: 12388, signingKeyId: TrustedKey(key.publicKey).keyId, builder: ["orix-package": "1.0.0"], minAppVersion: AppVersion("1.0"))108 edit(&m)109 return m110 }111112 func problem(_ edit: (inout PackageManifest) -> Void) -> PackageError? {113 packageError { try self.sample(edit).validate() }114 }115116 @Test func roundTrip() throws {117 let m = sample()118 let bytes = try m.encoded()119 let decoded = try PackageManifest.decode(bytes)120 #expect(decoded == m)121 #expect(try decoded.encoded() == bytes, "encoding is deterministic")122 #expect(decoded.capabilities == ["map", "search"])123 #expect(decoded.installedSize == 5100)124 #expect(decoded.name(preferring: ["fr-CA"]) == "Grand Montréal")125 #expect(decoded.dataDate == Date(timeIntervalSince1970: 1_795_478_400))126 }127128 @Test func unknownMembersAreIgnoredAndUnknownComponentsAccepted() throws {129 var object = try JSONSerialization.jsonObject(with: sample().encoded()) as! [String: Any]130 object["futureField"] = ["x": 1]131 var components = object["components"] as! [[String: Any]]132 components[0]["futureComponentField"] = true133 components.append(["id": "transit", "offset": 16384, "length": 10, "sha256": String(repeating: "0", count: 64),134 "mediaType": "application/x-future", "formatVersion": 1])135 object["components"] = components136 object["installedSize"] = 5110137 object["capabilities"] = ["map", "search", "transit"]138 let decoded = try PackageManifest.decode(JSONSerialization.data(withJSONObject: object))139 #expect(decoded.components.count == 3)140 #expect(decoded.components[2].id.isKnown == false)141 #expect(decoded.components[2].id.installedFileName == nil)142 }143144 @Test func newerSchemaVersionIsRefusedBeforeAnythingElse() throws {145 // A future schema may change the shape of every other member: only format and schemaVersion are read.146 let future = Data(#"{"format":"orixmap","schemaVersion":2,"regionId":42}"#.utf8)147 #expect(throws: PackageError.unsupportedSchemaVersion(found: 2, supported: 1)) { try PackageManifest.decode(future) }148 #expect(throws: PackageError.unsupportedSchemaVersion(found: 0, supported: 1)) {149 try PackageManifest.decode(Data(#"{"format":"orixmap","schemaVersion":0}"#.utf8))150 }151 #expect(throws: PackageError.invalidManifest(.wrongFormatName("zip"))) {152 try PackageManifest.decode(Data(#"{"format":"zip","schemaVersion":1}"#.utf8))153 }154 }155156 @Test func undecodableBytes() throws {157 #expect(throws: PackageError.emptyManifest) { try PackageManifest.decode(Data()) }158 for text in ["", " ", "[]", "null", "{", "{\"format\":\"orixmap\"}", "{\"format\":\"orixmap\",\"schemaVersion\":1}", "\u{FEFF}{}"] where !text.isEmpty {159 guard case .manifestNotDecodable = packageError({ _ = try PackageManifest.decode(Data(text.utf8)) }) else {160 Issue.record("expected manifestNotDecodable for \(text)"); continue161 }162 }163 // UTF-16 JSON is accepted by JSONDecoder but not by the format.164 let utf16 = String(decoding: try sample().encoded(), as: UTF8.self).data(using: .utf16)!165 guard case .manifestNotDecodable = packageError({ _ = try PackageManifest.decode(utf16) }) else {166 Issue.record("UTF-16 manifest accepted"); return167 }168 // Deep nesting must produce an error, not a stack overflow.169 let deep = Data((String(repeating: "[", count: 100_000)).utf8)170 #expect(packageError { _ = try PackageManifest.decode(Data(#"{"format":"orixmap","schemaVersion":1,"names":"#.utf8) + deep) } != nil)171 }172173 @Test func oversizedManifest() {174 var limits = PackageLimits()175 limits.maxManifestBytes = 100176 #expect(throws: PackageError.manifestTooLarge(size: 101, limit: 100)) {177 try PackageManifest.decode(Data(repeating: 0x20, count: 101), limits: limits)178 }179 }180181 @Test(arguments: ["", "../etc", "Montreal", "ca_qc", "ca/qc", "ca qc", "é", "a\u{0}b", ".", "..", String(repeating: "a", count: 65), "ca-qc\n"])182 func hostileRegionIds(_ id: String) {183 #expect(problem { $0.regionId = id } == .invalidManifest(.invalidRegionId(String(id.prefix(80)))))184 }185186 @Test(arguments: ["", "../map", "map/../../x", "/etc/passwd", "map.pmtiles", "MAP", "ma p", "map\u{0}", "..", "~", "a\\b",187 String(repeating: "m", count: 33), "map%2f", "map"])188 func hostileComponentIds(_ id: String) {189 #expect(problem { $0.components[1].id = ComponentID(rawValue: id) } == .invalidManifest(.invalidComponentId(String(id.prefix(80)))))190 // Whatever the identifier, the installed file name comes from the fixed table or does not exist.191 #expect(ComponentID(rawValue: id).installedFileName == nil)192 }193194 @Test func componentRules() {195 #expect(problem { $0.components[1].id = .map } == .invalidManifest(.duplicateComponentId("map")))196 #expect(problem { $0.components = [] } == .invalidManifest(.noKnownComponent))197 #expect(problem { $0.components[0].id = ComponentID(rawValue: "transit"); $0.components[1].id = ComponentID(rawValue: "other") }198 == .invalidManifest(.noKnownComponent))199 #expect(problem { $0.components[0].length = 0 } == .invalidManifest(.emptyComponent(id: "map")))200 #expect(problem { $0.components[0].length = (32 << 30) + 1 } == .invalidManifest(.componentTooLarge(id: "map", length: (32 << 30) + 1, limit: 32 << 30)))201 #expect(problem { $0.components[0].sha256 = "xyz" } == .invalidManifest(.invalidSHA256(component: "map")))202 #expect(problem { $0.components[0].sha256 = String(repeating: "AB", count: 32) } == .invalidManifest(.invalidSHA256(component: "map")))203 #expect(problem { $0.components[0].formatVersion = 0 } == .invalidManifest(.invalidComponentFormatVersion(id: "map")))204 #expect(problem { $0.components[0].mediaType = "" } == .invalidManifest(.emptyString(field: "components.map.mediaType")))205 #expect(problem { $0.installedSize = 1 } == .invalidManifest(.installedSizeMismatch(declared: 1, computed: 5100)))206 #expect(problem { m in207 m.components = (0..<17).map { ComponentEntry(id: ComponentID(rawValue: "c\($0)"), offset: 0, length: 1, sha256: m.components[0].sha256, mediaType: "x", formatVersion: 1) }208 } == .invalidManifest(.tooManyComponents(count: 17, limit: 16)))209 // The sum of the lengths must not wrap around.210 var limits = PackageLimits(); limits.maxComponentBytes = .max211 let wrapped = sample { $0.components[0].length = .max; $0.components[1].length = 2 }212 #expect(packageError { try wrapped.validate(limits: limits) } == .invalidLayout(.offsetOverflow(component: "search")))213 }214215 @Test func capabilitiesMustMatchComponents() {216 #expect(problem { $0.capabilities = ["map"] } == .invalidManifest(.capabilitiesMismatch(declared: ["map"], derived: ["map", "search"])))217 #expect(problem { $0.capabilities = ["map", "search", "routing"] } != nil)218 #expect(problem { $0.capabilities = ["map", "search", "map"] } != nil)219 #expect(problem { $0.capabilities = ["map", "search", "future-thing"] } == nil, "unknown capabilities are tolerated")220 }221222 @Test func boundingBoxAndZoom() {223 #expect(problem { $0.bbox = BoundingBox(minLat: 46, minLon: -74, maxLat: 45, maxLon: -73) } == .invalidManifest(.invalidBoundingBox))224 #expect(problem { $0.bbox = BoundingBox(minLat: 45, minLon: -74, maxLat: 91, maxLon: -73) } == .invalidManifest(.invalidBoundingBox))225 #expect(problem { $0.bbox = BoundingBox(minLat: 45, minLon: -181, maxLat: 46, maxLon: -73) } == .invalidManifest(.invalidBoundingBox))226 #expect(problem { $0.bbox = BoundingBox(minLat: .nan, minLon: -74, maxLat: 46, maxLon: -73) } == .invalidManifest(.invalidBoundingBox))227 #expect(problem { $0.bbox = BoundingBox(minLat: 45, minLon: -74, maxLat: 45, maxLon: -73) } == .invalidManifest(.invalidBoundingBox))228 #expect(problem { $0.bbox = BoundingBox(minLat: -20, minLon: 170, maxLat: -10, maxLon: -170) } == nil, "antimeridian boxes are valid")229 #expect(problem { $0.mapZoom = nil } == .invalidManifest(.missingMapZoom))230 #expect(problem { $0.mapZoom = ZoomRange(minZoom: 5, maxZoom: 4) } == .invalidManifest(.invalidZoomRange(min: 5, max: 4)))231 #expect(problem { $0.mapZoom = ZoomRange(minZoom: -1, maxZoom: 4) } == .invalidManifest(.invalidZoomRange(min: -1, max: 4)))232 #expect(problem { $0.mapZoom = ZoomRange(minZoom: 0, maxZoom: 25) } == .invalidManifest(.invalidZoomRange(min: 0, max: 25)))233 }234235 @Test func stringsDatesLicences() {236 #expect(problem { $0.names["fr"] = nil } == .invalidManifest(.missingName(language: "fr")))237 #expect(problem { $0.names["en"] = String(repeating: "x", count: 513) } == .invalidManifest(.stringTooLong(field: "names.en", length: 513, limit: 512)))238 #expect(problem { $0.names["en"] = "a\u{7}b" } != nil)239 #expect(problem { $0.names["EN_us"] = "x" } == .invalidManifest(.invalidLanguageTag("EN_us")))240 #expect(problem { $0.languages = ["en", "../fr"] } == .invalidManifest(.invalidLanguageTag("../fr")))241 #expect(problem { $0.languages = Array(repeating: "en", count: 33) } == .invalidManifest(.tooManyEntries(field: "languages", count: 33, limit: 32)))242 #expect(problem { $0.dataTimestamp = "2026-11-24" } == .invalidManifest(.invalidDate(field: "dataTimestamp", value: "2026-11-24")))243 #expect(problem { $0.buildDate = "2026-02-30T00:00:00Z" } == .invalidManifest(.invalidDate(field: "buildDate", value: "2026-02-30T00:00:00Z")))244 #expect(problem { $0.licences = [] } == .invalidManifest(.noLicence))245 #expect(problem { $0.licences[0].url = "javascript:alert(1)" } == .invalidManifest(.invalidURL(field: "licences[0].url")))246 #expect(problem { $0.licences[0].attribution = String(repeating: "x", count: 4097) }247 == .invalidManifest(.stringTooLong(field: "licences[0].attribution", length: 4097, limit: 4096)))248 #expect(problem { $0.licences = Array(repeating: $0.licences[0], count: 33) } == .invalidManifest(.tooManyEntries(field: "licences", count: 33, limit: 32)))249 #expect(problem { $0.signingKeyId = "XYZ" } == .invalidManifest(.invalidKeyId("XYZ")))250 #expect(problem { $0.builder = Dictionary(uniqueKeysWithValues: (0..<33).map { ("t\($0)", "1") }) }251 == .invalidManifest(.tooManyEntries(field: "builder", count: 33, limit: 32)))252 #expect(problem { $0.downloadSize = (64 << 30) + 1 } == .invalidLayout(.totalTooLarge(length: (64 << 30) + 1, limit: 64 << 30)))253 }254255 @Test func invalidVersionsAreNotDecodable() throws {256 for (key, value) in [("dataVersion", "2026-11-24"), ("dataVersion", "../1"), ("dataVersion", ""), ("minAppVersion", "1.0-beta")] {257 var object = try JSONSerialization.jsonObject(with: sample().encoded()) as! [String: Any]258 object[key] = value259 let data = try JSONSerialization.data(withJSONObject: object)260 guard case .manifestNotDecodable = packageError({ _ = try PackageManifest.decode(data) }) else {261 Issue.record("\(key)=\(value) accepted"); continue262 }263 }264 // Negative and out-of-range integers are decoding errors, not wrapped values.265 for value in ["-1", "18446744073709551616", "1.5", "\"12\""] {266 let text = String(decoding: try sample().encoded(), as: UTF8.self).replacingOccurrences(of: "\"offset\":4096", with: "\"offset\":\(value)")267 guard case .manifestNotDecodable = packageError({ _ = try PackageManifest.decode(Data(text.utf8)) }) else {268 Issue.record("offset \(value) accepted"); continue269 }270 }271 }272273 @Test func dottedVersions() {274 #expect(DataVersion("2026.11.24")! > DataVersion("2026.11.9")!)275 #expect(DataVersion("2026.11.24")! > DataVersion("2026.2.28")!)276 #expect(DataVersion("10")! > DataVersion("9")!)277 #expect(DataVersion("1.0")! == DataVersion("1")!)278 #expect(DataVersion("2026.11.04")! == DataVersion("2026.11.4")!)279 #expect(DataVersion("1.0.1")! > DataVersion("1")!)280 for bad in ["", ".", "1.", ".1", "1..2", "1.2.3.4.5", "v1", "1,2", "-1", "1234567890", " 1", "1 ", "١"] {281 #expect(DataVersion(bad) == nil, "\(bad)")282 }283 }284285 @Test func timestamps() {286 #expect(Timestamp.parse("1970-01-01T00:00:00Z") == Date(timeIntervalSince1970: 0))287 #expect(Timestamp.parse("2024-02-29T23:59:59Z") == Date(timeIntervalSince1970: 1_709_251_199))288 #expect(Timestamp.format(Date(timeIntervalSince1970: 1_709_251_199)) == "2024-02-29T23:59:59Z")289 for text in ["2026-11-24T00:00:00Z", "2000-01-01T12:34:56Z", "2099-12-31T23:59:59Z"] {290 #expect(Timestamp.format(Timestamp.parse(text)!) == text)291 }292 for bad in ["2026-11-24", "2026-11-24T00:00:00", "2026-11-24T00:00:00+00:00", "2026-13-01T00:00:00Z", "2025-02-29T00:00:00Z",293 "2026-11-24T24:00:00Z", "2026-11-24t00:00:00Z", "1969-12-31T23:59:59Z", "2026-11-24T00:00:00Z"] {294 #expect(Timestamp.parse(bad) == nil, "\(bad)")295 }296 }297298 @Test func trustStoreCoding() throws {299 let trusted = TrustedKey(key.publicKey, label: "dev", notAfter: Timestamp.parse("2027-01-01T00:00:00Z"))300 #expect(trusted.keyId.count == 16)301 #expect(trusted.keyId == String(sha256Hex(key.publicKey.rawRepresentation).prefix(16)))302 let store = TrustStore(keys: [trusted], revokedKeyIds: ["0011223344556677"])303 let decoded = try JSONDecoder().decode(TrustStore.self, from: JSONEncoder().encode(store))304 #expect(decoded == store)305 // A key identifier that does not match the key is refused; so is a key of the wrong size.306 let b64 = key.publicKey.rawRepresentation.base64EncodedString()307 #expect(throws: (any Error).self) {308 try JSONDecoder().decode(TrustStore.self, from: Data(#"{"keys":[{"keyId":"0000000000000000","publicKey":"\#(b64)"}]}"#.utf8))309 }310 #expect(throws: (any Error).self) { try JSONDecoder().decode(TrustStore.self, from: Data(#"{"keys":[{"publicKey":"AAAA"}]}"#.utf8)) }311 #expect(TrustedKey(publicKey: Data(count: 31)) == nil)312 let minimal = try JSONDecoder().decode(TrustStore.self, from: Data(#"{"keys":[{"publicKey":"\#(b64)"}]}"#.utf8))313 #expect(minimal.keys[0].keyId == trusted.keyId)314 }315}316