Search / tests /data /test_search_generation_fetch.mjs
vomebook
Materialize Space search data from a verified immutable bucket generation
fc4c1a6
Raw History Blame Contribute Delete
13.4 kB
import assert from "node:assert/strict";
import {createHash} from "node:crypto";
import {spawnSync} from "node:child_process";
import {fileURLToPath} from "node:url";
import {mkdtemp, readFile, readdir, rm, symlink, writeFile, mkdir} from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
import test from "node:test";
import {ensureSearchGeneration, fetchSearchGeneration} from "../../scripts/data/fetch_search_generation.mjs";
import {DEFAULT_GENERATION, prepareTestData} from "../../scripts/data/prepare_test_data.mjs";
const hash = bytes => createHash("sha256").update(bytes).digest("hex");
function canonical(value) {
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
if (value && typeof value === "object") return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
return JSON.stringify(value);
}
function fixture() {
const files = {}, objects = {}, bodies = new Map();
for (const name of ["search_data.json.gz", "folder_tree.json.gz", "folder_browser.json.gz",
"search_words.bin.gz", "search_ngrams_2.bin.gz", "search_ngrams_3.bin.gz",
"initial/global.json", "initial/manifest.json", "initial/repos/Test.json",
"sidebar/global.json", "sidebar/manifest.json", "sidebar/repos/Test.json"]) {
const bytes = Buffer.from(`fixture ${name}`), sha256 = hash(bytes);
const object = `objects/sha256/${sha256.slice(0, 2)}/${sha256}`;
files[name] = {sha256, bytes: bytes.length};
objects[name] = {...files[name], object};
bodies.set(object, bytes);
}
const identity = {version: 1, kind: "search-snapshot-local", files: {space: files}};
const generation = hash(Buffer.from(canonical(identity) + "\n"));
const manifest = {...identity, generation, object_layout: "objects/sha256/<first-two>/<sha256>", objects: {space: objects}};
bodies.set(`generations/${generation}/manifest.json`, Buffer.from(JSON.stringify(manifest)));
return {generation, manifest, bodies};
}
async function withFixture(run) {
const root = await mkdtemp(join(tmpdir(), "hf-search-generation-")), originalFetch = globalThis.fetch;
const f = {...fixture(), root, out: join(root, "data"), requests: []};
globalThis.fetch = async url => {
const base = "https://huggingface.co/buckets/vomebook/search-data-v1/resolve/";
assert.ok(String(url).startsWith(base), "only immutable search bucket requests");
const name = String(url).slice(base.length);
f.requests.push(name);
return f.bodies.has(name) ? new Response(f.bodies.get(name)) : new Response("missing", {status: 404});
};
try { await run(f); }
finally { globalThis.fetch = originalFetch; await rm(root, {recursive: true, force: true}); }
}
async function withGeneration(value, run) {
const previous = process.env.SEARCH_DATA_GENERATION;
if (value === undefined) delete process.env.SEARCH_DATA_GENERATION;
else process.env.SEARCH_DATA_GENERATION = value;
try { await run(); }
finally {
if (previous === undefined) delete process.env.SEARCH_DATA_GENERATION;
else process.env.SEARCH_DATA_GENERATION = previous;
}
}
async function snapshot(directory) {
const entries = (await readdir(directory, {recursive: true, withFileTypes: true}));
return Promise.all(entries.map(async entry => {
const path = join(entry.parentPath, entry.name);
return [path, entry.isSymbolicLink() ? "link" : entry.isDirectory() ? "directory" : hash(await readFile(path))];
}));
}
test("materialize complete Space data, then prepare the same generation entirely offline", async () => {
await withFixture(async f => {
await withGeneration(f.generation, async () => {
const result = await prepareTestData(f.out);
assert.deepEqual(result, {generation: f.generation, surface: "space", files: 12});
assert.equal(f.requests.length, 13);
for (const [name, member] of Object.entries(f.manifest.objects.space)) {
assert.deepEqual(await readFile(join(f.out, name)), f.bodies.get(member.object));
}
assert.deepEqual(JSON.parse(await readFile(join(f.out, "generation-manifest.json"))), f.manifest);
const before = await snapshot(f.out);
globalThis.fetch = () => { throw new Error("reuse must be offline"); };
assert.deepEqual(await prepareTestData(f.out), result);
assert.deepEqual(await snapshot(f.out), before);
assert.deepEqual(await readdir(f.root), ["data"]);
});
});
});
test("untrusted object name cannot replace a validated path or write outside the candidate", async () => {
await withFixture(async f => {
// objects is excluded from generation identity; malicious metadata still
// has otherwise valid hashes and member names and reaches the write loop.
f.manifest.objects.space["search_data.json.gz"].name = "../escape";
f.bodies.set(`generations/${f.generation}/manifest.json`, Buffer.from(JSON.stringify(f.manifest)));
await fetchSearchGeneration(f.generation, "space", f.out);
assert.deepEqual(await readdir(f.root), ["data"], "no escaped output");
assert.deepEqual(await readFile(join(f.out, "search_data.json.gz")),
f.bodies.get(f.manifest.objects.space["search_data.json.gz"].object));
globalThis.fetch = () => { throw new Error("reuse must be offline"); };
await ensureSearchGeneration(f.generation, "space", f.out);
assert.deepEqual(await readdir(f.root), ["data"]);
});
});
test("different generation is rejected offline without replacement", async () => {
await withFixture(async f => {
await fetchSearchGeneration(f.generation, "space", f.out);
const before = await snapshot(f.out);
globalThis.fetch = () => { throw new Error("must not fetch"); };
await withGeneration("a".repeat(64), async () => {
await assert.rejects(prepareTestData(f.out), /invalid search generation manifest/);
});
assert.deepEqual(await snapshot(f.out), before);
});
});
for (const fault of ["digest", "short", "oversized", "missing", "extra", "empty-directory",
"reader-assets", "reader-receipt", "member-link", "directory-link", "manifest-link", "manifest", "identity"]) {
test(`existing ${fault} generation fails closed without repair or network`, async () => {
await withFixture(async f => {
await fetchSearchGeneration(f.generation, "space", f.out);
const member = join(f.out, "initial/global.json");
if (fault === "digest") await writeFile(member, "X".repeat((await readFile(member)).length));
if (fault === "short") await writeFile(member, "X");
if (fault === "oversized") await writeFile(member, "X".repeat(1000));
if (fault === "missing") await rm(member);
if (fault === "extra") await writeFile(join(f.out, "initial/repos/Stale.json"), "{}");
if (fault === "empty-directory") await mkdir(join(f.out, "unknown"));
if (fault === "reader-assets") await writeFile(join(f.out, "reader_assets.json.gz"), "Reader");
if (fault === "reader-receipt") await writeFile(join(f.out, "reader_v3_receipt.json"), "{}");
if (fault === "member-link") { await rm(member); await symlink("manifest.json", member); }
if (fault === "directory-link") {
await rm(join(f.out, "initial"), {recursive: true});
await symlink("sidebar", join(f.out, "initial"));
}
if (fault === "manifest-link") {
await rm(join(f.out, "generation-manifest.json"));
await symlink("sidebar/global.json", join(f.out, "generation-manifest.json"));
}
if (fault === "manifest") await writeFile(join(f.out, "generation-manifest.json"), "{}");
if (fault === "identity") await writeFile(join(f.out, "generation-manifest.json"),
JSON.stringify({...f.manifest, injected: true}));
const before = await snapshot(f.out);
globalThis.fetch = () => { throw new Error("must not fetch"); };
await assert.rejects(ensureSearchGeneration(f.generation, "space", f.out),
/search member|ENOENT|invalid search generation manifest|search generation identity mismatch/);
assert.deepEqual(await snapshot(f.out), before);
assert.deepEqual(await readdir(f.root), ["data"]);
});
});
}
test("every declared member is hashed on reuse, including word and both ngram indexes", async () => {
await withFixture(async f => {
await fetchSearchGeneration(f.generation, "space", f.out);
globalThis.fetch = () => { throw new Error("must not fetch"); };
for (const [name, item] of Object.entries(f.manifest.objects.space)) {
const path = join(f.out, name), original = f.bodies.get(item.object);
await writeFile(path, "X".repeat(original.length));
await assert.rejects(ensureSearchGeneration(f.generation, "space", f.out), /search member mismatch/);
assert.equal(await readFile(path, "utf8"), "X".repeat(original.length));
await writeFile(path, original);
}
});
});
test("root symlinks and ordinary files are not reusable directories", async () => {
await withFixture(async f => {
await fetchSearchGeneration(f.generation, "space", f.out);
const link = join(f.root, "linked");
await symlink("data", link);
globalThis.fetch = () => { throw new Error("must not fetch"); };
await assert.rejects(ensureSearchGeneration(f.generation, "space", link), /must be a directory/);
await assert.rejects(ensureSearchGeneration(f.generation, "space", join(f.out, "search_data.json.gz")), /must be a directory/);
});
});
for (const fault of ["HTTP", "digest", "identity", "unsafe-path"]) {
test(`download ${fault} failure leaves no partial output and permits retry`, async () => {
await withFixture(async f => {
const name = ["identity", "unsafe-path"].includes(fault) ? `generations/${f.generation}/manifest.json`
: f.manifest.objects.space["sidebar/global.json"].object;
const original = f.bodies.get(name);
if (fault === "HTTP") f.bodies.delete(name);
if (fault === "digest") f.bodies.set(name, Buffer.from("X".repeat(original.length)));
if (fault === "identity") f.bodies.set(name, Buffer.from(JSON.stringify({...f.manifest, injected: true})));
if (fault === "unsafe-path") {
const manifest = structuredClone(f.manifest);
// Alter only the non-identity object map: it must fail member-list validation.
manifest.objects.space["../escape"] = manifest.objects.space["search_data.json.gz"];
f.bodies.set(name, Buffer.from(JSON.stringify(manifest)));
}
await assert.rejects(ensureSearchGeneration(f.generation, "space", f.out),
/search data HTTP|search member mismatch|search generation identity mismatch|search member list mismatch/);
assert.deepEqual(await readdir(f.root), []);
f.bodies.set(name, original);
await ensureSearchGeneration(f.generation, "space", f.out);
assert.deepEqual(await readdir(f.root), ["data"]);
});
});
}
test("prepare defaults to the published generation and rejects explicit empty/invalid overrides", async () => {
await withFixture(async f => {
await withGeneration(undefined, async () => {
await assert.rejects(prepareTestData(f.out), /search data HTTP 404/);
assert.deepEqual(f.requests, [`generations/${DEFAULT_GENERATION}/manifest.json`]);
});
f.requests.length = 0;
for (const generation of ["", "latest", "../escape"]) {
await withGeneration(generation, async () => {
await assert.rejects(prepareTestData(f.out), /invalid generation or surface/);
});
}
assert.deepEqual(f.requests, []);
assert.deepEqual(await readdir(f.root), []);
});
});
test("prepare CLI uses its default data directory, explicit output and explicit environment generation", async () => {
await withFixture(async f => {
await fetchSearchGeneration(f.generation, "space", f.out);
const script = fileURLToPath(new URL("../../scripts/data/prepare_test_data.mjs", import.meta.url));
const before = await snapshot(f.out);
for (const args of [[], [f.out]]) {
const result = spawnSync(process.execPath, [script, ...args], {cwd: f.root, encoding: "utf8", timeout: 10000,
env: {...process.env, SEARCH_DATA_GENERATION: f.generation}});
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(JSON.parse(result.stdout), {generation: f.generation, surface: "space", files: 12});
}
for (const [args, generation, error] of [
[[f.out], "", /invalid generation or surface/],
[[f.out], "a".repeat(64), /invalid search generation manifest/],
[[f.out, "extra"], f.generation, /usage:/],
]) {
const result = spawnSync(process.execPath, [script, ...args], {cwd: f.root, encoding: "utf8", timeout: 10000,
env: {...process.env, SEARCH_DATA_GENERATION: generation}});
assert.notEqual(result.status, 0);
assert.match(result.stderr, error);
assert.equal(result.stdout, "");
}
assert.deepEqual(await snapshot(f.out), before);
});
});
test("production fetch remains create-only even for the same valid generation", async () => {
await withFixture(async f => {
await fetchSearchGeneration(f.generation, "space", f.out);
const before = await snapshot(f.out);
await assert.rejects(fetchSearchGeneration(f.generation, "space", f.out), /output already exists/);
assert.deepEqual(await snapshot(f.out), before);
assert.deepEqual(await readdir(f.root), ["data"]);
});
});