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/DownloadTests.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 ORIXMapPackage9293/// One store, one distribution with a published package, one manager on the in-process transport.94struct DownloadHarness {95 let key = Curve25519.Signing.PrivateKey()96 let tmp = TempDir("download")97 let distribution = TestDistribution()98 let probe = SpaceProbe(nil)99 var trust: TrustStore { Fixture.trust(key) }100 var logic: ServerLogic { distribution.logic }101 var root: URL { tmp.file("root") }102103 func publish(_ version: String = "2026.11.24", region: String = "ca-qc-montreal", seed: UInt64 = 1,104 sizes: [(ComponentID, Int)] = [(.map, 900_000), (.search, 300_000), (.routing, 200_000)], minApp: String? = nil,105 signedBy signer: Curve25519.Signing.PrivateKey? = nil) throws -> (region: CatalogRegion, request: DownloadRequest, data: Data) {106 let p = try Fixture.makePackage(in: tmp.url, regionId: region, version: version, sizes: sizes, minApp: minApp, seed: seed, key: signer ?? key)107 let verifier = PackageVerifier(trustStore: Fixture.trust(signer ?? key))108 let entry = try distribution.publish(p.url, verifier: verifier)109 return (entry, DownloadRequest(region: entry), try Data(contentsOf: p.url))110 }111112 func store() throws -> RegionStore {113 let probe = self.probe114 return try RegionStore.open(root, trust: trust) { $0.freeSpace = { _ in probe.free }; $0.spaceMargin = 1000 }115 }116117 func manager(_ store: RegionStore, transport: (any HTTPTransport)? = nil, base: URL? = nil, maxAttempts: Int = 4) -> (DownloadManager, FakeTransport) {118 let fake = FakeTransport(logic: logic)119 var configuration = DownloadManager.Configuration()120 configuration.baseURL = base ?? fake.base121 configuration.maxAttempts = maxAttempts122 configuration.retryDelay = { _ in 0 }123 configuration.sleep = { _ in }124 configuration.progressInterval = 0125 return (DownloadManager(store: store, transport: transport ?? fake, configuration: configuration), fake)126 }127128 func partials() -> [String] {129 ((try? FileManager.default.contentsOfDirectory(atPath: root.appendingPathComponent("staging/downloads").path)) ?? []).sorted()130 }131}132133func downloadError(_ body: () async throws -> Void) async -> DownloadError? {134 do { try await body(); return nil } catch let e as DownloadError { return e } catch { return nil }135}136137/// Collects the events of a manager until the stream is dropped.138actor EventLog {139 private(set) var events: [DownloadEvent] = []140 func append(_ e: DownloadEvent) { events.append(e) }141 var states: [DownloadState] { events.map(\.state) }142}143144@Suite struct DownloadTests {145 let h = DownloadHarness()146147 @Test func downloadVerifyInstall() async throws {148 let published = try h.publish()149 let store = try h.store()150 let (manager, _) = h.manager(store)151 let log = EventLog()152 let stream = await manager.events()153 let collector = Task { for await e in stream { await log.append(e); if e.state.isFinal { break } } }154155 let region = try await manager.download(published.request)156 await collector.value157 #expect(region.dataVersion == DataVersion("2026.11.24"))158 #expect(await store.regions() == [region])159 try await store.verifyInstalled(regionId: "ca-qc-montreal")160 #expect(h.partials().isEmpty, "the partial file and its sidecar are consumed")161162 // Progress: monotonic, ends at the total, then verification, installation, completion.163 let states = await log.states164 var last: UInt64 = 0165 var sawVerifying = false, sawFull = false166 for state in states {167 switch state {168 case .downloading(let p):169 #expect(p.receivedBytes >= last); last = p.receivedBytes170 #expect(p.totalBytes == published.request.size)171 #expect(!sawVerifying)172 if p.receivedBytes == p.totalBytes { sawFull = true; #expect(p.fraction == 1) }173 case .verifying: sawVerifying = true174 default: break175 }176 }177 #expect(sawFull && sawVerifying)178 #expect(states.last == .completed(region))179 #expect(await manager.state(regionId: "ca-qc-montreal") == .completed(region))180181 // One request, no Range, nothing about the user.182 let requests = h.logic.requests183 #expect(requests.count == 1)184 #expect(requests[0].headers == ["accept-encoding": "identity"])185 #expect(requests[0].path == "files/ca-qc-montreal/2026.11.24/ca-qc-montreal-2026.11.24.orixmap")186 }187188 @Test func interruptedTransferResumesWithRangeAndIfRange() async throws {189 let published = try h.publish()190 let path = published.request.path191 let etag = "\"\(sha256Hex(published.data))\""192 // Three connection losses in a row, each after some progress.193 h.logic.fail(path, .truncate(afterBytes: 300_000), .truncate(afterBytes: 250_000), .truncate(afterBytes: 1))194 let store = try h.store()195 let (manager, _) = h.manager(store, maxAttempts: 2)196 let region = try await manager.download(published.request)197 try await store.verifyInstalled(regionId: region.id)198199 let requests = h.logic.requests(for: path)200 #expect(requests.count == 4)201 #expect(requests[0].headers["range"] == nil)202 #expect(requests[1].headers["range"] == "bytes=300000-")203 #expect(requests[1].headers["if-range"] == etag)204 #expect(requests[2].headers["range"] == "bytes=550000-")205 #expect(requests[3].headers["range"] == "bytes=550001-")206 #expect(h.logic.bodyBytesServed == published.data.count, "no byte was transferred twice")207 }208209 @Test func truncatedBodyWithoutProgressEndsAsInterruptedAndKeepsThePartialFile() async throws {210 let published = try h.publish()211 let path = published.request.path212 h.logic.fail(path, .truncate(afterBytes: 100_000), .truncate(afterBytes: 0), .truncate(afterBytes: 0))213 let store = try h.store()214 let (manager, _) = h.manager(store, maxAttempts: 3)215 #expect(await downloadError { try await manager.download(published.request) } == .network(.connectionLost))216 #expect(await manager.state(regionId: "ca-qc-montreal") == .failed(.network(.connectionLost)))217 #expect(h.partials() == ["ca-qc-montreal-2026.11.24.download.json", "ca-qc-montreal-2026.11.24.orixmap.part"])218 #expect(manager.pendingDownloads() == [PendingDownload(request: published.request, receivedBytes: 100_000)])219 #expect(await store.regions().isEmpty)220221 // A body that ends early without a transport error (a proxy that closes cleanly) is detected by the byte count.222 let quiet = QuietTruncation(inner: FakeTransport(logic: h.logic))223 let (second, _) = h.manager(store, transport: quiet, maxAttempts: 1)224 h.logic.fail(path, .truncate(afterBytes: 50_000))225 #expect(await downloadError { try await second.download(published.request) } == .interrupted(received: 150_000, expected: published.request.size))226227 // The next attempt finishes the job from where it stopped.228 try await second.resume(regionId: "ca-qc-montreal")229 let result = try #require(await second.result(regionId: "ca-qc-montreal"))230 #expect(try result.get().dataVersion == DataVersion("2026.11.24"))231 #expect(h.logic.requests(for: path).last?.headers["range"] == "bytes=150000-")232 }233234 @Test func pauseThenResume() async throws {235 let published = try h.publish()236 let path = published.request.path237 h.logic.fail(path, .stall(afterBytes: 400_000))238 let store = try h.store()239 let (manager, _) = h.manager(store)240 let stream = await manager.events()241 await manager.start(published.request)242 await manager.start(published.request) // a second start of the same region is ignored243 for await event in stream {244 if case .downloading(let p) = event.state, p.receivedBytes >= 400_000 { break }245 }246 await manager.pause(regionId: "ca-qc-montreal")247 let paused = await manager.result(regionId: "ca-qc-montreal") ?? .failure(.paused)248 #expect(paused == .failure(.paused))249 #expect(await manager.state(regionId: "ca-qc-montreal") == .paused(receivedBytes: 400_000, totalBytes: published.request.size))250 #expect(await store.regions().isEmpty)251 #expect(h.logic.requests(for: path).count == 1)252253 try await manager.resume(regionId: "ca-qc-montreal")254 let finished = try #require(await manager.result(regionId: "ca-qc-montreal"))255 #expect(try finished.get().dataVersion == DataVersion("2026.11.24"))256 #expect(h.logic.requests(for: path).map { $0.headers["range"] } == [nil, "bytes=400000-"])257 #expect(await downloadError { try await manager.resume(regionId: "ca-qc-montreal") } == .nothingToResume(regionId: "ca-qc-montreal"))258 }259260 @Test func resumeAfterRelaunch() async throws {261 let published = try h.publish()262 let path = published.request.path263 h.logic.fail(path, .truncate(afterBytes: 700_000))264 do {265 let (manager, _) = h.manager(try h.store(), maxAttempts: 1)266 #expect(await downloadError { try await manager.download(published.request) } == .network(.connectionLost))267 }268 // New process: new store (whose recovery must not delete the partial download), new manager.269 let store = try h.store()270 #expect(store.recoveryReport.isClean)271 let (manager, _) = h.manager(store)272 #expect(manager.pendingDownloads() == [PendingDownload(request: published.request, receivedBytes: 700_000)])273 try await manager.resume(regionId: "ca-qc-montreal")274 let result = try #require(await manager.result(regionId: "ca-qc-montreal"))275 #expect(try result.get().dataVersion == DataVersion("2026.11.24"))276 #expect(h.logic.requests(for: path).last?.headers["range"] == "bytes=700000-")277 try await store.verifyInstalled(regionId: "ca-qc-montreal")278 #expect(manager.pendingDownloads().isEmpty)279 }280281 @Test func serverFileChangedDuringResume() async throws {282 let published = try h.publish()283 let path = published.request.path284 h.logic.fail(path, .truncate(afterBytes: 500_000))285 let store = try h.store()286 let (manager, _) = h.manager(store, maxAttempts: 1)287 #expect(await downloadError { try await manager.download(published.request) } == .network(.connectionLost))288 #expect(h.partials().count == 2)289290 // The publisher replaces the file at the same URL (same size, other bytes): the ETag changes.291 var other = published.data292 other[other.count - 10] ^= 0xFF293 h.logic.put(path, other)294 #expect(await downloadError { try await manager.download(published.request) } == .serverFileChanged)295 #expect(h.logic.requests(for: path).last?.headers["if-range"] == "\"\(sha256Hex(published.data))\"")296 #expect(h.partials().isEmpty, "bytes of two different files are never mixed")297 #expect(await store.regions().isEmpty)298299 // Same thing when the new file is shorter than what was already downloaded (416).300 h.logic.put(path, published.data)301 h.logic.fail(path, .truncate(afterBytes: 500_000))302 #expect(await downloadError { try await manager.download(published.request) } == .network(.connectionLost))303 h.logic.put(path, published.data.prefix(1000))304 #expect(await downloadError { try await manager.download(published.request) } == .serverFileChanged)305 #expect(h.partials().isEmpty)306 }307308 @Test func serverWithoutRangeSupportRestartsFromZero() async throws {309 let published = try h.publish()310 let path = published.request.path311 h.logic.fail(path, .truncate(afterBytes: 500_000), .ignoreRange)312 let store = try h.store()313 let (manager, _) = h.manager(store)314 let region = try await manager.download(published.request)315 try await store.verifyInstalled(regionId: region.id)316 #expect(h.logic.requests(for: path).count == 2)317 }318319 @Test func withoutAStrongETagNothingIsResumed() async throws {320 let published = try h.publish()321 let path = published.request.path322 h.logic.fail(path, .noETag, .truncate(afterBytes: 500_000))323 h.logic.fail(path)324 let store = try h.store()325 // First response has no ETag and is cut by the transport wrapper.326 let cut = QuietTruncation(inner: FakeTransport(logic: h.logic), limitFirstBody: 200_000)327 let (manager, _) = h.manager(store, transport: cut, maxAttempts: 3)328 let region = try await manager.download(published.request)329 try await store.verifyInstalled(regionId: region.id)330 let requests = h.logic.requests(for: path)331 #expect(requests.count >= 2)332 #expect(requests[1].headers["range"] == nil, "no validator, no Range: the transfer restarts from zero")333 }334335 @Test func rateLimited() async throws {336 let published = try h.publish()337 h.logic.fail(published.request.path, .status(429, ["Retry-After": "17"]), .status(429, [:]))338 let store = try h.store()339 let (manager, _) = h.manager(store)340 #expect(await downloadError { try await manager.download(published.request) } == .rateLimited(retryAfter: 17))341 #expect(await downloadError { try await manager.download(published.request) } == .rateLimited(retryAfter: nil))342 #expect(h.logic.requests.count == 2, "a 429 is never retried automatically")343 try await manager.download(published.request)344 }345346 @Test func httpErrorsAndOffline() async throws {347 let published = try h.publish()348 let store = try h.store()349 let (manager, _) = h.manager(store)350 h.logic.fail(published.request.path, .status(500, [:]), .status(403, [:]), .offline)351 #expect(await downloadError { try await manager.download(published.request) } == .httpStatus(500))352 #expect(await downloadError { try await manager.download(published.request) } == .httpStatus(403))353 #expect(await downloadError { try await manager.download(published.request) } == .offline)354 var missing = published.request355 missing.path = "files/ca-qc-montreal/2026.11.24/withdrawn.orixmap"356 #expect(await downloadError { try await manager.download(missing) } == .httpStatus(404))357 #expect(await store.regions().isEmpty)358 }359360 @Test func wrongChecksumAndWrongSize() async throws {361 let published = try h.publish()362 let store = try h.store()363 let (manager, _) = h.manager(store)364365 // The catalog announces another digest than the file has.366 var request = published.request367 request.sha256 = String(repeating: "0", count: 64)368 #expect(await downloadError { try await manager.download(request) }369 == .checksumMismatch(expected: request.sha256, actual: sha256Hex(published.data)))370 #expect(h.partials().isEmpty)371372 // The catalog announces another size.373 request = published.request374 request.size += 4096375 #expect(await downloadError { try await manager.download(request) } == .sizeMismatch(expected: request.size, actual: published.request.size))376 request.size = published.request.size - 4096377 #expect(await downloadError { try await manager.download(request) } == .sizeMismatch(expected: request.size, actual: published.request.size))378 #expect(await store.regions().isEmpty)379 #expect(h.partials().isEmpty)380 }381382 @Test func serverControlledByAnAttackerCannotInstallAnything() async throws {383 let store = try h.store()384 let (manager, _) = h.manager(store)385386 // 1. A component is modified and the catalog digest recomputed to match: the signature chain catches it.387 let published = try h.publish()388 var modified = published.data389 modified[modified.count - 100] ^= 0x01390 h.logic.put(published.request.path, modified)391 var request = published.request392 request.sha256 = sha256Hex(modified)393 #expect(await downloadError { try await manager.download(request) } == .invalidPackage(.componentChecksumMismatch(component: "routing")))394 #expect(h.partials().isEmpty)395396 // 2. A package signed with the attacker's own key: refused as soon as the preamble has arrived.397 let attacker = Curve25519.Signing.PrivateKey()398 let forged = try h.publish("2026.12.1", seed: 9, signedBy: attacker)399 h.logic.resetLog()400 #expect(await downloadError { try await manager.download(forged.request) }401 == .invalidPackage(.unknownSigningKey(keyId: TrustedKey(attacker.publicKey).keyId)))402 #expect(h.partials().isEmpty)403404 // 3. A genuine, correctly signed package of another region served under this region's name.405 let quebec = try h.publish("2026.11.24", region: "ca-qc-quebec", seed: 4)406 var disguised = quebec.request407 disguised.regionId = "ca-qc-montreal"408 #expect(await downloadError { try await manager.download(disguised) }409 == .packageMismatch(.region(expected: "ca-qc-montreal", found: "ca-qc-quebec")))410411 // 4. A genuine older version served as the new one (rollback through the catalog).412 let old = try h.publish("2026.10.1", seed: 5)413 var relabelled = old.request414 relabelled.dataVersion = DataVersion("2026.12.24")!415 #expect(await downloadError { try await manager.download(relabelled) }416 == .packageMismatch(.dataVersion(expected: DataVersion("2026.12.24")!, found: DataVersion("2026.10.1")!)))417418 // 5. Garbage.419 h.logic.put("files/x/1/x-1.orixmap", pseudoRandomData(100_000, seed: 3))420 let garbage = DownloadRequest(regionId: "x", dataVersion: DataVersion("1")!, path: "files/x/1/x-1.orixmap", size: 100_000,421 sha256: sha256Hex(pseudoRandomData(100_000, seed: 3)), installedSize: 1)422 #expect(await downloadError { try await manager.download(garbage) } == .invalidPackage(.badMagic))423424 #expect(await store.regions().isEmpty)425 #expect(h.partials().isEmpty)426 #expect(listTree(h.root) == ["regions", "staging", "staging/downloads"])427 }428429 @Test func downgradeOfferedByTheCatalogIsRefusedEarly() async throws {430 let new = try h.publish("2026.11.24", seed: 1)431 let old = try h.publish("2026.11.10", seed: 2)432 let store = try h.store()433 let (manager, _) = h.manager(store)434 try await manager.download(new.request)435 h.logic.resetLog()436 #expect(await downloadError { try await manager.download(old.request) }437 == .install(.downgradeRefused(regionId: "ca-qc-montreal", installed: DataVersion("2026.11.24")!, offered: DataVersion("2026.11.10")!)))438 #expect(await store.region("ca-qc-montreal")?.dataVersion == DataVersion("2026.11.24"))439 #expect(h.partials().isEmpty)440 // Explicitly forced by the user: accepted, and the newer version stays as the rollback copy.441 let forced = try await manager.download(old.request, options: InstallOptions(allowDowngrade: true))442 #expect(forced.dataVersion == DataVersion("2026.11.10"))443 #expect(forced.previousVersion == DataVersion("2026.11.24"))444 // An application that is too old learns it from the manifest, before the transfer ends.445 let future = try h.publish("2026.12.24", region: "ca-on-ottawa", seed: 3, minApp: "9.0")446 let strict = try RegionStore.open(h.tmp.file("root-strict"), trust: h.trust) { $0.compatibility.appVersion = AppVersion("1.0") }447 let (second, _) = h.manager(strict)448 #expect(await downloadError { try await second.download(future.request) } == .install(.appTooOld(required: AppVersion("9.0")!, current: AppVersion("1.0")!)))449 }450451 @Test func notEnoughSpace() async throws {452 let published = try h.publish()453 let store = try h.store()454 let (manager, _) = h.manager(store)455 h.probe.free = 1_000_000456 let required = published.request.size + published.request.installedSize + 1000457 #expect(await downloadError { try await manager.download(published.request) }458 == .notEnoughSpace(required: required, available: 1_000_000, missing: required - 1_000_000))459 #expect(h.logic.requests.isEmpty, "the check happens before any network request")460 h.probe.free = required461 try await manager.download(published.request)462 }463464 @Test func cancelDeletesThePartialFile() async throws {465 let published = try h.publish()466 h.logic.fail(published.request.path, .stall(afterBytes: 300_000))467 let store = try h.store()468 let (manager, _) = h.manager(store)469 let stream = await manager.events()470 await manager.start(published.request)471 for await event in stream { if case .downloading(let p) = event.state, p.receivedBytes >= 300_000 { break } }472 #expect(h.partials().count == 2)473 await manager.cancel(regionId: "ca-qc-montreal")474 #expect(h.partials().isEmpty)475 #expect(await manager.state(regionId: "ca-qc-montreal") == .cancelled)476 #expect(manager.pendingDownloads().isEmpty)477 #expect(await store.regions().isEmpty)478 await manager.cancel(regionId: "never-started")479 }480481 @Test func cancellingTheCallingTaskPauses() async throws {482 let published = try h.publish()483 h.logic.fail(published.request.path, .stall(afterBytes: 300_000))484 let store = try h.store()485 let (manager, _) = h.manager(store)486 let stream = await manager.events()487 let task = Task { try await manager.download(published.request) }488 for await event in stream { if case .downloading(let p) = event.state, p.receivedBytes >= 300_000 { break } }489 task.cancel()490 let result = await task.result491 guard case .failure(let error) = result else { Issue.record("download finished"); return }492 #expect(error as? DownloadError == .paused)493 #expect(h.partials().count == 2, "the partial file is kept")494 }495496 @Test func newerVersionReplacesTheOldPartialFile() async throws {497 let old = try h.publish("2026.11.10", seed: 1), new = try h.publish("2026.11.24", seed: 2)498 h.logic.fail(old.request.path, .truncate(afterBytes: 200_000))499 let store = try h.store()500 let (manager, _) = h.manager(store, maxAttempts: 1)501 #expect(await downloadError { try await manager.download(old.request) } == .network(.connectionLost))502 #expect(h.partials().first?.contains("2026.11.10") == true)503 try await manager.download(new.request)504 #expect(h.partials().isEmpty)505 #expect(await store.region("ca-qc-montreal")?.dataVersion == DataVersion("2026.11.24"))506 }507508 @Test func invalidRequestsNeverReachTheNetwork() async throws {509 let published = try h.publish()510 let store = try h.store()511 let (manager, _) = h.manager(store)512 var r = published.request; r.path = "../../../other/file"513 #expect(await downloadError { try await manager.download(r) } == .invalidRequest(.path))514 r = published.request; r.path = "https://evil.example/x.orixmap"515 #expect(await downloadError { try await manager.download(r) } == .invalidRequest(.path))516 r = published.request; r.regionId = "../x"517 #expect(await downloadError { try await manager.download(r) } == .invalidRequest(.regionId))518 r = published.request; r.sha256 = "abc"519 #expect(await downloadError { try await manager.download(r) } == .invalidRequest(.sha256))520 r = published.request; r.size = 0521 #expect(await downloadError { try await manager.download(r) } == .invalidRequest(.size))522 r = published.request; r.size = .max523 #expect(await downloadError { try await manager.download(r) } == .invalidRequest(.size))524 #expect(h.logic.requests.isEmpty)525 #expect(h.partials().isEmpty)526 }527528 @Test func manifestAloneWithOneRangeRequest() async throws {529 let published = try h.publish()530 let store = try h.store()531 let (manager, _) = h.manager(store)532 let preamble = try await manager.fetchManifest(published.request, preambleSize: published.region.latest.preambleSize)533 #expect(preamble.manifest.regionId == "ca-qc-montreal")534 #expect(preamble.manifest.licences == Fixture.licences)535 #expect(preamble.manifest.downloadSize == published.request.size)536 let size = try #require(published.region.latest.preambleSize)537 #expect(h.logic.requests.count == 1)538 #expect(h.logic.requests[0].headers["range"] == "bytes=0-\(size - 1)")539 #expect(h.logic.bodyBytesServed == Int(size), "only the preamble was transferred")540541 // Without the size hint: 16 KiB first, which is enough here.542 h.logic.resetLog()543 #expect(try await manager.fetchManifest(published.request).manifest == preamble.manifest)544 #expect(h.logic.bodyBytesServed == 16_384)545 // With a hint that is too small, a second request fetches the rest.546 h.logic.resetLog()547 #expect(try await manager.fetchManifest(published.request, preambleSize: 64).manifest == preamble.manifest)548 #expect(h.logic.requests.map { $0.headers["range"] } == ["bytes=0-63", "bytes=64-\(size - 1)"])549 // A server that ignores Range still works, and the connection is dropped once the preamble is read.550 h.logic.fail(published.request.path, .ignoreRange)551 #expect(try await manager.fetchManifest(published.request).manifest == preamble.manifest)552553 let attacker = Curve25519.Signing.PrivateKey()554 let forged = try h.publish("2026.12.1", seed: 9, signedBy: attacker)555 #expect(await downloadError { _ = try await manager.fetchManifest(forged.request) }556 == .invalidPackage(.unknownSigningKey(keyId: TrustedKey(attacker.publicKey).keyId)))557 h.logic.fail(published.request.path, .status(429, ["Retry-After": "5"]))558 #expect(await downloadError { _ = try await manager.fetchManifest(published.request) } == .rateLimited(retryAfter: 5))559 #expect(await store.regions().isEmpty)560 #expect(h.partials().isEmpty)561 }562563 @Test func fileDeliveredByAnotherMechanism() async throws {564 let published = try h.publish()565 let store = try h.store()566 let (manager, _) = h.manager(store)567 let delivered = h.tmp.file("CFNetworkDownload_abc.tmp")568 try published.data.write(to: delivered)569 var wrong = published.request; wrong.sha256 = String(repeating: "1", count: 64)570 #expect(await downloadError { try await manager.installDownloadedFile(at: delivered, for: wrong) }571 == .checksumMismatch(expected: wrong.sha256, actual: sha256Hex(published.data)))572 let region = try await manager.installDownloadedFile(at: delivered, for: published.request)573 #expect(region.dataVersion == DataVersion("2026.11.24"))574 #expect(!FileManager.default.fileExists(atPath: delivered.path))575 #expect(h.logic.requests.isEmpty)576 }577}578579/// Wraps a transport and turns "connection lost" into a clean end of body, as some proxies do; optionally cuts the580/// first response body after a number of bytes.581final class QuietTruncation: HTTPTransport, @unchecked Sendable {582 let inner: FakeTransport583 private let lock = NSLock()584 private var limitFirstBody: Int?585586 init(inner: FakeTransport, limitFirstBody: Int? = nil) { self.inner = inner; self.limitFirstBody = limitFirstBody }587588 private func takeLimit() -> Int? { lock.lock(); defer { lock.unlock() }; let l = limitFirstBody; limitFirstBody = nil; return l }589590 func send(_ request: HTTPRequest) async throws(TransportError) -> HTTPResponse {591 let response = try await inner.send(request)592 let limit = takeLimit()593 let (stream, continuation) = AsyncThrowingStream<Data, any Error>.makeStream()594 let body = response.body595 Task {596 var sent = 0597 do {598 for try await chunk in body {599 if let limit, sent + chunk.count > limit {600 continuation.yield(chunk.prefix(limit - sent))601 break602 }603 continuation.yield(chunk)604 sent += chunk.count605 }606 } catch {}607 continuation.finish()608 }609 return HTTPResponse(status: response.status, headers: response.headers, body: stream)610 }611}612