A New zone form on a Technitium DNS provider makes a Primary zone (a domain name, or an address or network for a reverse zone), a Secondary zone (from the servers that hold it) or a Forwarder zone (where to pass questions, the protocol, DNSSEC). Names are written lower case, ASCII, without the trailing dot and refused before Technitium is asked if they are not zone names; Technitium's own refusal (a zone that exists) is shown as it was said. Administrators only, audited, and only for providers that can (the adapter gets an optional createZone). The new zone opens when it is made. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
266 lines
14 KiB
TypeScript
266 lines
14 KiB
TypeScript
/**
|
|
* Making a zone on a Technitium DNS provider: the names that are zone names, what is sent to Technitium for each kind of zone (Primary, Secondary, Forwarder), that only an administrator may, what
|
|
* is refused before Technitium is asked, what is passed on when it refuses, and what is written in the audit log.
|
|
*
|
|
* Run with: npm test --workspace server
|
|
*/
|
|
import { test, describe, before, after } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { createServer as createHttpServer, type Server } from "node:http";
|
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import type { AddressInfo } from "node:net";
|
|
|
|
const dir = mkdtempSync(join(tmpdir(), "hm-tn-zones-"));
|
|
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
|
process.env.SESSION_DIR = join(dir, "sessions");
|
|
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
|
|
|
const express = (await import("express")).default;
|
|
const { db } = await import("../src/db/client.js");
|
|
const { users, dnsProviders, integrationCredentials, auditLog } = await import("../src/db/schema.js");
|
|
const { runMigrations } = await import("../src/db/migrate.js");
|
|
const { encryptSecret } = await import("../src/crypto.js");
|
|
const { normaliseZoneName } = await import("../src/dns/zoneNames.js");
|
|
const { createTechnitiumAdapter } = await import("../src/dns/adapters/technitium.js");
|
|
const { dnsRouter } = await import("../src/routes/dns.js");
|
|
|
|
await runMigrations();
|
|
|
|
describe("what a zone is called", () => {
|
|
test("a domain name, one label or many, in lower case without the trailing dot", () => {
|
|
assert.equal(normaliseZoneName("Home.LAN."), "home.lan");
|
|
assert.equal(normaliseZoneName(" lan "), "lan");
|
|
assert.equal(normaliseZoneName("a-b_c.example.com"), "a-b_c.example.com");
|
|
assert.equal(normaliseZoneName("xn--bcher-kva.example"), "xn--bcher-kva.example");
|
|
assert.equal(normaliseZoneName("1.168.192.in-addr.arpa"), "1.168.192.in-addr.arpa");
|
|
});
|
|
|
|
test("a reverse zone is an address or a network: IPv4 up to /32, IPv6 up to /128", () => {
|
|
assert.equal(normaliseZoneName("192.168.1.0/24"), "192.168.1.0/24");
|
|
assert.equal(normaliseZoneName("192.168.1.5"), "192.168.1.5");
|
|
assert.equal(normaliseZoneName("FD00::/8"), "fd00::/8");
|
|
assert.equal(normaliseZoneName("192.168.1.0/33"), null);
|
|
assert.equal(normaliseZoneName("fd00::/129"), null);
|
|
assert.equal(normaliseZoneName("300.1.1.1/24"), null);
|
|
});
|
|
|
|
test("what is not a name is refused: empty, spaces, a leading or doubled dot, a wildcard, other letters, a label that is too long, a name that is too long, anything to do with a path", () => {
|
|
for (const bad of ["", " ", "a b.lan", ".lan", "a..lan", "*.lan", "bücher.example", "-a.lan", "a-.lan", `${"a".repeat(64)}.lan`, `${"a.".repeat(130)}lan`, "../etc", "a/b", "home.lan/../x", "a;b.lan", "https://home.lan"]) {
|
|
assert.equal(normaliseZoneName(bad), null, JSON.stringify(bad));
|
|
}
|
|
});
|
|
});
|
|
|
|
interface Seen {
|
|
method: string;
|
|
path: string;
|
|
auth: string;
|
|
type: string;
|
|
form: Record<string, string>;
|
|
}
|
|
const seen: Seen[] = [];
|
|
let answer: { status: number; body: unknown } = { status: 200, body: null };
|
|
|
|
let fake: Server;
|
|
let fakeUrl = "";
|
|
|
|
before(async () => {
|
|
fake = createHttpServer((req, res) => {
|
|
let body = "";
|
|
req.on("data", (c) => (body += c));
|
|
req.on("end", () => {
|
|
seen.push({ method: req.method ?? "", path: req.url ?? "", auth: String(req.headers.authorization ?? ""), type: String(req.headers["content-type"] ?? ""), form: Object.fromEntries(new URLSearchParams(body)) });
|
|
const form = new URLSearchParams(body);
|
|
const sendJson = (status: number, json: unknown) => {
|
|
res.writeHead(status, { "content-type": "application/json" });
|
|
res.end(JSON.stringify(json));
|
|
};
|
|
if (answer.body !== null) return sendJson(answer.status, answer.body);
|
|
// The domain a reverse zone is made as.
|
|
const zone = form.get("zone") ?? "";
|
|
const reverse = /^(\d+)\.(\d+)\.(\d+)\.0\/24$/.exec(zone);
|
|
return sendJson(200, { status: "ok", response: { domain: reverse ? `${reverse[3]}.${reverse[2]}.${reverse[1]}.in-addr.arpa` : zone } });
|
|
});
|
|
});
|
|
await new Promise<void>((resolve) => fake.listen(0, "127.0.0.1", resolve));
|
|
fakeUrl = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`;
|
|
});
|
|
after(() => {
|
|
fake.close();
|
|
});
|
|
|
|
describe("what is sent to Technitium", () => {
|
|
const adapter = () => createTechnitiumAdapter({ url: `${fakeUrl}/`, token: "tok-1" });
|
|
const reset = () => {
|
|
seen.length = 0;
|
|
answer = { status: 200, body: null };
|
|
};
|
|
|
|
test("a Primary zone is a POST of the name and the type, with the token in the Authorization header", async () => {
|
|
reset();
|
|
const zone = await adapter().createZone!({ type: "Primary", name: "home.lan" });
|
|
assert.deepEqual(zone, { id: "home.lan", name: "home.lan" });
|
|
assert.deepEqual([seen[0].method, seen[0].path, seen[0].auth, seen[0].type], ["POST", "/api/zones/create", "Bearer tok-1", "application/x-www-form-urlencoded"]);
|
|
assert.deepEqual(seen[0].form, { zone: "home.lan", type: "Primary" });
|
|
});
|
|
|
|
test("a Secondary zone adds the servers that hold it, comma-separated", async () => {
|
|
reset();
|
|
await adapter().createZone!({ type: "Secondary", name: "lab.lan", primaryNameServers: ["10.0.0.2", "ns.lab.lan"] });
|
|
assert.deepEqual(seen[0].form, { zone: "lab.lan", type: "Secondary", primaryNameServerAddresses: "10.0.0.2,ns.lab.lan" });
|
|
});
|
|
|
|
test("a Forwarder zone adds where questions go, how, and whether to validate DNSSEC; the forwarder is set up with the zone", async () => {
|
|
reset();
|
|
await adapter().createZone!({ type: "Forwarder", name: "corp.example", forwarder: "10.1.1.1", protocol: "Tls", dnssecValidation: true });
|
|
assert.deepEqual(seen[0].form, { zone: "corp.example", type: "Forwarder", initializeForwarder: "true", forwarder: "10.1.1.1", protocol: "Tls", dnssecValidation: "true" });
|
|
});
|
|
|
|
test("the zone is the name Technitium gives back: a reverse zone is the arpa name", async () => {
|
|
reset();
|
|
const zone = await adapter().createZone!({ type: "Primary", name: "192.168.1.0/24" });
|
|
assert.deepEqual(zone, { id: "1.168.192.in-addr.arpa", name: "1.168.192.in-addr.arpa" });
|
|
assert.equal(seen[0].form.zone, "192.168.1.0/24");
|
|
});
|
|
|
|
test("what Technitium says when it refuses is the error; so is a token it does not accept", async () => {
|
|
reset();
|
|
answer = { status: 200, body: { status: "error", errorMessage: "Zone already exists: home.lan" } };
|
|
await assert.rejects(() => adapter().createZone!({ type: "Primary", name: "home.lan" }), /Zone already exists: home\.lan/);
|
|
answer = { status: 200, body: { status: "invalid-token" } };
|
|
await assert.rejects(() => adapter().createZone!({ type: "Primary", name: "home.lan" }), /Invalid or expired Technitium API token/);
|
|
});
|
|
});
|
|
|
|
describe("the route", () => {
|
|
let app: Server;
|
|
let base = "";
|
|
let technitium = 0;
|
|
let disabled = 0;
|
|
let cloudflare = 0;
|
|
|
|
const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub });
|
|
const make = (id: number, body: unknown, sub = "admin") => fetch(`${base}/providers/${id}/zones`, { method: "POST", headers: as(sub), body: JSON.stringify(body) });
|
|
const reset = () => {
|
|
seen.length = 0;
|
|
answer = { status: 200, body: null };
|
|
};
|
|
|
|
before(async () => {
|
|
await db.insert(users).values([
|
|
{ oidcSub: "admin", name: "Alma", role: "admin" },
|
|
{ oidcSub: "operator", name: "Olle", role: "operator" },
|
|
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
|
|
]);
|
|
const cred = (await db.insert(integrationCredentials).values({ name: "dns:technitium", encryptedSecret: encryptSecret(JSON.stringify({ token: "tok-route" })) }).returning({ id: integrationCredentials.id }))[0];
|
|
const config = JSON.stringify({ url: fakeUrl });
|
|
technitium = (await db.insert(dnsProviders).values({ providerType: "technitium", name: "Home DNS", credentialId: cred.id, config }).returning({ id: dnsProviders.id }))[0].id;
|
|
disabled = (await db.insert(dnsProviders).values({ providerType: "technitium", name: "Old DNS", credentialId: cred.id, config, enabled: false }).returning({ id: dnsProviders.id }))[0].id;
|
|
cloudflare = (await db.insert(dnsProviders).values({ providerType: "cloudflare", name: "Cloudflare", config: "{}" }).returning({ id: dnsProviders.id }))[0].id;
|
|
const a = express();
|
|
a.use(express.json());
|
|
a.use((req, _res, next) => {
|
|
(req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } };
|
|
next();
|
|
});
|
|
a.use("/api/dns", dnsRouter);
|
|
app = await new Promise<Server>((resolve) => {
|
|
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
|
});
|
|
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/dns`;
|
|
});
|
|
after(() => {
|
|
app.close();
|
|
try {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
} catch {
|
|
// Windows keeps the database file locked until the process exits.
|
|
}
|
|
});
|
|
|
|
test("the providers say which can make zones", async () => {
|
|
const body = (await (await fetch(`${base}/providers`, { headers: as("viewer") })).json()) as { providers: { id: number; canCreateZones: boolean }[] };
|
|
const can = Object.fromEntries(body.providers.map((p) => [p.id, p.canCreateZones]));
|
|
assert.deepEqual([can[technitium], can[disabled], can[cloudflare]], [true, true, false]);
|
|
});
|
|
|
|
test("only an administrator makes a zone; nothing reaches Technitium for anyone else", async () => {
|
|
reset();
|
|
for (const sub of ["viewer", "operator"]) assert.equal((await make(technitium, { type: "Primary", name: "home.lan" }, sub)).status, 403, sub);
|
|
assert.deepEqual(seen, []);
|
|
});
|
|
|
|
test("a zone is made with the name as Technitium should have it, and the audit log says who made which", async () => {
|
|
reset();
|
|
const res = await make(technitium, { type: "Primary", name: " Home.LAN. " });
|
|
assert.equal(res.status, 201);
|
|
assert.deepEqual(((await res.json()) as { zone: unknown }).zone, { id: "home.lan", name: "home.lan" });
|
|
assert.deepEqual(seen.map((s) => s.form), [{ zone: "home.lan", type: "Primary" }]);
|
|
assert.equal(seen[0].auth, "Bearer tok-route");
|
|
const [entry] = (await db.select().from(auditLog)).filter((e) => e.action === "create_zone");
|
|
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["dns", "dns_zone", "home.lan"]);
|
|
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { providerId: technitium, name: "home.lan", type: "Primary" });
|
|
});
|
|
|
|
test("a Secondary zone and a Forwarder zone take what they need; a Forwarder's protocol is UDP and its DNSSEC check off unless said", async () => {
|
|
reset();
|
|
assert.equal((await make(technitium, { type: "Secondary", name: "lab.lan", primaryNameServers: [" 10.0.0.2 ", "ns.lab.lan"] })).status, 201);
|
|
assert.equal((await make(technitium, { type: "Forwarder", name: "corp.example", forwarder: "10.1.1.1" })).status, 201);
|
|
assert.deepEqual(seen.map((s) => s.form), [
|
|
{ zone: "lab.lan", type: "Secondary", primaryNameServerAddresses: "10.0.0.2,ns.lab.lan" },
|
|
{ zone: "corp.example", type: "Forwarder", initializeForwarder: "true", forwarder: "10.1.1.1", protocol: "Udp", dnssecValidation: "false" },
|
|
]);
|
|
const entries = (await db.select().from(auditLog)).filter((e) => e.action === "create_zone" && /corp\.example/.test(e.detail ?? ""));
|
|
assert.equal(JSON.parse(entries[0].detail ?? "{}").forwarder, "10.1.1.1");
|
|
});
|
|
|
|
test("what is wrong with the zone is said before Technitium is asked", async () => {
|
|
reset();
|
|
const bad: unknown[] = [
|
|
{},
|
|
{ type: "Primary" },
|
|
{ type: "Primary", name: "" },
|
|
{ type: "Primary", name: "not a name" },
|
|
{ type: "Primary", name: "../x" },
|
|
{ type: "Primary", name: "*.lan" },
|
|
{ type: "Secondary", name: "lab.lan" },
|
|
{ type: "Secondary", name: "lab.lan", primaryNameServers: [] },
|
|
{ type: "Secondary", name: "lab.lan", primaryNameServers: ["a b"] },
|
|
{ type: "Secondary", name: "lab.lan", primaryNameServers: Array.from({ length: 11 }, (_, i) => `10.0.0.${i}`) },
|
|
{ type: "Forwarder", name: "corp.example" },
|
|
{ type: "Forwarder", name: "corp.example", forwarder: "a b" },
|
|
{ type: "Forwarder", name: "corp.example", forwarder: "10.1.1.1", protocol: "Carrier-pigeon" },
|
|
{ type: "Stub", name: "x.lan" },
|
|
];
|
|
for (const body of bad) {
|
|
const res = await make(technitium, body);
|
|
assert.equal(res.status, 400, JSON.stringify(body));
|
|
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
|
|
}
|
|
assert.deepEqual(seen, []);
|
|
});
|
|
|
|
test("a provider that cannot make zones, a switched-off one, an unknown one and an id that is no id are not asked", async () => {
|
|
reset();
|
|
const unsupported = await make(cloudflare, { type: "Primary", name: "home.lan" });
|
|
assert.equal(unsupported.status, 400);
|
|
assert.equal(((await unsupported.json()) as { error: string }).error, "not_supported");
|
|
assert.equal(((await (await make(disabled, { type: "Primary", name: "home.lan" })).json()) as { error: string }).error, "provider_disabled");
|
|
assert.equal((await make(999999, { type: "Primary", name: "home.lan" })).status, 404);
|
|
assert.equal((await fetch(`${base}/providers/abc/zones`, { method: "POST", headers: as("admin"), body: JSON.stringify({ type: "Primary", name: "home.lan" }) })).status, 400);
|
|
assert.deepEqual(seen, []);
|
|
});
|
|
|
|
test("what Technitium says when it refuses is passed on, and nothing is written in the audit log", async () => {
|
|
reset();
|
|
const before = (await db.select().from(auditLog)).filter((e) => e.action === "create_zone").length;
|
|
answer = { status: 200, body: { status: "error", errorMessage: "Zone already exists: home.lan" } };
|
|
const res = await make(technitium, { type: "Primary", name: "home.lan" });
|
|
assert.equal(res.status, 502);
|
|
assert.match(((await res.json()) as { message: string }).message, /Zone already exists: home\.lan/);
|
|
assert.equal((await db.select().from(auditLog)).filter((e) => e.action === "create_zone").length, before);
|
|
});
|
|
});
|