Delete Technitium zones from the DNS page

A Delete zone button on the open zone of a Technitium provider deletes the zone
and every record in it: the name has to be typed, and the server checks it
against the zone as the provider lists it now (so a stale page, a wrong id or
an internal zone cannot be deleted by mistake). What this app cached of the
zone and its records goes with it. Technitium's own refusal is shown and
nothing is changed. Administrators only, audited with how many records were
cached; the adapter gets an optional deleteZone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 22:51:19 +01:00
1 parent 0244f5a8ab
commit 082c524125
10 files changed
+197 -16

No files matched your search

+7 -2
View File
@@ -6,7 +6,8 @@
* 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.
* 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). Deleting one is `/api/zones/delete` with the
* zone's name (permission "Zones: Delete", which is not the one for changing records): the zone and every record in it go. Neither is checked against a live server.
*/
import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone, NewDnsZone } from "../types.js";
import { withDiagLogging } from "../../services/diagLog.js";
@@ -113,6 +114,10 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
return { id: made, name: made };
}
async function deleteZone(zoneId: string): Promise<void> {
await apiPost("/api/zones/delete", { zone: zoneId });
}
async function listZones(): Promise<DnsZone[]> {
const resp = await apiGet("/api/zones/list");
const zones = resp?.zones ?? [];
@@ -166,5 +171,5 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
await apiPost("/api/zones/records/delete", { domain: name, zone, type, ...typeParams });
}
return withDiagLogging("technitium", { listZones, createZone, listRecords, addRecord, updateRecord, deleteRecord });
return withDiagLogging("technitium", { listZones, createZone, deleteZone, listRecords, addRecord, updateRecord, deleteRecord });
}
+3
View File
@@ -10,6 +10,9 @@ 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"]);
/** The kinds of provider whose adapter can delete a zone: the page offers "Delete zone" for these, and the route refuses it for the others. */
export const ZONE_DELETING_PROVIDERS: ReadonlySet<DnsProviderType> = new Set<DnsProviderType>(["technitium"]);
export function createDnsAdapter(providerType: DnsProviderType, config: DnsProviderConfig): DnsAdapter {
switch (providerType) {
case "cloudflare":
+2
View File
@@ -32,6 +32,8 @@ 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>;
/** Only for a provider that can delete a zone (ZONE_DELETING_PROVIDERS in registry.ts): the zone and every record in it are gone. */
deleteZone?(zoneId: string): Promise<void>;
listRecords(zoneId: string): Promise<DnsRecord[]>;
addRecord(zoneId: string, record: DnsRecordInput): Promise<DnsRecord>;
updateRecord(zoneId: string, recordId: string, record: DnsRecordInput): Promise<DnsRecord>;
+36 -2
View File
@@ -11,7 +11,7 @@ import {
splitProviderConfig,
validateProviderConfig,
} from "../dns/providerSchemas.js";
import { createDnsAdapter, ZONE_CREATING_PROVIDERS } from "../dns/registry.js";
import { createDnsAdapter, ZONE_CREATING_PROVIDERS, ZONE_DELETING_PROVIDERS } from "../dns/registry.js";
import { normaliseZoneName } from "../dns/zoneNames.js";
import { loadDnsProviderConfig, getDnsAdapterForProvider } from "../dns/loadProvider.js";
import { getDnsStats } from "../dns/stats.js";
@@ -56,7 +56,7 @@ dnsRouter.get("/providers", asyncHandler(async (_req, res) => {
createdAt: dnsProviders.createdAt,
})
.from(dnsProviders);
res.json({ providers: rows.map((r) => ({ ...r, canCreateZones: ZONE_CREATING_PROVIDERS.has(r.providerType) })) });
res.json({ providers: rows.map((r) => ({ ...r, canCreateZones: ZONE_CREATING_PROVIDERS.has(r.providerType), canDeleteZones: ZONE_DELETING_PROVIDERS.has(r.providerType) })) });
}));
const configValueSchema = z.union([z.string(), z.boolean()]);
@@ -331,6 +331,40 @@ dnsRouter.post("/providers/:id/zones", requireRole("admin"), asyncHandler(async
}
}));
const deleteZoneSchema = z.object({ name: z.string().min(1).max(300) });
/**
* Deletes a zone, and every record in it, on a provider that can (Technitium). An administrator's alone. The zone's name has to be sent along and has to be the one the zone has now, and the
* provider has to list the zone: a page that is minutes old, a wrong id or one of the server's own internal zones (not listed) cannot be deleted by mistake. What this app has cached of the zone
* and its records goes with it. What the provider says when it refuses (a token that may not delete zones) is passed on, and nothing is changed here.
*/
dnsRouter.delete("/providers/:id/zones/:zoneId", requireRole("admin"), asyncHandler(async (req, res) => {
const providerId = /^\d+$/.test(req.params.id) ? Number(req.params.id) : Number.NaN;
const zoneId = req.params.zoneId;
if (!Number.isInteger(providerId) || normaliseZoneName(zoneId) !== zoneId) return res.status(400).json({ error: "invalid_id" });
const parsed = deleteZoneSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "The name of the zone has to be sent along to delete it." });
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_DELETING_PROVIDERS.has(found.provider.providerType) || !found.adapter.deleteZone) {
return res.status(400).json({ error: "not_supported", message: "Zones can't be deleted from here on this kind of provider." });
}
try {
const zone = (await found.adapter.listZones()).find((z) => z.id === zoneId);
if (!zone) return res.status(404).json({ error: "zone_not_found", message: "The provider has no such zone." });
if (zone.name !== parsed.data.name) return res.status(400).json({ error: "name_mismatch", message: "That is not the name of that zone." });
await found.adapter.deleteZone(zoneId);
} catch (err) {
return res.status(502).json({ error: "dns_provider_error", message: err instanceof Error ? err.message : String(err) });
}
const cachedRecords = await db.select({ id: dnsRecordsCache.id }).from(dnsRecordsCache).where(and(eq(dnsRecordsCache.providerId, providerId), eq(dnsRecordsCache.zoneId, zoneId)));
await db.delete(dnsRecordsCache).where(and(eq(dnsRecordsCache.providerId, providerId), eq(dnsRecordsCache.zoneId, zoneId)));
await db.delete(dnsZonesCache).where(and(eq(dnsZonesCache.providerId, providerId), eq(dnsZonesCache.zoneId, zoneId)));
await recordAudit({ actor: req.currentUser!, category: "dns", action: "delete_zone", targetType: "dns_zone", targetId: zoneId, detail: { providerId, name: parsed.data.name, cachedRecords: cachedRecords.length } });
res.status(204).end();
}));
// ─── Records (cached) ────────────────────────────────────────────────────────
dnsRouter.get("/providers/:id/zones/:zoneId/records", asyncHandler(async (req, res) => {
+106 -6
View File
@@ -1,5 +1,5 @@
/**
* 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
* 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
@@ -19,7 +19,8 @@ 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 { 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");
@@ -62,6 +63,8 @@ interface Seen {
}
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 = "";
@@ -77,7 +80,13 @@ before(async () => {
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);
@@ -125,6 +134,17 @@ describe("what is sent to Technitium", () => {
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" } };
@@ -143,10 +163,24 @@ describe("the route", () => {
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([
@@ -180,10 +214,10 @@ describe("the route", () => {
}
});
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("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 () => {
@@ -253,6 +287,72 @@ describe("the route", () => {
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;