Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : tests/maps.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */424344import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";45import { createHash, randomBytes } from "node:crypto";46import { mkdirSync, mkdtempSync, rmSync, symlinkSync, truncateSync, utimesSync, writeFileSync } from "node:fs";47import { tmpdir } from "node:os";48import { join } from "node:path";49import { resetRateLimits } from "@/lib/security/ratelimit";5051/**52 * /maps/v1 against a throw-away distribution directory: a synthetic catalog in the shape `orix-package catalog`53 * writes (docs/CATALOG_API.md of the ORIX Maps repository), and small random files standing in for packages.54 */5556const dir = mkdtempSync(join(tmpdir(), "orix-maps-test-"));57const outside = mkdtempSync(join(tmpdir(), "orix-maps-outside-"));58const v1 = join(dir, "v1");59const sha = (b: Buffer | string) => createHash("sha256").update(b).digest("hex");60const artefactPath = (id: string, version: string) => `files/${id}/${version}/${id}-${version}.orixmap`;6162const ID = "ca-qc-montreal";63const current = randomBytes(5000), previous = randomBytes(3000);64const entry = (version: string, bytes: Buffer, over: Record<string, unknown> = {}) => ({65 dataVersion: version, dataTimestamp: "2026-11-24T00:00:00Z", buildDate: "2026-11-25T08:33:51Z", downloadSize: bytes.length, installedSize: bytes.length,66 sha256: sha(bytes), signingKeyId: "0000000000000000", path: artefactPath(ID, version), preambleSize: 100, ...over,67});68const schema = { major: 1, minor: 0 }, generatedAt = "2026-11-25T08:33:59Z";69const region = (id: string, latest: unknown) => ({ id, names: { en: id }, bbox: { minLat: 0, minLon: 0, maxLat: 1, maxLon: 1 }, capabilities: ["map"], latest });7071const put = (relative: string, content: Buffer | string) => {72 const file = join(v1, relative);73 mkdirSync(join(file, ".."), { recursive: true });74 writeFileSync(file, content);75 return file;76};77const writeCatalog = (regions: unknown[]) => { const raw = JSON.stringify({ schema, generatedAt, regions }, null, 2); put("catalog.json", raw); return raw; };7879let GET: (typeof import("@/app/maps/v1/[...path]/route"))["GET"], HEAD: (typeof import("@/app/maps/v1/[...path]/route"))["HEAD"];80let catalogRaw = "";81const regionRaw = JSON.stringify({ schema, generatedAt, region: region(ID, entry("2026.11.24", current)), mapZoom: { minZoom: 0, maxZoom: 15 } });82const versionsRaw = JSON.stringify({ schema, generatedAt, id: ID, latest: "2026.11.24", versions: [entry("2026.11.24", current), entry("2026.11.10", previous)] });8384const call = (segments: string[], headers: Record<string, string> = {}, method: "GET" | "HEAD" = "GET") =>85 (method === "GET" ? GET : HEAD)(new Request(`https://orix.test/maps/v1/${segments.join("/")}`, { method, headers }), { params: Promise.resolve({ path: segments }) });86const get = (relative: string, headers: Record<string, string> = {}) => call(relative.split("/"), headers);87const head = (relative: string, headers: Record<string, string> = {}) => call(relative.split("/"), headers, "HEAD");88const bytes = async (r: Response) => Buffer.from(await r.arrayBuffer());8990const CURRENT = artefactPath(ID, "2026.11.24"), PREVIOUS = artefactPath(ID, "2026.11.10");91const etag = `"${sha(current)}"`;9293beforeAll(async () => {94 process.env.ORIX_MAPS_DIR = dir;95 ({ GET, HEAD } = await import("@/app/maps/v1/[...path]/route"));96 catalogRaw = writeCatalog([97 region(ID, entry("2026.11.24", current)),98 region("size-mismatch", entry("1.0", current, { path: artefactPath("size-mismatch", "1.0") })),99 region("escape", entry("1.0", current, { path: artefactPath("escape", "1.0") })),100 region("bad-digest", entry("1.0", current, { path: artefactPath("bad-digest", "1.0"), sha256: "ABC" })),101 region("other-path", entry("1.0", current, { path: CURRENT })),102 ]);103 put(`regions/${ID}.json`, regionRaw);104 put(`regions/${ID}/versions.json`, versionsRaw);105 put(CURRENT, current);106 put(PREVIOUS, previous);107 put(artefactPath(ID, "2026.11.01"), randomBytes(100)); // on disk, listed nowhere108 put(artefactPath("size-mismatch", "1.0"), current.subarray(0, 4999)); // listed with 5000 bytes109 put(artefactPath("bad-digest", "1.0"), current);110 put(artefactPath("other-path", "1.0"), current);111 put("pins.json", JSON.stringify({ pins: {} }));112 put("notes.txt", "publisher notes");113 // Listed, right size, but the file is a symbolic link leaving the distribution root.114 writeFileSync(join(outside, "package"), current);115 mkdirSync(join(v1, "files/escape/1.0"), { recursive: true });116 symlinkSync(join(outside, "package"), join(v1, artefactPath("escape", "1.0")));117 writeFileSync(join(outside, "secret.json"), "{}");118 symlinkSync(join(outside, "secret.json"), join(v1, "regions/linked.json"));119});120afterAll(() => { rmSync(dir, { recursive: true, force: true }); rmSync(outside, { recursive: true, force: true }); delete process.env.ORIX_MAPS_DIR; });121beforeEach(() => resetRateLimits());122123describe("JSON documents", () => {124 it("serves catalog.json with a strong SHA-256 ETag and short caching", async () => {125 const r = await get("catalog.json");126 expect(r.status).toBe(200);127 expect(r.headers.get("content-type")).toBe("application/json");128 expect(r.headers.get("etag")).toBe(`"${sha(catalogRaw)}"`);129 expect(r.headers.get("content-length")).toBe(String(Buffer.byteLength(catalogRaw)));130 expect(r.headers.get("cache-control")).toBe("public, max-age=300");131 expect(r.headers.get("x-content-type-options")).toBe("nosniff");132 expect(r.headers.get("access-control-allow-origin")).toBe("*");133 expect(r.headers.get("set-cookie")).toBeNull();134 expect(r.headers.get("content-encoding")).toBeNull();135 expect(await r.text()).toBe(catalogRaw);136 });137138 it("answers 304 to a matching If-None-Match, 200 to another tag", async () => {139 const tag = `"${sha(catalogRaw)}"`;140 for (const value of [tag, `W/${tag}`, `"other", ${tag}`, "*"]) {141 const r = await get("catalog.json", { "if-none-match": value });142 expect(r.status).toBe(304);143 expect(r.headers.get("etag")).toBe(tag);144 expect(await r.text()).toBe("");145 }146 expect((await get("catalog.json", { "if-none-match": `"${"0".repeat(64)}"` })).status).toBe(200);147 });148149 it("serves the region document and its versions", async () => {150 const a = await get(`regions/${ID}.json`);151 expect(a.status).toBe(200);152 expect(a.headers.get("etag")).toBe(`"${sha(regionRaw)}"`);153 expect(await a.text()).toBe(regionRaw);154 const b = await get(`regions/${ID}/versions.json`);155 expect(b.status).toBe(200);156 expect(b.headers.get("etag")).toBe(`"${sha(versionsRaw)}"`);157 expect(b.headers.get("content-type")).toBe("application/json");158 expect(await b.text()).toBe(versionsRaw);159 expect((await get(`regions/${ID}/versions.json`, { "if-none-match": `"${sha(versionsRaw)}"` })).status).toBe(304);160 expect((await get("regions/unknown.json")).status).toBe(404);161 expect((await get("regions/unknown/versions.json")).status).toBe(404);162 });163164 it("answers HEAD with the headers and no body", async () => {165 const r = await head("catalog.json");166 expect(r.status).toBe(200);167 expect(r.headers.get("content-length")).toBe(String(Buffer.byteLength(catalogRaw)));168 expect(r.headers.get("etag")).toBe(`"${sha(catalogRaw)}"`);169 expect(await r.text()).toBe("");170 });171172 it("sees a republished document (new ETag) and keeps the tag when only read again", async () => {173 const file = put("regions/republished.json", "{\"a\":1}");174 const first = await get("regions/republished.json");175 expect(first.headers.get("etag")).toBe(`"${sha("{\"a\":1}")}"`);176 expect((await get("regions/republished.json")).headers.get("etag")).toBe(first.headers.get("etag"));177 writeFileSync(file, "{\"a\":2}");178 utimesSync(file, new Date(), new Date(Date.now() + 5000));179 const second = await get("regions/republished.json");180 expect(second.headers.get("etag")).toBe(`"${sha("{\"a\":2}")}"`);181 expect(await second.text()).toBe("{\"a\":2}");182 });183});184185describe("artefacts", () => {186 it("serves a listed package whole, with the catalog SHA-256 as ETag", async () => {187 const r = await get(CURRENT);188 expect(r.status).toBe(200);189 expect(r.headers.get("content-type")).toBe("application/vnd.orix.map");190 expect(r.headers.get("etag")).toBe(etag);191 expect(r.headers.get("content-length")).toBe("5000");192 expect(r.headers.get("accept-ranges")).toBe("bytes");193 expect(r.headers.get("cache-control")).toContain("public, max-age=31536000, immutable");194 expect(r.headers.get("content-encoding")).toBeNull();195 expect(r.headers.get("set-cookie")).toBeNull();196 expect(r.headers.get("x-content-type-options")).toBe("nosniff");197 expect((await bytes(r)).equals(current)).toBe(true);198 });199200 it("serves a version listed only in versions.json", async () => {201 const r = await get(PREVIOUS);202 expect(r.status).toBe(200);203 expect(r.headers.get("etag")).toBe(`"${sha(previous)}"`);204 expect((await bytes(r)).equals(previous)).toBe(true);205 });206207 it("answers 206 with exactly the requested bytes", async () => {208 const cases: [string, number, number][] = [["bytes=1000-1999", 1000, 1999], ["bytes=4000-", 4000, 4999], ["bytes=0-99", 0, 99], ["bytes=0-0", 0, 0], ["bytes=4990-99999", 4990, 4999], ["bytes=-10", 4990, 4999], ["bytes=-99999", 0, 4999]];209 for (const [range, start, end] of cases) {210 const r = await get(CURRENT, { range });211 expect(r.status, range).toBe(206);212 expect(r.headers.get("content-range"), range).toBe(`bytes ${start}-${end}/5000`);213 expect(r.headers.get("content-length"), range).toBe(String(end - start + 1));214 expect(r.headers.get("etag")).toBe(etag);215 expect(r.headers.get("content-type")).toBe("application/vnd.orix.map");216 expect(r.headers.get("accept-ranges")).toBe("bytes");217 expect((await bytes(r)).equals(current.subarray(start, end + 1)), range).toBe(true);218 }219 });220221 it("honours the range when If-Range carries the current tag", async () => {222 const r = await get(CURRENT, { range: "bytes=2500-", "if-range": etag });223 expect(r.status).toBe(206);224 expect(r.headers.get("content-range")).toBe("bytes 2500-4999/5000");225 expect((await bytes(r)).equals(current.subarray(2500))).toBe(true);226 });227228 it("ignores the range and sends the whole file when If-Range does not match", async () => {229 for (const value of [`"${"0".repeat(64)}"`, `W/${etag}`, "Wed, 25 Nov 2026 08:00:00 GMT"]) {230 const r = await get(CURRENT, { range: "bytes=2500-", "if-range": value });231 expect(r.status, value).toBe(200);232 expect(r.headers.get("content-range")).toBeNull();233 expect(r.headers.get("content-length")).toBe("5000");234 expect(r.headers.get("etag")).toBe(etag);235 expect((await bytes(r)).equals(current)).toBe(true);236 }237 // Even an unsatisfiable range is ignored when the validator does not match: the client must see the new file.238 expect((await get(CURRENT, { range: "bytes=9000-", "if-range": `"${"0".repeat(64)}"` })).status).toBe(200);239 });240241 it("answers 416 to a range starting at or after the end", async () => {242 for (const range of ["bytes=5000-", "bytes=5000-6000", "bytes=99999-", "bytes=-0"]) {243 const r = await get(CURRENT, { range });244 expect(r.status, range).toBe(416);245 expect(r.headers.get("content-range")).toBe("bytes */5000");246 expect(await r.text()).toBe("");247 }248 expect((await get(CURRENT, { range: "bytes=5000-", "if-range": etag })).status).toBe(416);249 });250251 it("ignores a Range header it does not serve (several ranges, other unit, malformed)", async () => {252 for (const range of ["bytes=0-9,20-29", "items=0-9", "bytes=abc", "bytes=10-5", "bytes=-"]) {253 const r = await get(CURRENT, { range });254 expect(r.status, range).toBe(200);255 expect(r.headers.get("content-length")).toBe("5000");256 await r.body?.cancel();257 }258 });259260 it("answers 304 to a matching If-None-Match, before looking at Range", async () => {261 const r = await get(CURRENT, { "if-none-match": etag, range: "bytes=0-9" });262 expect(r.status).toBe(304);263 expect(r.headers.get("etag")).toBe(etag);264 });265266 it("answers HEAD with the full length and no body, Range ignored", async () => {267 const r = await head(CURRENT, { range: "bytes=0-9" });268 expect(r.status).toBe(200);269 expect(r.headers.get("content-length")).toBe("5000");270 expect(r.headers.get("etag")).toBe(etag);271 expect(r.headers.get("accept-ranges")).toBe("bytes");272 expect(r.headers.get("content-type")).toBe("application/vnd.orix.map");273 expect(await r.text()).toBe("");274 });275276 it("refuses a file on disk that no document lists", async () => {277 expect((await get(artefactPath(ID, "2026.11.01"))).status).toBe(404);278 expect((await head(artefactPath(ID, "2026.11.01"))).status).toBe(404);279 });280281 it("refuses a listed file whose size on disk differs", async () => {282 expect((await get(artefactPath("size-mismatch", "1.0"))).status).toBe(404);283 // …and a published file that shrinks afterwards284 const file = put(artefactPath("shrinks", "1.0"), current);285 writeCatalog([region(ID, entry("2026.11.24", current)), region("shrinks", entry("1.0", current, { path: artefactPath("shrinks", "1.0") }))]);286 utimesSync(join(v1, "catalog.json"), new Date(), new Date(Date.now() + 9000));287 const ok = await get(artefactPath("shrinks", "1.0"));288 expect(ok.status).toBe(200);289 await ok.body?.cancel();290 truncateSync(file, 10);291 expect((await get(artefactPath("shrinks", "1.0"))).status).toBe(404);292 });293294 it("refuses a listing without a usable SHA-256, or whose path is another file", async () => {295 expect((await get(artefactPath("bad-digest", "1.0"))).status).toBe(404);296 expect((await get(artefactPath("other-path", "1.0"))).status).toBe(404);297 });298299 it("refuses a listed file that is a symbolic link leaving the distribution", async () => {300 expect((await get(artefactPath("escape", "1.0"))).status).toBe(404);301 expect((await get("regions/linked.json")).status).toBe(404);302 });303});304305describe("everything else is 404", () => {306 it("never serves pins.json or any other file of the directory", async () => {307 for (const p of ["pins.json", "notes.txt", "files", "regions", `files/${ID}`, `files/${ID}/2026.11.24`, `regions/${ID}`, "catalog.json/x", `regions/${ID}/pins.json`]) {308 const r = await get(p);309 expect(r.status, p).toBe(404);310 expect(r.headers.get("cache-control")).toBe("no-store");311 }312 });313314 it("refuses traversal and odd segments", async () => {315 const odd: string[][] = [316 [".."], ["..", "v1", "catalog.json"], ["regions", "..", "catalog.json"], ["regions", "..", "pins.json"], ["files", "..", "..", "pins.json"],317 ["files", ID, "..", `${ID}-...orixmap`], ["files", ID, "2026.11.24", "..", "..", "..", "..", "pins.json"],318 ["files", "..", "2026.11.24", "..-2026.11.24.orixmap"], ["files", ID, "..", `${ID}-2026.11.24.orixmap`],319 ["regions", "../pins.json"], ["regions", "..%2Fpins.json"], ["regions", "%2e%2e", "versions.json"], ["regions", `${ID}.json\0`], ["regions", ".json"],320 ["regions", "CA-QC.json"], ["regions", "a_b.json"], ["regions", `${"a".repeat(65)}.json`], ["regions", "", "versions.json"],321 ["files", ID, "2026.11.24", `${ID}-2026.11.24.orixmap.part`], ["files", ID, "2026.11.24", "other-2026.11.24.orixmap"], ["files", ID, "2026.11.24", `${ID}-2026.11.10.orixmap`],322 ["files", ID, "v2026", `${ID}-v2026.orixmap`], ["files", ID, "2026..11", `${ID}-2026..11.orixmap`], ["files", ID, ".", `${ID}-..orixmap`], ["files", ID, "2026.11.24.", `${ID}-2026.11.24..orixmap`],323 ["files", "Ca-Qc", "1.0", "Ca-Qc-1.0.orixmap"], ["files", ID, "2026.11.24", `${ID}-2026.11.24.orixmap`, "x"], ["catalog.json", ".."], ["CATALOG.JSON"], ["catalog.json "], [""],324 ];325 for (const segments of odd) expect((await call(segments)).status, JSON.stringify(segments)).toBe(404);326 });327328 it("answers 404, not 500, when the distribution is empty or missing", async () => {329 const saved = process.env.ORIX_MAPS_DIR;330 const empty = mkdtempSync(join(tmpdir(), "orix-maps-empty-"));331 try {332 mkdirSync(join(empty, "v1"));333 process.env.ORIX_MAPS_DIR = empty;334 expect((await get("catalog.json")).status).toBe(404);335 expect((await get(CURRENT)).status).toBe(404);336 process.env.ORIX_MAPS_DIR = join(empty, "missing");337 expect((await get("catalog.json")).status).toBe(404);338 expect((await get(`regions/${ID}/versions.json`)).status).toBe(404);339 } finally { process.env.ORIX_MAPS_DIR = saved; rmSync(empty, { recursive: true, force: true }); }340 });341});342343describe("rate limit", () => {344 it("answers 429 with Retry-After once the budget of an address is spent, per address", async () => {345 const from = (ip: string) => ({ "x-forwarded-for": ip });346 for (let i = 0; i < 300; i++) expect((await head("catalog.json", from("203.0.113.7"))).status).toBe(200);347 const r = await get("catalog.json", from("203.0.113.7"));348 expect(r.status).toBe(429);349 const wait = Number(r.headers.get("retry-after"));350 expect(Number.isInteger(wait) && wait >= 1 && wait <= 60).toBe(true);351 expect(r.headers.get("set-cookie")).toBeNull();352 expect((await get(CURRENT, from("203.0.113.7"))).status).toBe(429);353 expect((await get("catalog.json", from("203.0.113.8"))).status).toBe(200);354 });355});356