/** * Making and deleting 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, dnsZonesCache, dnsRecordsCache } = await import("../src/db/schema.js"); const { and, eq } = await import("drizzle-orm"); 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; } const seen: Seen[] = []; let answer: { status: number; body: unknown } = { status: 200, body: null }; /** The zones the fake Technitium has. */ let zoneList: string[] = ["home.lan", "lab.lan", "1.168.192.in-addr.arpa"]; 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)); }; const path = (req.url ?? "").split("?")[0]; if (path === "/api/zones/list") return sendJson(200, { status: "ok", response: { zones: [...zoneList.map((name) => ({ name, type: "Primary" })), { name: "localhost", type: "Primary", internal: true }] } }); if (answer.body !== null) return sendJson(answer.status, answer.body); if (path === "/api/zones/delete") { zoneList = zoneList.filter((z) => z !== form.get("zone")); return sendJson(200, { status: "ok" }); } // 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((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("deleting a zone is a POST of its name to /api/zones/delete", async () => { reset(); zoneList = ["home.lan", "lab.lan"]; await adapter().deleteZone!("lab.lan"); assert.deepEqual([seen[0].method, seen[0].path, seen[0].auth], ["POST", "/api/zones/delete", "Bearer tok-1"]); assert.deepEqual(seen[0].form, { zone: "lab.lan" }); assert.deepEqual(zoneList, ["home.lan"]); answer = { status: 200, body: { status: "error", errorMessage: "Access was denied to use Zones: Delete" } }; await assert.rejects(() => adapter().deleteZone!("home.lan"), /Access was denied/); }); 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 remove = (id: number, zone: string, name: unknown, sub = "admin") => fetch(`${base}/providers/${id}/zones/${encodeURIComponent(zone)}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ name }) }); const reset = () => { seen.length = 0; answer = { status: 200, body: null }; zoneList = ["home.lan", "lab.lan", "1.168.192.in-addr.arpa"]; }; /** What this app has cached of a zone: the zone and two records. */ const cacheZone = async (providerId: number, zone: string) => { await db.insert(dnsZonesCache).values({ providerId, zoneId: zone, zoneName: zone, syncedAt: new Date().toISOString() }); await db.insert(dnsRecordsCache).values([ { providerId, zoneId: zone, recordId: `A||www.${zone}||10.0.0.5||`, type: "A", name: `www.${zone}`, content: "10.0.0.5", ttl: 3600, priority: null }, { providerId, zoneId: zone, recordId: `A||nas.${zone}||10.0.0.6||`, type: "A", name: `nas.${zone}`, content: "10.0.0.6", ttl: 3600, priority: null }, ]); }; const cached = async (providerId: number, zone: string) => ({ zones: (await db.select().from(dnsZonesCache).where(and(eq(dnsZonesCache.providerId, providerId), eq(dnsZonesCache.zoneId, zone)))).length, records: (await db.select().from(dnsRecordsCache).where(and(eq(dnsRecordsCache.providerId, providerId), eq(dnsRecordsCache.zoneId, zone)))).length, }); 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((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 and delete zones", async () => { const body = (await (await fetch(`${base}/providers`, { headers: as("viewer") })).json()) as { providers: { id: number; canCreateZones: boolean; canDeleteZones: boolean }[] }; const can = Object.fromEntries(body.providers.map((p) => [p.id, [p.canCreateZones, p.canDeleteZones]])); assert.deepEqual([can[technitium], can[disabled], can[cloudflare]], [[true, true], [true, true], [false, 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("deleting a zone: administrators only; nothing reaches Technitium for anyone else", async () => { reset(); for (const sub of ["viewer", "operator"]) assert.equal((await remove(technitium, "lab.lan", "lab.lan", sub)).status, 403, sub); assert.deepEqual(seen, []); assert.deepEqual(zoneList, ["home.lan", "lab.lan", "1.168.192.in-addr.arpa"]); }); test("the zone's name has to be sent and be the zone's name now; an id that is not a zone name, and a zone the provider does not list — its internal ones too — are refused", async () => { reset(); assert.equal((await remove(technitium, "lab.lan", undefined)).status, 400); assert.equal((await remove(technitium, "lab.lan", "")).status, 400); const wrong = await remove(technitium, "lab.lan", "home.lan"); assert.equal(wrong.status, 400); assert.equal(((await wrong.json()) as { error: string }).error, "name_mismatch"); for (const bad of ["Lab.LAN", "a b", "a/b", "lab.lan."]) assert.equal((await remove(technitium, bad, bad)).status, 400, bad); assert.equal((await remove(technitium, "nothere.lan", "nothere.lan")).status, 404); assert.equal((await remove(technitium, "localhost", "localhost")).status, 404, "an internal zone is not listed, so it is not deleted"); assert.deepEqual(seen.filter((s) => s.path.startsWith("/api/zones/delete")), []); assert.deepEqual(zoneList, ["home.lan", "lab.lan", "1.168.192.in-addr.arpa"]); }); test("a zone is deleted with the name typed; what this app cached of it goes too (and no other zone's), and the audit log says who deleted which and how many records were cached", async () => { reset(); await cacheZone(technitium, "lab.lan"); await cacheZone(technitium, "home.lan"); const res = await remove(technitium, "lab.lan", "lab.lan"); assert.equal(res.status, 204); assert.deepEqual(seen.filter((s) => s.path.startsWith("/api/zones/delete")).map((s) => s.form), [{ zone: "lab.lan" }]); assert.deepEqual(zoneList, ["home.lan", "1.168.192.in-addr.arpa"]); assert.deepEqual([await cached(technitium, "lab.lan"), await cached(technitium, "home.lan")], [{ zones: 0, records: 0 }, { zones: 1, records: 2 }]); const [entry] = (await db.select().from(auditLog)).filter((e) => e.action === "delete_zone"); assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["dns", "dns_zone", "lab.lan"]); assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { providerId: technitium, name: "lab.lan", cachedRecords: 2 }); }); test("a reverse zone is deleted by its arpa name", async () => { reset(); assert.equal((await remove(technitium, "1.168.192.in-addr.arpa", "1.168.192.in-addr.arpa")).status, 204); assert.deepEqual(zoneList, ["home.lan", "lab.lan"]); }); test("what Technitium says when it refuses is passed on; nothing is dropped from the cache and nothing is written in the audit log", async () => { reset(); await cacheZone(technitium, "guarded.lan"); zoneList.push("guarded.lan"); const entries = () => db.select().from(auditLog).then((rows) => rows.filter((e) => e.action === "delete_zone").length); const before = await entries(); answer = { status: 200, body: { status: "error", errorMessage: "Access was denied to use Zones: Delete" } }; const res = await remove(technitium, "guarded.lan", "guarded.lan"); assert.equal(res.status, 502); assert.match(((await res.json()) as { message: string }).message, /Access was denied/); assert.deepEqual(await cached(technitium, "guarded.lan"), { zones: 1, records: 2 }); assert.equal(await entries(), before); }); test("a provider that cannot delete zones, a switched-off one, an unknown one and an id that is no id are not asked", async () => { reset(); const unsupported = await remove(cloudflare, "home.lan", "home.lan"); assert.equal(unsupported.status, 400); assert.equal(((await unsupported.json()) as { error: string }).error, "not_supported"); assert.equal(((await (await remove(disabled, "home.lan", "home.lan")).json()) as { error: string }).error, "provider_disabled"); assert.equal((await remove(999999, "home.lan", "home.lan")).status, 404); assert.equal((await fetch(`${base}/providers/abc/zones/home.lan`, { method: "DELETE", headers: as("admin"), body: JSON.stringify({ 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); }); });