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/CatalogTests.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 Testing91@testable import ORIXMapPackage9293final class Clock: @unchecked Sendable {94 private let lock = NSLock()95 private var current: Date96 init(_ text: String) { current = Timestamp.parse(text)! }97 var now: Date { lock.lock(); defer { lock.unlock() }; return current }98 func advance(_ seconds: TimeInterval) { lock.lock(); current += seconds; lock.unlock() }99}100101@Suite struct CatalogTests {102 let key = Curve25519.Signing.PrivateKey()103 let tmp = TempDir("catalog")104105 static let sample = """106 {107 "schema": {"major": 1, "minor": 3, "note": "a later minor"},108 "generatedAt": "2026-11-25T09:00:00Z",109 "announcement": {"en": "ignored by this client"},110 "regions": [111 {112 "id": "ca-qc-montreal",113 "names": {"en": "Greater Montréal", "fr": "Grand Montréal", "es": "Gran Montreal"},114 "bbox": {"minLat": 45.15, "minLon": -74.35, "maxLat": 45.95, "maxLon": -73.15},115 "capabilities": ["map", "search", "routing", "transit"],116 "population": 4300000,117 "latest": {118 "dataVersion": "2026.11.24", "dataTimestamp": "2026-11-24T00:00:00Z", "buildDate": "2026-11-25T08:00:00Z",119 "downloadSize": 312000000, "installedSize": 311990000,120 "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",121 "signingKeyId": "0123456789abcdef", "minAppVersion": "1.0",122 "path": "files/ca-qc-montreal/2026.11.24/ca-qc-montreal-2026.11.24.orixmap", "preambleSize": 1911,123 "deltaFrom": ["2026.11.17"]124 }125 },126 {"id": "broken-entry", "names": {"en": "No latest"}},127 {"id": "../../etc", "names": {"en": "x"}, "bbox": {"minLat": 0, "minLon": 0, "maxLat": 1, "maxLon": 1}, "capabilities": [],128 "latest": {"dataVersion": "1", "dataTimestamp": "2026-11-24T00:00:00Z", "downloadSize": 1, "installedSize": 1,129 "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "signingKeyId": "0123456789abcdef", "path": "files/x"}},130 {"id": "hostile-path", "names": {"en": "x"}, "bbox": {"minLat": 0, "minLon": 0, "maxLat": 1, "maxLon": 1}, "capabilities": [],131 "latest": {"dataVersion": "1", "dataTimestamp": "2026-11-24T00:00:00Z", "downloadSize": 1, "installedSize": 1,132 "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "signingKeyId": "0123456789abcdef",133 "path": "../../../other-site/file.orixmap"}},134 "not even an object"135 ]136 }137 """138139 @Test func forwardCompatibleDecoding() throws {140 let catalog = try Catalog.decode(Data(Self.sample.utf8))141 #expect(catalog.schema == CatalogSchema(major: 1, minor: 3))142 #expect(catalog.regions.map(\.id) == ["ca-qc-montreal"], "entries that are malformed or hostile are dropped, the others kept")143 #expect(catalog.skippedRegions == 4)144 let region = try #require(catalog.region("ca-qc-montreal"))145 #expect(region.capabilities == ["map", "search", "routing", "transit"], "unknown capabilities are preserved")146 #expect(region.latest.dataVersion == DataVersion("2026.11.24"))147 #expect(region.latest.minAppVersion == AppVersion("1"))148 #expect(region.latest.preambleSize == 1911)149 #expect(region.name(preferring: ["fr-CA", "en"]) == "Grand Montréal")150 #expect(region.name(preferring: ["de"]) == "Greater Montréal")151 #expect(catalog.generatedDate == Timestamp.parse("2026-11-25T09:00:00Z"))152 let request = DownloadRequest(region: region)153 #expect(request.path == CatalogRelease.canonicalPath(regionId: "ca-qc-montreal", dataVersion: DataVersion("2026.11.24")!))154 #expect(request.size == 312_000_000)155 }156157 @Test func unknownMajorAndGarbageAreTypedErrors() {158 #expect(throws: CatalogError.unsupportedSchema(major: 2, supported: 1)) {159 try Catalog.decode(Data(#"{"schema":{"major":2,"minor":0},"entirely":"different"}"#.utf8))160 }161 #expect(throws: CatalogError.unsupportedSchema(major: 0, supported: 1)) {162 try Catalog.decode(Data(#"{"schema":{"major":0,"minor":9},"generatedAt":"x","regions":[]}"#.utf8))163 }164 #expect(throws: CatalogError.notDecodable(detail: "missing schema")) { try Catalog.decode(Data("{}".utf8)) }165 #expect(throws: CatalogError.notDecodable(detail: "missing schema")) { try Catalog.decode(Data("<html>captive portal</html>".utf8)) }166 #expect(throws: CatalogError.notDecodable(detail: "missing key regions")) {167 try Catalog.decode(Data(#"{"schema":{"major":1,"minor":0},"generatedAt":"2026-11-25T09:00:00Z"}"#.utf8))168 }169 #expect(throws: CatalogError.tooLarge(limit: 8 << 20)) { try Catalog.decode(Data(count: (8 << 20) + 1)) }170 #expect(throws: CatalogError.notDecodable(detail: "not UTF-8")) { try Catalog.decode(Data([0xFF, 0xFE, 0x00])) }171 }172173 @Test func safeRelativePaths() {174 for good in ["catalog.json", "files/ca-qc-montreal/2026.11.24/ca-qc-montreal-2026.11.24.orixmap", "a/b_c/d-e.f"] {175 #expect(HTTPSupport.isSafeRelativePath(good), "\(good)")176 }177 for bad in ["", "/etc/passwd", "../x", "a/../b", "a/./b", "a//b", "a/", "https://evil.example/x", "//evil.example/x", "a?b=c", "a#b", "a b", "a%2e%2e/b",178 "a\\b", "é", String(repeating: "a", count: 513)] {179 #expect(!HTTPSupport.isSafeRelativePath(bad), "\(bad)")180 #expect(HTTPSupport.resolve(bad, against: URL(string: "https://www.orixlab.dev/maps/v1/")!) == nil)181 }182 #expect(HTTPSupport.resolve("regions/x.json", against: URL(string: "https://www.orixlab.dev/maps/v1")!)?.absoluteString183 == "https://www.orixlab.dev/maps/v1/regions/x.json")184 }185186 @Test func retryAfterAndContentRangeParsing() {187 let now = Date(timeIntervalSince1970: 1_795_000_000)188 #expect(HTTPSupport.retryAfter("17", now: now) == 17)189 #expect(HTTPSupport.retryAfter(" 0 ", now: now) == 0)190 #expect(HTTPSupport.retryAfter(nil, now: now) == nil)191 #expect(HTTPSupport.retryAfter("soon", now: now) == nil)192 #expect(HTTPSupport.retryAfter("-5", now: now) == nil)193 #expect(HTTPSupport.retryAfter("Wed, 18 Nov 2026 11:07:40 GMT", now: now) == 60)194 #expect(HTTPSupport.retryAfter("Wed, 18 Nov 2026 08:00:00 GMT", now: now) == 0)195 #expect(HTTPSupport.contentRange("bytes 100-199/1000").map { [$0.first, $0.last, $0.total] } == [100, 199, 1000])196 for bad in [nil, "", "bytes */1000", "bytes 5-4/10", "bytes 0-10/10", "items 0-1/2", "bytes 0-1", "bytes -1-2/3", "bytes 0-18446744073709551616/3"] {197 #expect(HTTPSupport.contentRange(bad) == nil, "\(bad ?? "nil")")198 }199 #expect(HTTPSupport.strongETag("\"abc\"") == "\"abc\"")200 #expect(HTTPSupport.strongETag("W/\"abc\"") == nil)201 #expect(HTTPSupport.strongETag(nil) == nil)202 }203204 // MARK: Client205206 func makeDistribution() throws -> (TestDistribution, CatalogRegion) {207 let distribution = TestDistribution()208 let p = try Fixture.makePackage(in: tmp.url, key: key)209 let region = try distribution.publish(p.url, verifier: PackageVerifier(trustStore: Fixture.trust(key)))210 try distribution.publishCatalog([region])211 return (distribution, region)212 }213214 @Test func fetchCacheRevalidateAndOfflineUse() async throws {215 let (distribution, region) = try makeDistribution()216 let transport = FakeTransport(logic: distribution.logic)217 let clock = Clock("2026-11-25T10:00:00Z")218 let cache = tmp.file("cache")219 let client = CatalogClient(baseURL: transport.base, transport: transport, cacheDirectory: cache, now: { clock.now })220221 let first = try await client.catalog()222 #expect(first.origin == .network)223 #expect(first.document.regions == [region])224 #expect(first.fetchedAt == clock.now)225 #expect(!first.isStale)226227 // Within max-age: no request at all.228 clock.advance(120)229 #expect(try await client.catalog().origin == .cache)230 #expect(distribution.logic.requests.count == 1)231232 // After max-age: conditional request, 304, nothing transferred.233 clock.advance(400)234 let revalidated = try await client.catalog()235 #expect(revalidated.origin == .revalidated)236 #expect(revalidated.fetchedAt == first.fetchedAt)237 #expect(revalidated.validatedAt == clock.now)238 #expect(distribution.logic.requests.count == 2)239 #expect(distribution.logic.requests[1].headers["if-none-match"] == "\"\(sha256Hex(try Catalog(generatedAt: "2026-11-25T09:00:00Z", regions: [region]).encoded()))\"")240241 // Offline: the cached catalog is returned, marked stale, with the date it was fetched.242 clock.advance(86_400)243 distribution.logic.fail("catalog.json", .offline)244 let stale = try await client.catalog()245 #expect(stale.origin == .staleCache(reason: .offline))246 #expect(stale.isStale)247 #expect(stale.fetchedAt == first.fetchedAt)248 #expect(stale.document == first.document)249250 // A new client (application relaunch) starts from the disk cache.251 let relaunched = CatalogClient(baseURL: transport.base, transport: transport, cacheDirectory: cache, now: { clock.now })252 #expect(try await relaunched.catalog(refresh: .cacheOnly).document == first.document)253 distribution.logic.fail("catalog.json", .status(503, [:]))254 #expect(try await relaunched.catalog().origin == .staleCache(reason: .httpStatus(503)))255 distribution.logic.fail("catalog.json", .status(429, ["Retry-After": "42"]))256 #expect(try await relaunched.catalog().origin == .staleCache(reason: .rateLimited(retryAfter: 42)))257258 // A changed catalog replaces the cache.259 var newer = region260 newer.latest.dataVersion = DataVersion("2026.12.1")!261 try distribution.publishCatalog([newer], generatedAt: "2026-11-26T12:00:00Z")262 let updated = try await relaunched.catalog(refresh: .always)263 #expect(updated.origin == .network)264 #expect(updated.document.regions[0].latest.dataVersion == DataVersion("2026.12.1"))265266 // Another base URL never reads this cache.267 let other = CatalogClient(baseURL: URL(string: "https://staging.test/maps/v1/")!, transport: transport, cacheDirectory: cache, now: { clock.now })268 await #expect(throws: CatalogError.offline) { try await other.catalog(refresh: .cacheOnly) }269 }270271 @Test func errorsWithoutCacheAreTyped() async throws {272 let (distribution, _) = try makeDistribution()273 let transport = FakeTransport(logic: distribution.logic)274 let client = CatalogClient(baseURL: transport.base, transport: transport, cacheDirectory: tmp.file("cache-empty"))275 await #expect(throws: CatalogError.offline) { try await client.catalog(refresh: .cacheOnly) }276 distribution.logic.fail("catalog.json", .offline)277 await #expect(throws: CatalogError.offline) { try await client.catalog() }278 distribution.logic.fail("catalog.json", .status(429, ["Retry-After": "30"]))279 await #expect(throws: CatalogError.rateLimited(retryAfter: 30)) { try await client.catalog() }280 distribution.logic.fail("catalog.json", .status(500, [:]))281 await #expect(throws: CatalogError.httpStatus(500)) { try await client.catalog() }282 distribution.logic.fail("catalog.json", .truncate(afterBytes: 20))283 await #expect(throws: CatalogError.network(.connectionLost)) { try await client.catalog() }284 distribution.logic.put("catalog.json", Data(#"{"schema":{"major":9,"minor":0}}"#.utf8))285 await #expect(throws: CatalogError.unsupportedSchema(major: 9, supported: 1)) { try await client.catalog() }286 distribution.logic.put("catalog.json", Data(count: (8 << 20) + 1))287 await #expect(throws: CatalogError.tooLarge(limit: 8 << 20)) { try await client.catalog() }288 distribution.logic.put("catalog.json", Data("<html>".utf8))289 await #expect(throws: CatalogError.notDecodable(detail: "missing schema")) { try await client.catalog() }290 #expect(!FileManager.default.fileExists(atPath: tmp.file("cache-empty/catalog.json").path), "nothing invalid is cached")291 }292293 @Test func replayedOlderCatalogDoesNotReplaceANewerOne() async throws {294 let (distribution, region) = try makeDistribution()295 let transport = FakeTransport(logic: distribution.logic)296 let client = CatalogClient(baseURL: transport.base, transport: transport, cacheDirectory: tmp.file("cache"))297 var newer = region298 newer.latest.dataVersion = DataVersion("2026.12.1")!299 try distribution.publishCatalog([newer], generatedAt: "2026-12-02T00:00:00Z")300 #expect(try await client.catalog(refresh: .always).document.regions[0].latest.dataVersion == DataVersion("2026.12.1"))301302 // The server (or something in between) now serves the catalog of the week before.303 try distribution.publishCatalog([region], generatedAt: "2026-11-25T09:00:00Z")304 let snapshot = try await client.catalog(refresh: .always)305 #expect(snapshot.origin == .staleCache(reason: .olderThanCached(served: "2026-11-25T09:00:00Z", cached: "2026-12-02T00:00:00Z")))306 #expect(snapshot.document.regions[0].latest.dataVersion == DataVersion("2026.12.1"))307 // A legitimate publisher rollback regenerates the catalog with a new date: it is accepted.308 try distribution.publishCatalog([region], generatedAt: "2026-12-03T00:00:00Z")309 #expect(try await client.catalog(refresh: .always).document.regions[0].latest.dataVersion == DataVersion("2026.11.24"))310 }311312 @Test func regionDetailAndVersions() async throws {313 let (distribution, region) = try makeDistribution()314 let transport = FakeTransport(logic: distribution.logic)315 let client = CatalogClient(baseURL: transport.base, transport: transport, cacheDirectory: tmp.file("cache"))316 let detail = try await client.regionDetail(id: "ca-qc-montreal").document317 #expect(detail.region == region)318 #expect(detail.licences == Fixture.licences)319 #expect(detail.components.map(\.id) == ["map", "search", "routing"])320 #expect(detail.mapZoom == ZoomRange(minZoom: 0, maxZoom: 14))321 let versions = try await client.versions(id: "ca-qc-montreal").document322 #expect(versions.latest == DataVersion("2026.11.24"))323 #expect(versions.versions == [region.latest])324 #expect(distribution.logic.requests.map(\.path) == ["regions/ca-qc-montreal.json", "regions/ca-qc-montreal/versions.json"])325326 await #expect(throws: CatalogError.invalidRegionId("../catalog")) { try await client.regionDetail(id: "../catalog") }327 await #expect(throws: CatalogError.invalidRegionId("a/b")) { try await client.versions(id: "a/b") }328 await #expect(throws: CatalogError.httpStatus(404)) { try await client.regionDetail(id: "atlantis") }329 // A document about another region than the one asked for is refused.330 distribution.logic.put("regions/ca-on-ottawa.json", try CatalogRegionDetail(manifest: try PackageManifest.decode(331 try JSONEncoder().encode(try PackageVerifier(trustStore: Fixture.trust(key)).verify(at: Fixture.makePackage(in: tmp.url, key: key).url).manifest)),332 release: region.latest, generatedAt: "2026-11-25T09:00:00Z").encoded())333 await #expect(throws: CatalogError.wrongRegion(expected: "ca-on-ottawa", found: "ca-qc-montreal")) { try await client.regionDetail(id: "ca-on-ottawa") }334 }335336 @Test func requestsCarryNothingAboutTheUser() async throws {337 let (distribution, _) = try makeDistribution()338 let transport = FakeTransport(logic: distribution.logic)339 let client = CatalogClient(baseURL: transport.base, transport: transport, cacheDirectory: tmp.file("cache"))340 _ = try await client.catalog()341 _ = try await client.catalog(refresh: .always)342 _ = try await client.regionDetail(id: "ca-qc-montreal")343 _ = try await client.versions(id: "ca-qc-montreal")344 let allowed: Set<String> = ["accept", "if-none-match"]345 for request in distribution.logic.requests {346 #expect(Set(request.headers.keys).isSubset(of: allowed), "unexpected headers \(request.headers.keys)")347 #expect(!request.path.contains("?") && !request.path.contains("#"), "no query string, ever")348 }349 }350}351