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
+3
-2
@@ -598,6 +598,7 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
|
||||
|
||||
- **Config fields:** Technitium URL, API Token
|
||||
- **Auth:** Bearer token
|
||||
- **Actions used:** list zones, read zone records, add/delete records (an "update" is implemented as delete + add)
|
||||
- **Required access:** A token tied to a Technitium user account with **Zones: View + Modify** permission — view-only will fail on record changes since updates are add/delete calls under the hood.
|
||||
- **Actions used:** list zones, **make a zone**, read zone records, add/delete records (an "update" is implemented as delete + add)
|
||||
- **Making a zone** (DNS page → pick the provider → **New zone**, administrators only — it makes the server an authority for a name; it is the one DNS provider that can): a **Primary** zone (a domain name such as `home.lan`, or an address or network such as `192.168.1.0/24`, which Technitium turns into the reverse `…in-addr.arpa` zone), a **Secondary** zone (the servers that hold it, comma-separated) or a **Forwarder** zone (the DNS server to pass questions to — an address, a name, a URL or `this-server` — the protocol, UDP unless told, and whether to check DNSSEC, off unless told). It is `POST /api/zones/create` with the name and the type (and, for a Secondary, `primaryNameServerAddresses`; for a Forwarder, `initializeForwarder`, `forwarder`, `protocol` and `dnssecValidation`). The name is written lower case without a trailing dot and must be ASCII (a name with other letters in its `xn--` form); anything else is refused before Technitium is asked, and what Technitium says when it refuses (a zone that is there already) is shown as it was said. The new zone opens when it is made; a Primary zone has the records Technitium makes for it and the rest are added as usual. It is written in the audit log (who made which zone, of which kind). Zones are not deleted from here. **Not verified against a live install**: the call is as Technitium's API documentation has it.
|
||||
- **Required access:** A token tied to a Technitium user account with **Zones: View + Modify** permission — view-only will fail on record changes (updates are add/delete calls under the hood) and on making a zone.
|
||||
- **This is the DNS provider** (zones and records, on the DNS page). How the *server* is doing — queries, blocking, zone health, a real DNS test, alerts — is a separate integration with its own token: see [Technitium DNS](#technitium-dns) under the integrations above.
|
||||
@@ -78,7 +78,9 @@ All modules from the original plan are built:
|
||||
a range on the spot; managing ranges from either page updates the other
|
||||
- **DNS** — zone/record management across Cloudflare, Loopia, Pi-hole, Azure
|
||||
DNS, cPanel, and Technitium; providers are configured in-app (not via env
|
||||
vars) and their credentials are encrypted at rest
|
||||
vars) and their credentials are encrypted at rest. On a Technitium provider an
|
||||
administrator can also **make a zone** (Primary, Secondary or Forwarder — a name, or a
|
||||
network for a reverse zone), and Technitium's own refusal (a zone that exists) is shown as it was said
|
||||
- **Servers** — cron/systemd tracking across Debian/Raspbian servers via a
|
||||
lightweight push agent (`agent/linux/`), Windows scheduled-task tracking
|
||||
through a PowerShell agent (`agent/windows/`, see its README), plus manual
|
||||
|
||||
@@ -108,7 +108,7 @@ even further, to admin only:
|
||||
- **Integrations & DNS providers**: any operator can use an integration
|
||||
once it's configured (start/stop a guest, run a template, sync DNS
|
||||
records, etc.), but adding, editing, testing, or deleting an
|
||||
integration or DNS provider is admin-only.
|
||||
integration or DNS provider is admin-only. So is **making a zone** on a DNS provider that can (Technitium): it makes the server an authority for a name, so it is not an operator's job like adding a record.
|
||||
- **Servers**: registering a new server, rotating its agent token, and
|
||||
editing/deleting a server are admin-only; tagging a server and
|
||||
linking/unlinking it to a Proxmox guest just need operator.
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -675,8 +675,16 @@ export interface DnsProviderSummary {
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
createdAt: string;
|
||||
/** Whether zones can be made on it from here (Technitium). */
|
||||
canCreateZones: boolean;
|
||||
}
|
||||
|
||||
/** A zone to be made: a Primary one, a Secondary one from the servers that hold it, or a Forwarder one that passes questions on. */
|
||||
export type NewDnsZoneInput =
|
||||
| { 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 DnsZone {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -3917,6 +3925,7 @@ export const api = {
|
||||
},
|
||||
zones: {
|
||||
list: (providerId: number) => request<{ zones: DnsZone[] }>(`/api/dns/providers/${providerId}/zones`),
|
||||
create: (providerId: number, body: NewDnsZoneInput) => request<{ zone: { id: string; name: string } }>(`/api/dns/providers/${providerId}/zones`, { method: "POST", body: JSON.stringify(body) }),
|
||||
},
|
||||
records: {
|
||||
list: (providerId: number, zoneId: string) =>
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { api, type NewDnsZoneInput } from "../api/client";
|
||||
import { ErrorNotice } from "./Notice";
|
||||
import { readableError } from "../utils/errors";
|
||||
|
||||
type Kind = NewDnsZoneInput["type"];
|
||||
type Protocol = "Udp" | "Tcp" | "Tls" | "Https" | "Quic";
|
||||
|
||||
const KINDS: { value: Kind; label: string; hint: string }[] = [
|
||||
{ value: "Primary", label: "Primary zone", hint: "This server holds the zone: its records are made and changed here. It starts with the records Technitium makes for it; the rest are added under Records." },
|
||||
{ value: "Secondary", label: "Secondary zone", hint: "A copy of a zone another server holds. This server fetches it from there and keeps it up to date; it can only be read here." },
|
||||
{ value: "Forwarder", label: "Forwarder zone", hint: "Questions about this name (and under it) are passed on to another DNS server — for a domain another server answers, such as a company network." },
|
||||
];
|
||||
|
||||
/** The servers a person typed, one to a line or separated by commas or spaces. */
|
||||
const serversOf = (text: string) => text.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
|
||||
|
||||
/**
|
||||
* Making a zone on a DNS provider that can: Technitium. A name (a domain such as home.lan, or an address or network such as 192.168.1.0/24 for a reverse zone) and what kind. What the provider says
|
||||
* when it won't — a zone that is there already — is shown as it was said. An administrator's alone, as it makes the server an authority for the name.
|
||||
*/
|
||||
export default function DnsNewZone({ providerId, providerName, onCreated, onCancel }: { providerId: number; providerName: string; onCreated: (zone: { id: string; name: string }) => void; onCancel: () => void }) {
|
||||
const [kind, setKind] = useState<Kind>("Primary");
|
||||
const [name, setName] = useState("");
|
||||
const [primaries, setPrimaries] = useState("");
|
||||
const [forwarder, setForwarder] = useState("");
|
||||
const [protocol, setProtocol] = useState<Protocol>("Udp");
|
||||
const [dnssec, setDnssec] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const body: NewDnsZoneInput = kind === "Primary" ? { type: "Primary", name } : kind === "Secondary" ? { type: "Secondary", name, primaryNameServers: serversOf(primaries) } : { type: "Forwarder", name, forwarder: forwarder.trim(), protocol, dnssecValidation: dnssec };
|
||||
const { zone } = await api.dns.zones.create(providerId, body);
|
||||
onCreated(zone);
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit}>
|
||||
<h4 className="mb-2">New zone on {providerName}</h4>
|
||||
<ErrorNotice error={error} />
|
||||
<div className="mb-2">
|
||||
<label className="form-label" htmlFor="newzone-kind">
|
||||
Kind
|
||||
</label>
|
||||
<select id="newzone-kind" className="form-select form-select-sm" value={kind} onChange={(e) => setKind(e.target.value as Kind)}>
|
||||
{KINDS.map((k) => (
|
||||
<option key={k.value} value={k.value}>
|
||||
{k.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="text-secondary small mt-1">{KINDS.find((k) => k.value === kind)!.hint}</div>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<label className="form-label" htmlFor="newzone-name">
|
||||
Name
|
||||
</label>
|
||||
<input id="newzone-name" className="form-control form-control-sm" required autoFocus maxLength={300} autoComplete="off" placeholder="home.lan — or 192.168.1.0/24 for a reverse zone" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<div className="text-secondary small mt-1">Written in lower case, ASCII (a name with other letters in its xn-- form), with no dot at the end.</div>
|
||||
</div>
|
||||
{kind === "Secondary" && (
|
||||
<div className="mb-2">
|
||||
<label className="form-label" htmlFor="newzone-primaries">
|
||||
Servers that hold it
|
||||
</label>
|
||||
<input id="newzone-primaries" className="form-control form-control-sm" required maxLength={600} autoComplete="off" placeholder="10.0.0.2, ns1.example.lan" value={primaries} onChange={(e) => setPrimaries(e.target.value)} />
|
||||
<div className="text-secondary small mt-1">Addresses or host names, separated by commas.</div>
|
||||
</div>
|
||||
)}
|
||||
{kind === "Forwarder" && (
|
||||
<div className="row g-2 mb-2">
|
||||
<div className="col-md-6">
|
||||
<label className="form-label" htmlFor="newzone-forwarder">
|
||||
Pass questions to
|
||||
</label>
|
||||
<input id="newzone-forwarder" className="form-control form-control-sm" required maxLength={255} autoComplete="off" placeholder="10.1.1.1 — or this-server" value={forwarder} onChange={(e) => setForwarder(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label" htmlFor="newzone-protocol">
|
||||
Protocol
|
||||
</label>
|
||||
<select id="newzone-protocol" className="form-select form-select-sm" value={protocol} onChange={(e) => setProtocol(e.target.value as Protocol)}>
|
||||
{(["Udp", "Tcp", "Tls", "Https", "Quic"] as Protocol[]).map((p) => (
|
||||
<option key={p} value={p}>
|
||||
{p === "Udp" ? "UDP" : p === "Tcp" ? "TCP" : p === "Tls" ? "TLS" : p === "Https" ? "HTTPS" : "QUIC"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3 d-flex align-items-end">
|
||||
<label className="form-check mb-1">
|
||||
<input type="checkbox" className="form-check-input" checked={dnssec} onChange={(e) => setDnssec(e.target.checked)} />
|
||||
<span className="form-check-label">Check DNSSEC</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="d-flex gap-2 mt-3">
|
||||
<button type="submit" className="btn btn-sm btn-primary" disabled={busy || name.trim() === ""}>
|
||||
{busy ? "Making…" : "Make zone"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-link text-secondary" onClick={onCancel} disabled={busy}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
+25
-2
@@ -13,6 +13,7 @@ import {
|
||||
type DnsZone,
|
||||
} from "../api/client";
|
||||
import DnsProviderForm from "../components/DnsProviderForm";
|
||||
import DnsNewZone from "../components/DnsNewZone";
|
||||
import { formatDateTime } from "../utils/date";
|
||||
import { useSortable } from "../hooks/useSortable";
|
||||
import SortableTh from "../components/SortableTh";
|
||||
@@ -86,6 +87,7 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
|
||||
const [zones, setZones] = useState<DnsZone[] | null>(null);
|
||||
const [zonesError, setZonesError] = useState<string | null>(null);
|
||||
const [selectedZone, setSelectedZone] = useState<DnsZone | null>(null);
|
||||
const [creatingZone, setCreatingZone] = useState(false);
|
||||
|
||||
const [records, setRecords] = useState<DnsRecord[] | null>(null);
|
||||
const [syncedAt, setSyncedAt] = useState<string | null>(null);
|
||||
@@ -111,7 +113,8 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
|
||||
|
||||
useEffect(loadProviders, []);
|
||||
|
||||
function loadZones(providerId: number) {
|
||||
/** `selectId`: a zone to open once the list is read (the one just made). */
|
||||
function loadZones(providerId: number, selectId?: string) {
|
||||
setZonesError(null);
|
||||
setZones(null);
|
||||
setSelectedZone(null);
|
||||
@@ -121,7 +124,7 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
|
||||
.then((res) => {
|
||||
setZones(res.zones);
|
||||
// Deep-link from global search (?providerId=&zoneId=) — auto-open the linked zone once its records load.
|
||||
const linkedZoneId = searchParams.get("zoneId");
|
||||
const linkedZoneId = selectId ?? searchParams.get("zoneId");
|
||||
const linkedZone = linkedZoneId ? res.zones.find((z) => z.id === linkedZoneId) : undefined;
|
||||
if (linkedZone) selectZone(linkedZone);
|
||||
})
|
||||
@@ -129,6 +132,7 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setCreatingZone(false);
|
||||
if (selectedProviderId && !managingProviders) loadZones(selectedProviderId);
|
||||
}, [selectedProviderId, managingProviders]);
|
||||
|
||||
@@ -427,6 +431,11 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Zones</h3>
|
||||
<div className="card-actions">
|
||||
{isAdmin && selectedProvider?.canCreateZones && selectedProvider.enabled && (
|
||||
<button className="btn btn-sm btn-primary me-2" onClick={() => setCreatingZone((v) => !v)} aria-expanded={creatingZone}>
|
||||
New zone
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn btn-sm btn-outline-secondary"
|
||||
onClick={exportZonesCsv}
|
||||
@@ -436,6 +445,20 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{creatingZone && selectedProvider && selectedProviderId && (
|
||||
<div className="card-body border-bottom">
|
||||
<DnsNewZone
|
||||
providerId={selectedProviderId}
|
||||
providerName={selectedProvider.name}
|
||||
onCancel={() => setCreatingZone(false)}
|
||||
onCreated={(zone) => {
|
||||
setCreatingZone(false);
|
||||
toast.success(`Made the zone ${zone.name}.`);
|
||||
loadZones(selectedProviderId, zone.id);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<ErrorNotice error={zonesError} className="m-3 mb-0" />
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
|
||||
Reference in new issue
Block a user