Make Technitium zones from the DNS page
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>
This commit is contained in:
1 parent
f73704e6ca
commit
0244f5a8ab
12 files changed
+533
-10
No files matched your search
@@ -4,8 +4,11 @@
|
||||
*
|
||||
* API docs: https://github.com/TechnitiumSoftware/DnsServer/blob/master/APIDOCS.md
|
||||
* Record ID format: "type||name||content||priority"
|
||||
*
|
||||
* Making a zone is `/api/zones/create` (permission "Zones: Modify"): the name and the type, and for a Secondary zone its primary servers, for a Forwarder zone the address to pass questions to, the
|
||||
* protocol to use and whether to validate DNSSEC. It answers with the name of the zone it made (`response.domain` — for a reverse zone the …arpa name). Not checked against a live server.
|
||||
*/
|
||||
import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone } from "../types.js";
|
||||
import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone, NewDnsZone } from "../types.js";
|
||||
import { withDiagLogging } from "../../services/diagLog.js";
|
||||
|
||||
export interface TechnitiumConfig {
|
||||
@@ -96,6 +99,20 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
|
||||
return { type, name, content, priority: priorityStr ? parseInt(priorityStr, 10) : undefined };
|
||||
}
|
||||
|
||||
async function createZone(zone: NewDnsZone): Promise<DnsZone> {
|
||||
const params: Record<string, string> = { zone: zone.name, type: zone.type };
|
||||
if (zone.type === "Secondary") params.primaryNameServerAddresses = zone.primaryNameServers.join(",");
|
||||
if (zone.type === "Forwarder") {
|
||||
params.initializeForwarder = "true";
|
||||
params.forwarder = zone.forwarder;
|
||||
params.protocol = zone.protocol;
|
||||
params.dnssecValidation = String(zone.dnssecValidation);
|
||||
}
|
||||
const resp = await apiPost("/api/zones/create", params);
|
||||
const made = typeof resp?.domain === "string" && resp.domain.trim() !== "" ? resp.domain.trim() : zone.name;
|
||||
return { id: made, name: made };
|
||||
}
|
||||
|
||||
async function listZones(): Promise<DnsZone[]> {
|
||||
const resp = await apiGet("/api/zones/list");
|
||||
const zones = resp?.zones ?? [];
|
||||
@@ -149,5 +166,5 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
|
||||
await apiPost("/api/zones/records/delete", { domain: name, zone, type, ...typeParams });
|
||||
}
|
||||
|
||||
return withDiagLogging("technitium", { listZones, listRecords, addRecord, updateRecord, deleteRecord });
|
||||
return withDiagLogging("technitium", { listZones, createZone, listRecords, addRecord, updateRecord, deleteRecord });
|
||||
}
|
||||
@@ -7,6 +7,9 @@ import { createAzureAdapter } from "./adapters/azure.js";
|
||||
import { createCpanelAdapter } from "./adapters/cpanel.js";
|
||||
import { createTechnitiumAdapter } from "./adapters/technitium.js";
|
||||
|
||||
/** The kinds of provider whose adapter can make a zone: the page offers "New zone" for these, and the route refuses it for the others. */
|
||||
export const ZONE_CREATING_PROVIDERS: ReadonlySet<DnsProviderType> = new Set<DnsProviderType>(["technitium"]);
|
||||
|
||||
export function createDnsAdapter(providerType: DnsProviderType, config: DnsProviderConfig): DnsAdapter {
|
||||
switch (providerType) {
|
||||
case "cloudflare":
|
||||
|
||||
@@ -22,8 +22,16 @@ export interface DnsRecordInput {
|
||||
proxied?: boolean;
|
||||
}
|
||||
|
||||
/** A zone to be made. Primary: this server holds it. Secondary: a copy of one a primary server holds. Forwarder: questions about the name are passed on to another DNS server. */
|
||||
export type NewDnsZone =
|
||||
| { type: "Primary"; name: string }
|
||||
| { type: "Secondary"; name: string; primaryNameServers: string[] }
|
||||
| { type: "Forwarder"; name: string; forwarder: string; protocol: "Udp" | "Tcp" | "Tls" | "Https" | "Quic"; dnssecValidation: boolean };
|
||||
|
||||
export interface DnsAdapter {
|
||||
listZones(): Promise<DnsZone[]>;
|
||||
/** Only for a provider that can make a zone (see ZONE_CREATING_PROVIDERS in registry.ts); the zone it made, by the name the provider gave it. */
|
||||
createZone?(zone: NewDnsZone): Promise<DnsZone>;
|
||||
listRecords(zoneId: string): Promise<DnsRecord[]>;
|
||||
addRecord(zoneId: string, record: DnsRecordInput): Promise<DnsRecord>;
|
||||
updateRecord(zoneId: string, recordId: string, record: DnsRecordInput): Promise<DnsRecord>;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* The name a new DNS zone is made with. A zone is a domain name (`home.lan`, a single label such as `lan` is one too), or — for a reverse zone — an address or a network in CIDR form
|
||||
* (`192.168.1.0/24`, `fd00::/8`), which Technitium turns into the `…in-addr.arpa` or `…ip6.arpa` zone. Names are written the way DNS compares them: lower case, no trailing dot, and only
|
||||
* ASCII — a name with other letters is given in its punycode form (`xn--…`). Anything else is refused here, before a provider is asked.
|
||||
*/
|
||||
import * as net from "node:net";
|
||||
|
||||
const LABEL = /^[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?$/;
|
||||
|
||||
/** The name as it is to be sent, or null when it is not a zone name. */
|
||||
export function normaliseZoneName(input: string): string | null {
|
||||
const s = input.trim().toLowerCase().replace(/\.$/, "");
|
||||
if (s === "" || s.length > 253) return null;
|
||||
const network = /^([0-9a-f.:]+)\/(\d{1,3})$/.exec(s);
|
||||
if (network) {
|
||||
const bits = Number(network[2]);
|
||||
if (net.isIPv4(network[1])) return bits <= 32 ? s : null;
|
||||
if (net.isIPv6(network[1])) return bits <= 128 ? s : null;
|
||||
return null;
|
||||
}
|
||||
if (net.isIP(s) !== 0) return s;
|
||||
return s.split(".").every((label) => LABEL.test(label)) ? s : null;
|
||||
}
|
||||
@@ -11,7 +11,8 @@ import {
|
||||
splitProviderConfig,
|
||||
validateProviderConfig,
|
||||
} from "../dns/providerSchemas.js";
|
||||
import { createDnsAdapter } from "../dns/registry.js";
|
||||
import { createDnsAdapter, ZONE_CREATING_PROVIDERS } from "../dns/registry.js";
|
||||
import { normaliseZoneName } from "../dns/zoneNames.js";
|
||||
import { loadDnsProviderConfig, getDnsAdapterForProvider } from "../dns/loadProvider.js";
|
||||
import { getDnsStats } from "../dns/stats.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
@@ -55,7 +56,7 @@ dnsRouter.get("/providers", asyncHandler(async (_req, res) => {
|
||||
createdAt: dnsProviders.createdAt,
|
||||
})
|
||||
.from(dnsProviders);
|
||||
res.json({ providers: rows });
|
||||
res.json({ providers: rows.map((r) => ({ ...r, canCreateZones: ZONE_CREATING_PROVIDERS.has(r.providerType) })) });
|
||||
}));
|
||||
|
||||
const configValueSchema = z.union([z.string(), z.boolean()]);
|
||||
@@ -277,6 +278,59 @@ dnsRouter.get("/providers/:id/zones", asyncHandler(async (req, res) => {
|
||||
}
|
||||
}));
|
||||
|
||||
const zoneName = z.string().max(300).transform((s, ctx) => {
|
||||
const name = normaliseZoneName(s);
|
||||
if (name === null) {
|
||||
ctx.addIssue({ code: "custom", message: "That is not a zone name: use a domain name such as home.lan (letters, digits, - and _, ASCII), or an address or network such as 192.168.1.0/24 for a reverse zone." });
|
||||
return z.NEVER;
|
||||
}
|
||||
return name;
|
||||
});
|
||||
const serverAddress = z.string().trim().min(1).max(255).regex(/^[A-Za-z0-9._:\[\]-]+$/, "A server is given by its address or host name.");
|
||||
|
||||
const newZoneSchema = z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("Primary"), name: zoneName }),
|
||||
z.object({ type: z.literal("Secondary"), name: zoneName, primaryNameServers: z.array(serverAddress).min(1, "Give the server that holds the zone.").max(10) }),
|
||||
z.object({
|
||||
type: z.literal("Forwarder"),
|
||||
name: zoneName,
|
||||
forwarder: z.string().trim().min(1, "Give the DNS server to pass questions to.").max(255).regex(/^[^\s,;"'<>]+$/, "The server is an address, a host name, a URL or this-server."),
|
||||
protocol: z.enum(["Udp", "Tcp", "Tls", "Https", "Quic"]).default("Udp"),
|
||||
dnssecValidation: z.boolean().default(false),
|
||||
}),
|
||||
]);
|
||||
|
||||
/**
|
||||
* Makes a zone on a provider that can (Technitium): a Primary zone, a Secondary zone from the servers that hold it, or a Forwarder zone that passes questions on. An administrator's alone — it makes
|
||||
* the server an authority for a name. Nothing is made if the name is not one; what the provider says when it refuses (a zone that exists, a name it will not take) is passed on.
|
||||
*/
|
||||
dnsRouter.post("/providers/:id/zones", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const providerId = /^\d+$/.test(req.params.id) ? Number(req.params.id) : Number.NaN;
|
||||
if (!Number.isInteger(providerId)) return res.status(400).json({ error: "invalid_id" });
|
||||
const parsed = newZoneSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a zone.", details: parsed.error.flatten() });
|
||||
const found = await getDnsAdapterForProvider(providerId);
|
||||
if (!found) return res.status(404).json({ error: "not_found" });
|
||||
if (!found.provider.enabled) return res.status(400).json({ error: "provider_disabled", message: "This provider is switched off." });
|
||||
if (!ZONE_CREATING_PROVIDERS.has(found.provider.providerType) || !found.adapter.createZone) {
|
||||
return res.status(400).json({ error: "not_supported", message: "Zones can't be made from here on this kind of provider." });
|
||||
}
|
||||
try {
|
||||
const zone = await found.adapter.createZone(parsed.data);
|
||||
await recordAudit({
|
||||
actor: req.currentUser!,
|
||||
category: "dns",
|
||||
action: "create_zone",
|
||||
targetType: "dns_zone",
|
||||
targetId: zone.id,
|
||||
detail: { providerId, name: zone.name, type: parsed.data.type, ...(parsed.data.type === "Forwarder" ? { forwarder: parsed.data.forwarder } : {}) },
|
||||
});
|
||||
res.status(201).json({ zone });
|
||||
} catch (err) {
|
||||
res.status(502).json({ error: "dns_provider_error", message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}));
|
||||
|
||||
// ─── Records (cached) ────────────────────────────────────────────────────────
|
||||
|
||||
dnsRouter.get("/providers/:id/zones/:zoneId/records", asyncHandler(async (req, res) => {
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user