Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

6.8 KB
Raw Blame
import { describe, expect, it } from "vitest";

import { createNameLookup, hasPublicIpv6, type NameAddress } from "./names.ts";

const coded = (code: string) => Object.assign(new Error(code), { code });
const never = <T>() => new Promise<T>(() => {});

describe("the gates' name lookup", () => {
  it("asks the name servers for both families and lists IPv6 first on a machine with a routable IPv6 address", async () => {
    const asked: string[] = [];
    const lookup = createNameLookup({
      ipv6First: () => true,
      query: async (host, family) => { asked.push(`${host}/${family}`); return family === 4 ? ["203.0.113.7"] : ["2001:db8::7"]; },
      system: async () => { throw new Error("the system lookup is not asked when the name servers answer"); },
    });
    expect(await lookup("Example.COM.")).toEqual([{ address: "2001:db8::7", family: 6 }, { address: "203.0.113.7", family: 4 }]);
    expect(asked.sort()).toEqual(["example.com/4", "example.com/6"]);
  });

  it("reuses an answer for a minute, then asks again", async () => {
    let time = 1_000, asks = 0;
    const lookup = createNameLookup({
      now: () => time,
      query: async (_host, family) => { if (family === 4) asks += 1; return family === 4 ? [`203.0.113.${asks}`] : []; },
    });
    expect(await lookup("example.com")).toEqual([{ address: "203.0.113.1", family: 4 }]);
    time += 59_000;
    expect(await lookup("example.com")).toEqual([{ address: "203.0.113.1", family: 4 }]);
    expect(asks).toBe(1);
    time += 2_000;
    expect(await lookup("example.com")).toEqual([{ address: "203.0.113.2", family: 4 }]);
  });

  it("asks once for callers that arrive together", async () => {
    let asks = 0;
    let answer!: (addresses: string[]) => void;
    const lookup = createNameLookup({
      query: (_host, family) => family === 6 ? Promise.reject(coded("ENODATA")) : new Promise((resolve) => { asks += 1; answer = resolve; }),
    });
    const both = Promise.all([lookup("example.com"), lookup("example.com"), lookup("EXAMPLE.com")]);
    await new Promise((resolve) => setImmediate(resolve));
    answer(["203.0.113.7"]);
    expect(await both).toEqual(Array.from({ length: 3 }, () => [{ address: "203.0.113.7", family: 4 }]));
    expect(asks).toBe(1);
  });

  it("uses the last answer while the name servers are silent, without asking the system lookup, and for a quarter hour only", async () => {
    let time = 1_000, silent = false, systemAsks = 0;
    const lookup = createNameLookup({
      now: () => time,
      waitMs: 30,
      query: (_host, family) => silent ? never<string[]>() : Promise.resolve(family === 4 ? ["203.0.113.7"] : []),
      system: async () => { systemAsks += 1; return []; },
    });
    expect(await lookup("api.example.com")).toHaveLength(1);
    silent = true;
    time += 5 * 60_000;
    const started = Date.now();
    expect(await lookup("api.example.com")).toEqual([{ address: "203.0.113.7", family: 4 }]);
    expect(Date.now() - started).toBeLessThan(2_000);
    expect(lookup.stale).toBe(1);
    time += 11 * 60_000;
    expect(await lookup("api.example.com")).toEqual([]);
    expect(await lookup("never-seen.example.com")).toEqual([]);
    expect(systemAsks).toBe(0);
  });

  it("a name server error other than 'no such record' also leaves the system lookup alone", async () => {
    let systemAsks = 0;
    const lookup = createNameLookup({
      query: () => Promise.reject(coded("ESERVFAIL")),
      system: async () => { systemAsks += 1; return [{ address: "203.0.113.9", family: 4 }]; },
    });
    expect(await lookup("example.com")).toEqual([]);
    expect(systemAsks).toBe(0);
  });

  it("asks the system lookup for a name the name servers do not have, so the hosts file still works", async () => {
    const local: NameAddress[] = [{ address: "203.0.113.20", family: 4 }];
    const lookup = createNameLookup({
      query: (_host, family) => Promise.reject(coded(family === 4 ? "ENOTFOUND" : "ENODATA")),
      system: async (host) => host === "build-box" ? local : [],
    });
    expect(await lookup("build-box")).toEqual(local);
    expect(await lookup("no-such-name.invalid")).toEqual([]);
  });

  it("a system lookup that never returns does not hold the caller", async () => {
    const lookup = createNameLookup({ waitMs: 30, query: () => Promise.reject(coded("ENOTFOUND")), system: () => never<NameAddress[]>() });
    const started = Date.now();
    expect(await lookup("build-box")).toEqual([]);
    expect(Date.now() - started).toBeLessThan(2_000);
  });

  it("a query that throws at once is an unanswered one", async () => {
    const lookup = createNameLookup({ query: () => { throw coded("EBADNAME"); }, system: async () => [] });
    expect(await lookup("bad host name")).toEqual([]);
    expect(await lookup("")).toEqual([]);
  });

  it("keeps no more names than its limit", async () => {
    let asks = 0;
    const lookup = createNameLookup({ maxNames: 2, query: async (_host, family) => { if (family === 4) asks += 1; return family === 4 ? ["203.0.113.7"] : []; } });
    await lookup("a.example"); await lookup("b.example"); await lookup("c.example");
    expect(asks).toBe(3);
    await lookup("c.example"); await lookup("b.example");
    expect(asks).toBe(3);
    await lookup("a.example");
    expect(asks).toBe(4);
  });

  it("lists IPv4 first on a machine with no routable IPv6 address, for the callers that connect to the first address only", async () => {
    const lookup = createNameLookup({ ipv6First: () => false, query: async (_host, family) => family === 4 ? ["203.0.113.7"] : ["2001:db8::7"] });
    expect(await lookup("example.com")).toEqual([{ address: "203.0.113.7", family: 4 }, { address: "2001:db8::7", family: 6 }]);
  });

  it("counts only a routable IPv6 address: not loopback, link-local or a private one", () => {
    const entry = (address: string, family: "IPv4" | "IPv6", internal = false) => ({ address, family, internal, netmask: "", mac: "", cidr: null }) as never;
    expect(hasPublicIpv6({ lo: [entry("::1", "IPv6", true)], eth0: [entry("10.0.0.5", "IPv4"), entry("fe80::1", "IPv6"), entry("fd00::5", "IPv6")] })).toBe(false);
    expect(hasPublicIpv6({ eth0: [entry("2a01:4f8:c0c::1", "IPv6")] })).toBe(true);
    expect(hasPublicIpv6({})).toBe(false);
  });

  it("makes its resolver again after a round nobody answered, and not after an answer or a 'no such record'", async () => {
    let renewed = 0, mode: "silent" | "answer" | "missing" = "silent";
    const lookup = createNameLookup({
      waitMs: 30, freshMs: 0, renew: () => { renewed += 1; },
      query: () => mode === "silent" ? never<string[]>() : mode === "answer" ? Promise.resolve(["203.0.113.7"]) : Promise.reject(coded("ENOTFOUND")),
      system: async () => [],
    });
    await lookup("example.com");
    expect(renewed).toBe(1);
    mode = "answer"; await lookup("example.com");
    mode = "missing"; await lookup("other.example");
    expect(renewed).toBe(1);
  });
});