/** * Tests for ai-kit/web. * * Written against the CONTRACT rather than the implementation, deliberately. * The failure this package has already lived through once is a regression test * that asserted the buggy behaviour as expected and therefore went green while * shipping data loss. So each test below states a rule in the terms a reader * would state it ("a redirect into a private network is refused"), and would * fail against a plausible WRONG implementation — not merely against a changed * one. * * Three properties carry most of the weight: * * - The SSRF guard must hold on EVERY redirect hop, not just the first URL. * A guard that checks the input string and then lets `fetch` follow a 302 * is no guard at all, and it passes any test that only feeds it URLs. * - "Found nothing" and "could not look" must stay distinguishable all the * way to the model-facing sentence. * - A citation handle must address the evidence block it claims to. */ import { test } from "node:test"; import assert from "node:assert/strict"; import { isPrivateAddress, validateFetchTarget, readPage, extractReadableText, webSearch, describeAttempts, resultsToFacts, resultsEvidence, pageToFact, pageEvidence, describeEmptySearch, searxngProvider, braveProvider, tavilyProvider, defaultProviders, } from "@bitbaum/ai-kit/web"; import { assignFactIds, verifyAnswer, NOT_RECORDED } from "@bitbaum/ai-kit/grounding"; // ── the address judgement ──────────────────────────────────────────────────── test("every non-public IPv4 range is refused", () => { for (const addr of [ "127.0.0.1", "10.1.2.3", "172.16.0.1", "172.31.255.255", "192.168.1.1", "169.254.169.254", // the cloud metadata service — the one that matters most "0.0.0.0", "100.64.0.1", // carrier-grade NAT "192.0.0.1", "198.18.0.1", "224.0.0.1", "255.255.255.255", ]) { assert.equal(isPrivateAddress(addr), true, `${addr} should be refused`); } }); test("ordinary public addresses are allowed", () => { for (const addr of ["1.1.1.1", "8.8.8.8", "167.233.22.31", "172.32.0.1", "100.128.0.1"]) { assert.equal(isPrivateAddress(addr), false, `${addr} should be allowed`); } }); test("IPv6 spellings of a private address are refused too", () => { for (const addr of [ "::1", "::", "fe80::1", "fc00::1", "fd12:3456::1", "ff02::1", "::ffff:127.0.0.1", // IPv4-mapped loopback "::ffff:10.0.0.1", "2002:7f00:0001::", // 6to4 wrapping 127.0.0.1 "64:ff9b::7f00:1", // NAT64 wrapping 127.0.0.1 ]) { assert.equal(isPrivateAddress(addr), true, `${addr} should be refused`); } assert.equal(isPrivateAddress("2606:4700:4700::1111"), false); }); test("anything that is not a parseable address is refused, not allowed by default", () => { for (const junk of ["", "localhost", "not-an-ip", "999.1.1.1", "0x7f000001"]) { assert.equal(isPrivateAddress(junk), true, `${junk} should be refused`); } }); test("a hostname resolving to one public AND one private address is refused", async () => { // DNS rebinding with the work already done: checking only the first record // would let this through, which is why the guard checks every one. const verdict = await validateFetchTarget("https://mixed.example", async () => [ { address: "93.184.216.34" }, { address: "127.0.0.1" }, ]); assert.equal(verdict.ok, false); assert.match(verdict.reason, /private network/i); }); test("URL shape is judged before the network is touched", async () => { const never = async () => { throw new Error("DNS must not be consulted for a URL that cannot be fetched anyway"); }; assert.equal((await validateFetchTarget("file:///etc/passwd", never)).ok, false); assert.equal((await validateFetchTarget("gopher://example.com", never)).ok, false); assert.equal((await validateFetchTarget("https://example.com:5432/", never)).ok, false); assert.equal((await validateFetchTarget("https://user:pw@example.com/", never)).ok, false); assert.equal((await validateFetchTarget("not a url", never)).ok, false); }); test("a literal public address needs no resolver, and a literal private one is still refused", async () => { const never = async () => { throw new Error( "a literal address must not be resolved — the resolver would just echo it back", ); }; const good = await validateFetchTarget("https://1.1.1.1/", never); assert.equal(good.ok, true); assert.deepEqual(good.addresses, ["1.1.1.1"]); const bad = await validateFetchTarget("http://169.254.169.254/latest/meta-data/", never); assert.equal(bad.ok, false); }); // ── the reader ─────────────────────────────────────────────────────────────── const publicLookup = async () => [{ address: "93.184.216.34" }]; function htmlResponse(body, extra = {}) { return new Response(body, { status: 200, headers: { "content-type": "text/html; charset=utf-8" }, ...extra, }); } test("a redirect into a private network is refused AT THE HOP", async () => { // The crown jewel. The first URL is impeccable; the redirect is the attack. // An implementation that validates the input and then hands the rest to // fetch's own redirect following passes every other test in this file. let hops = 0; const fetchImpl = async (url) => { hops++; if (hops === 1) { assert.equal(url, "https://innocent.example/"); return new Response(null, { status: 302, headers: { location: "http://127.0.0.1:80/admin" }, }); } throw new Error("the guard let a private address through"); }; const lookup = async (hostname) => hostname === "innocent.example" ? [{ address: "93.184.216.34" }] : [{ address: "127.0.0.1" }]; const outcome = await readPage("https://innocent.example/", {}, { fetch: fetchImpl, lookup }); assert.equal(outcome.ok, false); assert.equal(outcome.failure.kind, "blocked"); assert.equal(hops, 1, "the second request must never have been made"); }); test("a relative redirect is resolved against the hop it came from", async () => { const seen = []; const fetchImpl = async (url) => { seen.push(url); if (seen.length === 1) { return new Response(null, { status: 301, headers: { location: "/moved" } }); } return htmlResponse("
Arrived.
"); }; const outcome = await readPage( "https://example.com/start", {}, { fetch: fetchImpl, lookup: publicLookup }, ); assert.equal(outcome.ok, true); assert.equal(seen[1], "https://example.com/moved"); assert.equal(outcome.title, "Here"); }); test("a redirect loop ends in a refusal rather than running forever", async () => { let calls = 0; const fetchImpl = async () => { calls++; return new Response(null, { status: 302, headers: { location: "https://example.com/again" } }); }; const outcome = await readPage( "https://example.com/a", {}, { fetch: fetchImpl, lookup: publicLookup }, ); assert.equal(outcome.ok, false); assert.ok(calls <= 5, `bounded, got ${calls} requests`); }); test("a non-page content type is refused unread, naming what it was", async () => { const fetchImpl = async () => new Response("%PDF-1.7", { status: 200, headers: { "content-type": "application/pdf" } }); const outcome = await readPage( "https://example.com/a.pdf", {}, { fetch: fetchImpl, lookup: publicLookup }, ); assert.equal(outcome.ok, false); assert.match(outcome.failure.reason, /application\/pdf/); }); test("HTTP failures are classified, not lumped together", async () => { const cases = [ [429, "rate_limited"], [403, "blocked"], [500, "bad_response"], ]; for (const [status, kind] of cases) { const fetchImpl = async () => new Response("no", { status }); const outcome = await readPage( "https://example.com/", {}, { fetch: fetchImpl, lookup: publicLookup }, ); assert.equal(outcome.ok, false); assert.equal(outcome.failure.kind, kind, `${status} should be ${kind}`); } }); test("a timeout is reported as a timeout, and never as an empty page", async () => { const fetchImpl = async () => { const err = new Error("The operation was aborted due to timeout"); err.name = "TimeoutError"; throw err; }; const outcome = await readPage( "https://example.com/", {}, { fetch: fetchImpl, lookup: publicLookup }, ); assert.equal(outcome.ok, false); assert.equal(outcome.failure.kind, "timeout"); }); test("truncation is stated, not silent", async () => { const long = `Real words.
`, ); assert.ok(!text.includes("TOKEN123"), "script body leaked into the text"); assert.ok(!text.includes("color:red"), "stylesheet leaked into the text"); assert.match(text, /Real words\./); }); test("an unclosed script does not drag the rest of the page in with it", () => { const { text } = extractReadableText(`Before.