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

+4 -3
View File
@@ -598,7 +598,8 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
- **Config fields:** Technitium URL, API Token - **Config fields:** Technitium URL, API Token
- **Auth:** Bearer token - **Auth:** Bearer token
- **Actions used:** list zones, **make a zone**, read zone records, add/delete records (an "update" is implemented as delete + add) - **Actions used:** list zones, **make a zone**, **delete 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. - **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).
- **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. - **Deleting a zone** (DNS page → open the zone → **Delete zone**, administrators only): the zone **and every record in it** go, for good — `POST /api/zones/delete` with the zone's name. The zone's name has to be typed, and the server checks it again: it must be the name the zone has now and the provider must list the zone, so a page that is minutes old, a wrong id, or one of the server's own internal zones (which are not listed) cannot be deleted by mistake; an id that is not a zone name as written (lower case, no trailing dot) is refused. What this app has cached of the zone and its records is dropped with it (the registration of the domain on the *Domain names* tab is not touched). What Technitium says when it refuses — a token that may not delete zones — is shown, and then nothing is changed here. It is written in the audit log (who deleted which zone, and how many of its records were cached). **Not verified against a live install**: the calls are as Technitium's API documentation has them.
- **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. **Deleting a zone** needs **Zones: Delete**, which is a permission of its own.
- **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. - **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.
+2 -1
View File
@@ -80,7 +80,8 @@ All modules from the original plan are built:
DNS, cPanel, and Technitium; providers are configured in-app (not via env DNS, cPanel, and Technitium; providers are configured in-app (not via env
vars) and their credentials are encrypted at rest. On a Technitium provider an 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 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 network for a reverse zone) and **delete** one (its name typed to confirm; every record in it goes), and
Technitium's own refusal (a zone that exists, a token that may not delete) is shown as it was said
- **Servers** — cron/systemd tracking across Debian/Raspbian servers via a - **Servers** — cron/systemd tracking across Debian/Raspbian servers via a
lightweight push agent (`agent/linux/`), Windows scheduled-task tracking lightweight push agent (`agent/linux/`), Windows scheduled-task tracking
through a PowerShell agent (`agent/windows/`, see its README), plus manual through a PowerShell agent (`agent/windows/`, see its README), plus manual
+1 -1
View File
@@ -108,7 +108,7 @@ even further, to admin only:
- **Integrations & DNS providers**: any operator can use an integration - **Integrations & DNS providers**: any operator can use an integration
once it's configured (start/stop a guest, run a template, sync DNS once it's configured (start/stop a guest, run a template, sync DNS
records, etc.), but adding, editing, testing, or deleting an records, etc.), but adding, editing, testing, or deleting an
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. integration or DNS provider is admin-only. So is **making or deleting a zone** on a DNS provider that can (Technitium): making one makes the server an authority for a name, and deleting one takes every record in it, so neither is an operator's job like adding a record.
- **Servers**: registering a new server, rotating its agent token, and - **Servers**: registering a new server, rotating its agent token, and
editing/deleting a server are admin-only; tagging a server and editing/deleting a server are admin-only; tagging a server and
linking/unlinking it to a Proxmox guest just need operator. linking/unlinking it to a Proxmox guest just need operator.
+7 -2
View File
@@ -6,7 +6,8 @@
* Record ID format: "type||name||content||priority" * 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 * 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 type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone, NewDnsZone } from "../types.js";
import { withDiagLogging } from "../../services/diagLog.js"; import { withDiagLogging } from "../../services/diagLog.js";
@@ -113,6 +114,10 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
return { id: made, name: made }; return { id: made, name: made };
} }
async function deleteZone(zoneId: string): Promise<void> {
await apiPost("/api/zones/delete", { zone: zoneId });
}
async function listZones(): Promise<DnsZone[]> { async function listZones(): Promise<DnsZone[]> {
const resp = await apiGet("/api/zones/list"); const resp = await apiGet("/api/zones/list");
const zones = resp?.zones ?? []; 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 }); 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. */ /** 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 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 { export function createDnsAdapter(providerType: DnsProviderType, config: DnsProviderConfig): DnsAdapter {
switch (providerType) { switch (providerType) {
case "cloudflare": case "cloudflare":
+2
View File
@@ -32,6 +32,8 @@ export interface DnsAdapter {
listZones(): Promise<DnsZone[]>; 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. */ /** 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>; 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[]>; listRecords(zoneId: string): Promise<DnsRecord[]>;
addRecord(zoneId: string, record: DnsRecordInput): Promise<DnsRecord>; addRecord(zoneId: string, record: DnsRecordInput): Promise<DnsRecord>;
updateRecord(zoneId: string, recordId: string, record: DnsRecordInput): Promise<DnsRecord>; updateRecord(zoneId: string, recordId: string, record: DnsRecordInput): Promise<DnsRecord>;
+36 -2
View File
@@ -11,7 +11,7 @@ import {
splitProviderConfig, splitProviderConfig,
validateProviderConfig, validateProviderConfig,
} from "../dns/providerSchemas.js"; } 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 { normaliseZoneName } from "../dns/zoneNames.js";
import { loadDnsProviderConfig, getDnsAdapterForProvider } from "../dns/loadProvider.js"; import { loadDnsProviderConfig, getDnsAdapterForProvider } from "../dns/loadProvider.js";
import { getDnsStats } from "../dns/stats.js"; import { getDnsStats } from "../dns/stats.js";
@@ -56,7 +56,7 @@ dnsRouter.get("/providers", asyncHandler(async (_req, res) => {
createdAt: dnsProviders.createdAt, createdAt: dnsProviders.createdAt,
}) })
.from(dnsProviders); .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()]); 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) ──────────────────────────────────────────────────────── // ─── Records (cached) ────────────────────────────────────────────────────────
dnsRouter.get("/providers/:id/zones/:zoneId/records", asyncHandler(async (req, res) => { 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. * 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 * 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 express = (await import("express")).default;
const { db } = await import("../src/db/client.js"); 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 { runMigrations } = await import("../src/db/migrate.js");
const { encryptSecret } = await import("../src/crypto.js"); const { encryptSecret } = await import("../src/crypto.js");
const { normaliseZoneName } = await import("../src/dns/zoneNames.js"); const { normaliseZoneName } = await import("../src/dns/zoneNames.js");
@@ -62,6 +63,8 @@ interface Seen {
} }
const seen: Seen[] = []; const seen: Seen[] = [];
let answer: { status: number; body: unknown } = { status: 200, body: null }; 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 fake: Server;
let fakeUrl = ""; let fakeUrl = "";
@@ -77,7 +80,13 @@ before(async () => {
res.writeHead(status, { "content-type": "application/json" }); res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(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 (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. // The domain a reverse zone is made as.
const zone = form.get("zone") ?? ""; const zone = form.get("zone") ?? "";
const reverse = /^(\d+)\.(\d+)\.(\d+)\.0\/24$/.exec(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"); 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 () => { test("what Technitium says when it refuses is the error; so is a token it does not accept", async () => {
reset(); reset();
answer = { status: 200, body: { status: "error", errorMessage: "Zone already exists: home.lan" } }; 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 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 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 = () => { const reset = () => {
seen.length = 0; seen.length = 0;
answer = { status: 200, body: null }; 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 () => { before(async () => {
await db.insert(users).values([ await db.insert(users).values([
@@ -180,10 +214,10 @@ describe("the route", () => {
} }
}); });
test("the providers say which can make zones", async () => { 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 }[] }; 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])); const can = Object.fromEntries(body.providers.map((p) => [p.id, [p.canCreateZones, p.canDeleteZones]]));
assert.deepEqual([can[technitium], can[disabled], can[cloudflare]], [true, true, false]); 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 () => { test("only an administrator makes a zone; nothing reaches Technitium for anyone else", async () => {
@@ -253,6 +287,72 @@ describe("the route", () => {
assert.deepEqual(seen, []); 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 () => { test("what Technitium says when it refuses is passed on, and nothing is written in the audit log", async () => {
reset(); reset();
const before = (await db.select().from(auditLog)).filter((e) => e.action === "create_zone").length; const before = (await db.select().from(auditLog)).filter((e) => e.action === "create_zone").length;
+3
View File
@@ -677,6 +677,8 @@ export interface DnsProviderSummary {
createdAt: string; createdAt: string;
/** Whether zones can be made on it from here (Technitium). */ /** Whether zones can be made on it from here (Technitium). */
canCreateZones: boolean; canCreateZones: boolean;
/** Whether zones can be deleted on it from here (Technitium). */
canDeleteZones: 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. */ /** 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. */
@@ -3925,6 +3927,7 @@ export const api = {
}, },
zones: { zones: {
list: (providerId: number) => request<{ zones: DnsZone[] }>(`/api/dns/providers/${providerId}/zones`), list: (providerId: number) => request<{ zones: DnsZone[] }>(`/api/dns/providers/${providerId}/zones`),
remove: (providerId: number, zoneId: string, name: string) => request<void>(`/api/dns/providers/${providerId}/zones/${encodeURIComponent(zoneId)}`, { method: "DELETE", body: JSON.stringify({ name }) }),
create: (providerId: number, body: NewDnsZoneInput) => request<{ zone: { id: string; name: string } }>(`/api/dns/providers/${providerId}/zones`, { method: "POST", body: JSON.stringify(body) }), create: (providerId: number, body: NewDnsZoneInput) => request<{ zone: { id: string; name: string } }>(`/api/dns/providers/${providerId}/zones`, { method: "POST", body: JSON.stringify(body) }),
}, },
records: { records: {
+33 -1
View File
@@ -20,9 +20,10 @@ import SortableTh from "../components/SortableTh";
import { usePagination } from "../hooks/usePagination"; import { usePagination } from "../hooks/usePagination";
import Pagination from "../components/Pagination"; import Pagination from "../components/Pagination";
import { downloadCsv } from "../utils/csv"; import { downloadCsv } from "../utils/csv";
import { confirmDialog } from "../utils/dialogs"; import { confirmDialog, promptDialog } from "../utils/dialogs";
import { ErrorNotice } from "../components/Notice"; import { ErrorNotice } from "../components/Notice";
import { toast } from "../utils/toast"; import { toast } from "../utils/toast";
import { readableError } from "../utils/errors";
import { EmptyRow, LoadingRow } from "../components/EmptyState"; import { EmptyRow, LoadingRow } from "../components/EmptyState";
const PROVIDER_LABELS: Record<DnsProviderType, string> = { const PROVIDER_LABELS: Record<DnsProviderType, string> = {
@@ -242,6 +243,32 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
} }
} }
/** Deletes the open zone, and every record in it, on the provider. The name of the zone has to be typed. */
async function deleteZone() {
if (!selectedProviderId || !selectedZone || !selectedProvider) return;
const zone = selectedZone;
const cached = zone.recordCount > 0 ? ` (${zone.recordCount} record${zone.recordCount === 1 ? " is" : "s are"} cached here)` : "";
const typed = await promptDialog({
title: "Delete zone",
message: `This deletes the zone "${zone.name}" on ${selectedProvider.name}, and every record in it${cached}, for good. It cannot be undone, and what uses this server stops finding the names in it. Type the name of the zone to confirm.`,
label: "Zone name",
confirmLabel: "Delete",
required: true,
});
if (typed === null) return;
if (typed.trim() !== zone.name) {
toast.error("That is not the name of the zone, so nothing was deleted.");
return;
}
try {
await api.dns.zones.remove(selectedProviderId, zone.id, zone.name);
toast.success(`Deleted the zone ${zone.name}.`);
loadZones(selectedProviderId);
} catch (err) {
toast.error(readableError(err));
}
}
async function removeProvider(p: DnsProviderSummary) { async function removeProvider(p: DnsProviderSummary) {
if (!(await confirmDialog({ title: "Delete DNS provider", message: `Delete provider "${p.name}"? This removes its cached zones and records too.`, confirmLabel: "Delete", danger: true }))) return; if (!(await confirmDialog({ title: "Delete DNS provider", message: `Delete provider "${p.name}"? This removes its cached zones and records too.`, confirmLabel: "Delete", danger: true }))) return;
try { try {
@@ -529,6 +556,11 @@ function DnsRecords({ user, tabs }: { user: CurrentUser; tabs: ReactNode }) {
Add record Add record
</button> </button>
)} )}
{isAdmin && selectedProvider?.canDeleteZones && selectedProvider.enabled && (
<button className="btn btn-sm btn-outline-danger ms-2" onClick={() => void deleteZone()}>
Delete zone
</button>
)}
</div> </div>
</div> </div>