Edit Technitium zones: switch off and on, and their options

An Edit zone panel on the open zone of a Technitium provider switches the zone
off and on (its records stay) and edits who may ask it (query access), who may
copy it (zone transfer, with the TSIG keys the server has) and who is told when
it changes (notify). Only the groups that apply to the kind of zone are shown,
a mode that goes by a list needs it, and entries must be addresses or networks;
only groups that differ are sent, each whole, and the zone is read again
afterwards so anything else that moved is named on the page and in the audit
log. The server's own zones are not touched. Administrators only, audited.
Zones in the list show when they are off and what kind they are.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 23:20:19 +01:00
1 parent 082c524125
commit 6f144b4e36
12 files changed
+1110 -10

No files matched your search

+57 -3
View File
@@ -7,9 +7,12 @@
*
* 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). 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.
* zone's name (permission "Zones: Delete", which is not the one for changing records): the zone and every record in it go. A zone is switched off and on with `/api/zones/disable` and
* `/api/zones/enable`, and its options are read with `/api/zones/options/get` and changed with `/api/zones/options/set` — query access, zone transfer and notify here. None of them is
* checked against a live server.
*/
import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone, NewDnsZone } from "../types.js";
import type { DnsZoneOptions, ZoneOptionsChange } from "../zoneOptions.js";
import { withDiagLogging } from "../../services/diagLog.js";
export interface TechnitiumConfig {
@@ -118,10 +121,61 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
await apiPost("/api/zones/delete", { zone: zoneId });
}
const list = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []);
const text = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
/** What the options call says that this app does not edit, by name, as JSON — so that an edit can be seen not to have changed it. What changes by itself (failed notifications) is left out. */
const NOT_COMPARED = new Set(["name", "type", "internal", "disabled", "queryAccess", "queryAccessNetworkACL", "zoneTransfer", "zoneTransferNetworkACL", "zoneTransferTsigKeyNames", "notify", "notifyNameServers", "availableTsigKeyNames", "availableCatalogZoneNames", "notifyFailed", "notifyFailedFor"]);
async function getZoneOptions(zoneId: string): Promise<DnsZoneOptions> {
const r = await apiGet("/api/zones/options/get", { zone: zoneId, includeAvailableTsigKeyNames: "true", includeAvailableCatalogZoneNames: "false" });
if (r === null || typeof r !== "object" || typeof r.name !== "string") throw new Error("Technitium did not say how that zone is set");
const other: Record<string, string> = {};
for (const [k, v] of Object.entries(r)) if (!NOT_COMPARED.has(k)) other[k] = JSON.stringify(v) ?? "null";
return {
name: r.name,
type: text(r.type) ?? "",
internal: r.internal === true,
disabled: r.disabled === true,
queryAccess: text(r.queryAccess),
queryAccessNetworkACL: list(r.queryAccessNetworkACL),
zoneTransfer: text(r.zoneTransfer),
zoneTransferNetworkACL: list(r.zoneTransferNetworkACL),
zoneTransferTsigKeyNames: list(r.zoneTransferTsigKeyNames),
notify: text(r.notify),
notifyNameServers: list(r.notifyNameServers),
availableTsigKeyNames: list(r.availableTsigKeyNames),
other,
};
}
async function setZoneEnabled(zoneId: string, enabled: boolean): Promise<void> {
await apiPost(enabled ? "/api/zones/enable" : "/api/zones/disable", { zone: zoneId });
}
async function setZoneOptions(zoneId: string, c: ZoneOptionsChange): Promise<void> {
const params: Record<string, string> = { zone: zoneId };
if (c.queryAccess !== undefined) {
params.queryAccess = c.queryAccess;
if (c.queryAccessNetworkACL) params.queryAccessNetworkACL = c.queryAccessNetworkACL.join(",");
}
if (c.zoneTransfer !== undefined) {
params.zoneTransfer = c.zoneTransfer;
if (c.zoneTransferNetworkACL) params.zoneTransferNetworkACL = c.zoneTransferNetworkACL.join(",");
}
// Technitium clears a list with the word false.
if (c.zoneTransferTsigKeyNames !== undefined) params.zoneTransferTsigKeyNames = c.zoneTransferTsigKeyNames.length > 0 ? c.zoneTransferTsigKeyNames.join(",") : "false";
if (c.notify !== undefined) {
params.notify = c.notify;
if (c.notifyNameServers) params.notifyNameServers = c.notifyNameServers.join(",");
}
await apiPost("/api/zones/options/set", params);
}
async function listZones(): Promise<DnsZone[]> {
const resp = await apiGet("/api/zones/list");
const zones = resp?.zones ?? [];
return zones.filter((z: any) => !z.internal).map((z: any) => ({ id: z.name, name: z.name }));
return zones.filter((z: any) => !z.internal).map((z: any) => ({ id: z.name, name: z.name, type: typeof z.type === "string" ? z.type : undefined, disabled: z.disabled === true }));
}
async function listRecords(zone: string): Promise<DnsRecord[]> {
@@ -171,5 +225,5 @@ export function createTechnitiumAdapter(config: TechnitiumConfig): DnsAdapter {
await apiPost("/api/zones/records/delete", { domain: name, zone, type, ...typeParams });
}
return withDiagLogging("technitium", { listZones, createZone, deleteZone, listRecords, addRecord, updateRecord, deleteRecord });
return withDiagLogging("technitium", { listZones, createZone, deleteZone, getZoneOptions, setZoneEnabled, setZoneOptions, listRecords, addRecord, updateRecord, deleteRecord });
}
+3
View File
@@ -13,6 +13,9 @@ export const ZONE_CREATING_PROVIDERS: ReadonlySet<DnsProviderType> = new Set<Dns
/** 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"]);
/** The kinds of provider whose zones can be switched off and on and have their options edited. */
export const ZONE_EDITING_PROVIDERS: ReadonlySet<DnsProviderType> = new Set<DnsProviderType>(["technitium"]);
export function createDnsAdapter(providerType: DnsProviderType, config: DnsProviderConfig): DnsAdapter {
switch (providerType) {
case "cloudflare":
+12
View File
@@ -1,6 +1,12 @@
import type { DnsZoneOptions, ZoneOptionsChange } from "./zoneOptions.js";
export interface DnsZone {
id: string;
name: string;
/** What kind of zone it is (Technitium: Primary, Secondary, Forwarder …), when the provider says. */
type?: string;
/** Switched off, when the provider says. */
disabled?: boolean;
}
export interface DnsRecord {
@@ -34,6 +40,12 @@ export interface DnsAdapter {
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>;
/** Only for a provider whose zones can be edited (ZONE_EDITING_PROVIDERS in registry.ts): how the zone is set now. */
getZoneOptions?(zoneId: string): Promise<DnsZoneOptions>;
/** Switches a zone on or off; its records stay. */
setZoneEnabled?(zoneId: string, enabled: boolean): Promise<void>;
/** Changes the options named (each group whole — see zoneOptions.ts). */
setZoneOptions?(zoneId: string, change: ZoneOptionsChange): Promise<void>;
listRecords(zoneId: string): Promise<DnsRecord[]>;
addRecord(zoneId: string, record: DnsRecordInput): Promise<DnsRecord>;
updateRecord(zoneId: string, recordId: string, record: DnsRecordInput): Promise<DnsRecord>;
+152
View File
@@ -0,0 +1,152 @@
/**
* A zone's options as far as this app edits them — who may ask the zone (query access), who may copy it (zone transfer) and who is told when it changes (notify) — and how an edit of them is
* checked and planned. Pure: nothing here talks to a provider. The values are Technitium's own words for them; the plan is only what has to be sent for what differs from the zone now.
*
* A group of options is sent whole (its mode and what the mode uses — the network list, the servers) or not at all, because what Technitium does with a parameter that is left out of a call is
* not documented: what is not changed is not mentioned.
*/
import * as net from "node:net";
export const QUERY_ACCESS = ["Deny", "Allow", "AllowOnlyPrivateNetworks", "AllowOnlyZoneNameServers", "UseSpecifiedNetworkACL", "AllowZoneNameServersAndUseSpecifiedNetworkACL"] as const;
export type QueryAccess = (typeof QUERY_ACCESS)[number];
export const ZONE_TRANSFER = ["Deny", "Allow", "AllowOnlyZoneNameServers", "UseSpecifiedNetworkACL", "AllowZoneNameServersAndUseSpecifiedNetworkACL"] as const;
export type ZoneTransfer = (typeof ZONE_TRANSFER)[number];
export const NOTIFY_MODES = ["None", "ZoneNameServers", "SpecifiedNameServers", "BothZoneAndSpecifiedNameServers"] as const;
export type NotifyMode = (typeof NOTIFY_MODES)[number];
/** Whether a mode goes by a list of networks, which then has to be given. */
export const usesAcl = (mode: string): boolean => mode === "UseSpecifiedNetworkACL" || mode === "AllowZoneNameServersAndUseSpecifiedNetworkACL";
/** Whether a notify mode goes by a list of servers, which then has to be given. */
export const usesNameServers = (mode: string): boolean => mode === "SpecifiedNameServers" || mode === "BothZoneAndSpecifiedNameServers";
/** What an edit asks for. Anything left out is not asked to change. */
export interface ZoneOptionsChange {
queryAccess?: QueryAccess;
queryAccessNetworkACL?: string[];
zoneTransfer?: ZoneTransfer;
zoneTransferNetworkACL?: string[];
zoneTransferTsigKeyNames?: string[];
notify?: NotifyMode;
notifyNameServers?: string[];
}
/** A zone's options as the provider has them now. `other` is everything else it says about the zone (as JSON text, by name), kept only to see that an edit did not change what it did not mean to. */
export interface DnsZoneOptions {
name: string;
type: string;
/** One of the server's own zones: not edited from here. */
internal: boolean;
disabled: boolean;
queryAccess: string | null;
queryAccessNetworkACL: string[];
zoneTransfer: string | null;
zoneTransferNetworkACL: string[];
zoneTransferTsigKeyNames: string[];
notify: string | null;
notifyNameServers: string[];
/** The TSIG keys the server has, which a zone transfer may be limited to. */
availableTsigKeyNames: string[];
other: Record<string, string>;
}
/** A network list entry — an address or a network in CIDR form, with a `!` in front to deny it — as it is to be sent; null when it is not one. */
export function aclEntry(input: string): string | null {
const s = input.trim();
const deny = s.startsWith("!");
const m = /^([0-9a-fA-F.:]+)(?:\/(\d{1,3}))?$/.exec(deny ? s.slice(1).trim() : s);
if (!m) return null;
const v4 = net.isIPv4(m[1]);
if (!v4 && !net.isIPv6(m[1])) return null;
if (m[2] !== undefined && Number(m[2]) > (v4 ? 32 : 128)) return null;
return `${deny ? "!" : ""}${m[1].toLowerCase()}${m[2] !== undefined ? `/${m[2]}` : ""}`;
}
const sameInOrder = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
const sameAsSet = (a: string[], b: string[]) => sameInOrder([...a].sort(), [...b].sort());
export type OptionsPlan = { send: ZoneOptionsChange; changed: ("queryAccess" | "zoneTransfer" | "notify")[] } | { error: string };
/**
* What has to be sent to make a zone of this type have what was asked, from what it has now: only the groups that differ, each whole. An error says what is wrong with the ask: an option the
* kind of zone does not have, a mode that needs a list and has none, an entry that is not an address or network, a key the server does not have. No change is not an error: `changed` is empty.
*/
export function planOptionsChange(type: string, current: DnsZoneOptions, wanted: ZoneOptionsChange): OptionsPlan {
const send: ZoneOptionsChange = {};
const changed: ("queryAccess" | "zoneTransfer" | "notify")[] = [];
const takesQuery = type !== "SecondaryCatalog";
const takesTransferAndNotify = type === "Primary" || type === "Secondary";
const acl = (list: string[] | undefined, fallback: string[], what: string): string[] | string => {
const out: string[] = [];
for (const raw of list ?? fallback) {
const e = aclEntry(raw);
if (e === null) return `"${raw}" is not an address or a network (for example 192.168.1.0/24, or !10.0.0.5 to refuse one).`;
out.push(e);
}
return out.length > 0 ? out : `${what} goes by a list of networks, and the list is empty.`;
};
if (wanted.queryAccess !== undefined || wanted.queryAccessNetworkACL !== undefined) {
if (!takesQuery) return { error: `A ${type} zone has no query access to set.` };
const mode = wanted.queryAccess ?? current.queryAccess;
if (mode === null) return { error: "The zone's query access is not known, so it is not changed from here." };
let list: string[] = [];
if (usesAcl(mode)) {
const r = acl(wanted.queryAccessNetworkACL, current.queryAccessNetworkACL, "Query access");
if (typeof r === "string") return { error: r };
list = r;
}
if (mode !== current.queryAccess || (usesAcl(mode) && !sameInOrder(list, current.queryAccessNetworkACL))) {
send.queryAccess = mode as QueryAccess;
if (usesAcl(mode)) send.queryAccessNetworkACL = list;
changed.push("queryAccess");
}
}
if (wanted.zoneTransfer !== undefined || wanted.zoneTransferNetworkACL !== undefined || wanted.zoneTransferTsigKeyNames !== undefined) {
if (!takesTransferAndNotify) return { error: `A ${type} zone has no zone transfer to set.` };
const mode = wanted.zoneTransfer ?? current.zoneTransfer;
if (mode === null) return { error: "The zone's transfer setting is not known, so it is not changed from here." };
let list: string[] = [];
if (usesAcl(mode)) {
const r = acl(wanted.zoneTransferNetworkACL, current.zoneTransferNetworkACL, "Zone transfer");
if (typeof r === "string") return { error: r };
list = r;
}
const keys = wanted.zoneTransferTsigKeyNames ?? current.zoneTransferTsigKeyNames;
const unknown = keys.find((k) => !current.availableTsigKeyNames.includes(k));
if (unknown !== undefined) return { error: `The server has no TSIG key called "${unknown}".` };
if (mode !== current.zoneTransfer || (usesAcl(mode) && !sameInOrder(list, current.zoneTransferNetworkACL)) || !sameAsSet(keys, current.zoneTransferTsigKeyNames)) {
send.zoneTransfer = mode as ZoneTransfer;
if (usesAcl(mode)) send.zoneTransferNetworkACL = list;
send.zoneTransferTsigKeyNames = keys;
changed.push("zoneTransfer");
}
}
if (wanted.notify !== undefined || wanted.notifyNameServers !== undefined) {
if (!takesTransferAndNotify) return { error: `A ${type} zone has no notify setting to set here.` };
const mode = wanted.notify ?? current.notify;
if (mode === null) return { error: "The zone's notify setting is not known, so it is not changed from here." };
let servers: string[] = [];
if (usesNameServers(mode)) {
servers = (wanted.notifyNameServers ?? current.notifyNameServers).map((s) => s.trim());
if (servers.length === 0) return { error: "Notify goes to named servers, and none is named." };
const bad = servers.find((s) => net.isIP(s) === 0);
if (bad !== undefined) return { error: `"${bad}" is not an address of a server to notify.` };
}
if (mode !== current.notify || (usesNameServers(mode) && !sameAsSet(servers, current.notifyNameServers))) {
send.notify = mode as NotifyMode;
if (usesNameServers(mode)) send.notifyNameServers = servers;
changed.push("notify");
}
}
return { send, changed };
}
/** The things the zone says that an edit did not mean to change but did — by comparing what it said (`other`) before and after. Empty when nothing else moved. */
export function unexpectedChanges(before: DnsZoneOptions, after: DnsZoneOptions): string[] {
const names = new Set([...Object.keys(before.other), ...Object.keys(after.other)]);
return [...names].filter((n) => before.other[n] !== after.other[n]).sort();
}
+111 -3
View File
@@ -1,4 +1,4 @@
import { Router } from "express";
import { Router, type Request, type Response } from "express";
import { eq, and } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
@@ -11,7 +11,8 @@ import {
splitProviderConfig,
validateProviderConfig,
} from "../dns/providerSchemas.js";
import { createDnsAdapter, ZONE_CREATING_PROVIDERS, ZONE_DELETING_PROVIDERS } from "../dns/registry.js";
import { createDnsAdapter, ZONE_CREATING_PROVIDERS, ZONE_DELETING_PROVIDERS, ZONE_EDITING_PROVIDERS } from "../dns/registry.js";
import { NOTIFY_MODES, planOptionsChange, QUERY_ACCESS, unexpectedChanges, ZONE_TRANSFER, type DnsZoneOptions } from "../dns/zoneOptions.js";
import { normaliseZoneName } from "../dns/zoneNames.js";
import { loadDnsProviderConfig, getDnsAdapterForProvider } from "../dns/loadProvider.js";
import { getDnsStats } from "../dns/stats.js";
@@ -56,7 +57,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), canDeleteZones: ZONE_DELETING_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), canEditZones: ZONE_EDITING_PROVIDERS.has(r.providerType) })) });
}));
const configValueSchema = z.union([z.string(), z.boolean()]);
@@ -331,6 +332,113 @@ dnsRouter.post("/providers/:id/zones", requireRole("admin"), asyncHandler(async
}
}));
/** The provider and the zone an edit is about, or the answer to send when it cannot be: an id that is no zone name, a provider that is not there, is switched off or cannot edit zones. */
async function loadEditableZone(req: Request, res: Response) {
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) {
res.status(400).json({ error: "invalid_id" });
return null;
}
const found = await getDnsAdapterForProvider(providerId);
if (!found) {
res.status(404).json({ error: "not_found" });
return null;
}
if (!found.provider.enabled) {
res.status(400).json({ error: "provider_disabled", message: "This provider is switched off." });
return null;
}
const { adapter } = found;
if (!ZONE_EDITING_PROVIDERS.has(found.provider.providerType) || !adapter.getZoneOptions || !adapter.setZoneEnabled || !adapter.setZoneOptions) {
res.status(400).json({ error: "not_supported", message: "Zones can't be edited from here on this kind of provider." });
return null;
}
return { providerId, zoneId, adapter: adapter as typeof adapter & Required<Pick<typeof adapter, "getZoneOptions" | "setZoneEnabled" | "setZoneOptions">> };
}
/** What the page is told of a zone's options: not what is only kept to see that an edit changed nothing else. */
const publicOptions = ({ other: _other, ...options }: DnsZoneOptions) => options;
const providerFailure = (res: Response, err: unknown) => res.status(502).json({ error: "dns_provider_error", message: err instanceof Error ? err.message : String(err) });
/** How a zone is set now — query access, zone transfer and notify, and whether it is switched off — and which TSIG keys the server has. An administrator's: the lists name networks. */
dnsRouter.get("/providers/:id/zones/:zoneId/options", requireRole("admin"), asyncHandler(async (req, res) => {
const ctx = await loadEditableZone(req, res);
if (!ctx) return;
try {
res.json({ options: publicOptions(await ctx.adapter.getZoneOptions(ctx.zoneId)) });
} catch (err) {
providerFailure(res, err);
}
}));
const enabledSchema = z.object({ enabled: z.boolean() });
/** Switches a zone off or on again. Off, the server no longer answers for the zone; its records stay, and on brings it all back. One of the server's own zones is not touched. */
dnsRouter.post("/providers/:id/zones/:zoneId/enabled", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = enabledSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say whether the zone is to be on or off." });
const ctx = await loadEditableZone(req, res);
if (!ctx) return;
try {
const options = await ctx.adapter.getZoneOptions(ctx.zoneId);
if (options.internal) return res.status(409).json({ error: "refused", message: "That is one of the server's own zones." });
if (options.disabled === !parsed.data.enabled) return res.json({ enabled: parsed.data.enabled, changed: false });
await ctx.adapter.setZoneEnabled(ctx.zoneId, parsed.data.enabled);
} catch (err) {
return providerFailure(res, err);
}
await recordAudit({ actor: req.currentUser!, category: "dns", action: parsed.data.enabled ? "enable_zone" : "disable_zone", targetType: "dns_zone", targetId: ctx.zoneId, detail: { providerId: ctx.providerId, name: ctx.zoneId } });
res.json({ enabled: parsed.data.enabled, changed: true });
}));
const aclList = z.array(z.string().trim().min(1).max(80)).max(100);
const optionsChangeSchema = z
.object({
queryAccess: z.enum(QUERY_ACCESS).optional(),
queryAccessNetworkACL: aclList.optional(),
zoneTransfer: z.enum(ZONE_TRANSFER).optional(),
zoneTransferNetworkACL: aclList.optional(),
zoneTransferTsigKeyNames: z.array(z.string().trim().min(1).max(255)).max(50).optional(),
notify: z.enum(NOTIFY_MODES).optional(),
notifyNameServers: z.array(z.string().trim().min(1).max(80)).max(20).optional(),
})
.strict();
/**
* Changes who may ask a zone, who may copy it and who is told when it changes. What is asked is checked against the kind of zone it is and what it has now (see dns/zoneOptions.ts); only the
* groups that differ are sent, each whole. Technitium does not say what it does with a setting that is not mentioned, so afterwards the zone is read again and anything else that moved is said.
* One of the server's own zones is not touched.
*/
dnsRouter.patch("/providers/:id/zones/:zoneId/options", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = optionsChangeSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "That is not a change of a zone's options.", details: parsed.error.flatten() });
const ctx = await loadEditableZone(req, res);
if (!ctx) return;
let before: DnsZoneOptions;
let plan: ReturnType<typeof planOptionsChange>;
try {
before = await ctx.adapter.getZoneOptions(ctx.zoneId);
if (before.internal) return res.status(409).json({ error: "refused", message: "That is one of the server's own zones." });
plan = planOptionsChange(before.type, before, parsed.data);
if ("error" in plan) return res.status(400).json({ error: "invalid_options", message: plan.error });
if (plan.changed.length === 0) return res.json({ changed: [], unexpected: [], options: publicOptions(before) });
await ctx.adapter.setZoneOptions(ctx.zoneId, plan.send);
} catch (err) {
return providerFailure(res, err);
}
let after: DnsZoneOptions | null = null;
try {
after = await ctx.adapter.getZoneOptions(ctx.zoneId);
} catch {
// The change was made; only the read-back failed.
}
const unexpected = after ? unexpectedChanges(before, after) : [];
await recordAudit({ actor: req.currentUser!, category: "dns", action: "update_zone_options", targetType: "dns_zone", targetId: ctx.zoneId, detail: { providerId: ctx.providerId, name: ctx.zoneId, changed: plan.changed, ...(unexpected.length > 0 ? { unexpected } : {}) } });
res.json({ changed: plan.changed, unexpected, options: after ? publicOptions(after) : null });
}));
const deleteZoneSchema = z.object({ name: z.string().min(1).max(300) });
/**
+464
View File
@@ -0,0 +1,464 @@
/**
* Editing a Technitium zone: switching it off and on, and its options (who may ask it, who may copy it, who is told when it changes) — how an edit is checked and planned against the kind of zone
* and what it has now, what is sent to Technitium, what is said when something else moved, who may, what is refused 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-zopts-"));
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 zo = await import("../src/dns/zoneOptions.js");
const { createTechnitiumAdapter } = await import("../src/dns/adapters/technitium.js");
const { dnsRouter } = await import("../src/routes/dns.js");
await runMigrations();
const opts = (over: Partial<import("../src/dns/zoneOptions.js").DnsZoneOptions> = {}): import("../src/dns/zoneOptions.js").DnsZoneOptions => ({
name: "home.lan",
type: "Primary",
internal: false,
disabled: false,
queryAccess: "Allow",
queryAccessNetworkACL: [],
zoneTransfer: "Deny",
zoneTransferNetworkACL: [],
zoneTransferTsigKeyNames: [],
notify: "ZoneNameServers",
notifyNameServers: [],
availableTsigKeyNames: ["key.lan", "catalog"],
other: {},
...over,
});
const plan = (type: string, current: ReturnType<typeof opts>, wanted: import("../src/dns/zoneOptions.js").ZoneOptionsChange) => zo.planOptionsChange(type, current, wanted);
const ok = (p: ReturnType<typeof plan>) => {
assert.ok(!("error" in p), "error" in p ? p.error : "");
return p;
};
const failure = (p: ReturnType<typeof plan>) => {
assert.ok("error" in p, "expected an error");
return (p as { error: string }).error;
};
describe("a network list entry", () => {
test("an address or a network, with ! to refuse it, in the form it is sent", () => {
assert.equal(zo.aclEntry("192.168.1.0/24"), "192.168.1.0/24");
assert.equal(zo.aclEntry(" !10.0.0.5 "), "!10.0.0.5");
assert.equal(zo.aclEntry("FD00::/8"), "fd00::/8");
assert.equal(zo.aclEntry("::1"), "::1");
});
test("anything else is not: text, a network too big for its kind, an empty refusal", () => {
for (const bad of ["", "!", "lan", "192.168.1.0/33", "fd00::/129", "300.1.1.1", "10.0.0.1/", "10.0.0.1,10.0.0.2", "a b"]) assert.equal(zo.aclEntry(bad), null, JSON.stringify(bad));
});
});
describe("what an edit comes to", () => {
test("what is already so is no change, and nothing is sent", () => {
const p = ok(plan("Primary", opts(), { queryAccess: "Allow", zoneTransfer: "Deny", notify: "ZoneNameServers" }));
assert.deepEqual([p.changed, "send" in p ? p.send : null], [[], {}]);
});
test("only the group that differs is sent; a mode that does not go by a list sends none", () => {
const p = ok(plan("Primary", opts({ queryAccessNetworkACL: ["10.0.0.0/8"] }), { queryAccess: "AllowOnlyPrivateNetworks", zoneTransfer: "Deny" }));
assert.deepEqual("send" in p ? p.send : null, { queryAccess: "AllowOnlyPrivateNetworks" });
assert.deepEqual(p.changed, ["queryAccess"]);
});
test("a mode that goes by a list needs the list, written as addresses and networks", () => {
assert.match(failure(plan("Primary", opts(), { queryAccess: "UseSpecifiedNetworkACL" })), /list of networks, and the list is empty/);
assert.match(failure(plan("Primary", opts(), { queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["home"] })), /"home" is not an address or a network/);
const p = ok(plan("Primary", opts(), { queryAccess: "AllowZoneNameServersAndUseSpecifiedNetworkACL", queryAccessNetworkACL: ["192.168.1.0/24", " !192.168.1.66"] }));
assert.deepEqual("send" in p ? p.send : null, { queryAccess: "AllowZoneNameServersAndUseSpecifiedNetworkACL", queryAccessNetworkACL: ["192.168.1.0/24", "!192.168.1.66"] });
});
test("a list changed under the same mode is a change — in its order, which matters — and the mode is sent with it", () => {
const cur = opts({ queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["10.0.0.0/8", "!10.0.0.5"] });
assert.deepEqual(ok(plan("Primary", cur, { queryAccessNetworkACL: ["10.0.0.0/8", "!10.0.0.5"] })).changed, []);
const swapped = ok(plan("Primary", cur, { queryAccessNetworkACL: ["!10.0.0.5", "10.0.0.0/8"] }));
assert.deepEqual(["send" in swapped ? swapped.send : null, swapped.changed], [{ queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["!10.0.0.5", "10.0.0.0/8"] }, ["queryAccess"]]);
});
test("zone transfer: the keys it is limited to must be ones the server has; they are sent with the mode, and none is a change to none", () => {
assert.match(failure(plan("Primary", opts(), { zoneTransfer: "Allow", zoneTransferTsigKeyNames: ["nope.lan"] })), /no TSIG key called "nope\.lan"/);
const p = ok(plan("Primary", opts(), { zoneTransfer: "AllowOnlyZoneNameServers", zoneTransferTsigKeyNames: ["key.lan"] }));
assert.deepEqual("send" in p ? p.send : null, { zoneTransfer: "AllowOnlyZoneNameServers", zoneTransferTsigKeyNames: ["key.lan"] });
const cleared = ok(plan("Primary", opts({ zoneTransfer: "Allow", zoneTransferTsigKeyNames: ["key.lan", "catalog"] }), { zoneTransferTsigKeyNames: [] }));
assert.deepEqual("send" in cleared ? cleared.send : null, { zoneTransfer: "Allow", zoneTransferTsigKeyNames: [] });
assert.deepEqual(ok(plan("Primary", opts({ zoneTransfer: "Allow", zoneTransferTsigKeyNames: ["key.lan", "catalog"] }), { zoneTransferTsigKeyNames: ["catalog", "key.lan"] })).changed, [], "the order of keys is not a change");
});
test("notify: named servers need addresses; a mode that names none sends none", () => {
assert.match(failure(plan("Primary", opts(), { notify: "SpecifiedNameServers" })), /none is named/);
assert.match(failure(plan("Primary", opts(), { notify: "SpecifiedNameServers", notifyNameServers: ["ns1.lan"] })), /"ns1\.lan" is not an address/);
const p = ok(plan("Primary", opts(), { notify: "BothZoneAndSpecifiedNameServers", notifyNameServers: ["10.0.0.2", "fd00::2"] }));
assert.deepEqual("send" in p ? p.send : null, { notify: "BothZoneAndSpecifiedNameServers", notifyNameServers: ["10.0.0.2", "fd00::2"] });
const none = ok(plan("Primary", opts({ notify: "SpecifiedNameServers", notifyNameServers: ["10.0.0.2"] }), { notify: "None" }));
assert.deepEqual("send" in none ? none.send : null, { notify: "None" });
});
test("what a kind of zone does not have is refused: a Forwarder neither transfers nor notifies here, a secondary catalog has no query access", () => {
assert.match(failure(plan("Forwarder", opts({ type: "Forwarder" }), { zoneTransfer: "Allow" })), /Forwarder zone has no zone transfer/);
assert.match(failure(plan("Forwarder", opts({ type: "Forwarder" }), { notify: "None" })), /Forwarder zone has no notify/);
assert.match(failure(plan("SecondaryCatalog", opts({ type: "SecondaryCatalog" }), { queryAccess: "Deny" })), /no query access/);
assert.deepEqual(ok(plan("Forwarder", opts({ type: "Forwarder" }), { queryAccess: "Deny" })).changed, ["queryAccess"]);
});
test("a zone whose mode the provider did not say is not changed blindly", () => {
assert.match(failure(plan("Primary", opts({ queryAccess: null }), { queryAccessNetworkACL: ["10.0.0.0/8"] })), /not known/);
assert.match(failure(plan("Primary", opts({ notify: null }), { notifyNameServers: ["10.0.0.2"] })), /not known/);
});
test("what else the zone says that moved is named; what did not is not", () => {
const before = opts({ other: { update: '"Deny"', catalog: '"c1"', dnssecStatus: '"Unsigned"' } });
assert.deepEqual(zo.unexpectedChanges(before, opts({ other: { update: '"Deny"', catalog: '"c1"', dnssecStatus: '"Unsigned"' } })), []);
assert.deepEqual(zo.unexpectedChanges(before, opts({ other: { update: '"Allow"', dnssecStatus: '"Unsigned"' } })), ["catalog", "update"]);
});
});
/** A Technitium with a few zones that keeps the options it is given, and can be told to forget something it was not asked to change. */
interface ZoneState {
name: string;
type: string;
internal: boolean;
disabled: boolean;
queryAccess: string;
queryAccessNetworkACL: string[];
zoneTransfer: string;
zoneTransferNetworkACL: string[];
zoneTransferTsigKeyNames: string[];
notify: string;
notifyNameServers: string[];
update: string;
updateNetworkACL: string[];
catalog: string;
notifyFailed: boolean;
}
const fresh = (): Map<string, ZoneState> =>
new Map(
[
["home.lan", "Primary"],
["mirror.lan", "Secondary"],
["corp.example", "Forwarder"],
["localhost", "Primary"],
].map(([name, type]) => [
name,
{ name, type, internal: name === "localhost", disabled: false, queryAccess: "Allow", queryAccessNetworkACL: [], zoneTransfer: "Deny", zoneTransferNetworkACL: [], zoneTransferTsigKeyNames: [], notify: "ZoneNameServers", notifyNameServers: [], update: "UseSpecifiedNetworkACL", updateNetworkACL: ["192.168.180.0/24"], catalog: "catalog1", notifyFailed: false },
]),
);
let zones = fresh();
let forgetUpdates = false;
let refuse: string | null = null;
const seen: { path: string; auth: string; form: Record<string, string> }[] = [];
let fake: Server;
let fakeUrl = "";
before(async () => {
fake = createHttpServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
const u = new URL(req.url ?? "", "http://x");
const form = Object.fromEntries(new URLSearchParams(body));
const query = Object.fromEntries(u.searchParams);
seen.push({ path: u.pathname, auth: String(req.headers.authorization ?? ""), form: { ...query, ...form } });
const send = (json: unknown) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(json));
};
const params = { ...query, ...form };
const zone = zones.get(params.zone ?? "");
if (u.pathname === "/api/zones/list") return send({ status: "ok", response: { zones: [...zones.values()].map((z) => ({ name: z.name, type: z.type, internal: z.internal, disabled: z.disabled })) } });
if (refuse !== null && u.pathname !== "/api/zones/options/get") return send({ status: "error", errorMessage: refuse });
if (!zone) return send({ status: "error", errorMessage: `No such zone was found: ${params.zone}` });
if (u.pathname === "/api/zones/options/get") {
const { name, type, internal, disabled, queryAccess, queryAccessNetworkACL, zoneTransfer, zoneTransferNetworkACL, zoneTransferTsigKeyNames, notify, notifyNameServers, update, updateNetworkACL, catalog, notifyFailed } = zone;
return send({ status: "ok", response: { name, type, internal, disabled, dnssecStatus: "Unsigned", notifyFailed, notifyFailedFor: [], catalog, queryAccess, queryAccessNetworkACL, zoneTransfer, zoneTransferNetworkACL, zoneTransferTsigKeyNames, notify, notifyNameServers, update, updateNetworkACL, availableTsigKeyNames: ["key.lan", "catalog"] } });
}
if (u.pathname === "/api/zones/enable" || u.pathname === "/api/zones/disable") {
zone.disabled = u.pathname.endsWith("/disable");
return send({ status: "ok" });
}
if (u.pathname === "/api/zones/options/set") {
const list = (v: string) => (v === "false" ? [] : v.split(","));
if (params.queryAccess !== undefined) zone.queryAccess = params.queryAccess;
if (params.queryAccessNetworkACL !== undefined) zone.queryAccessNetworkACL = list(params.queryAccessNetworkACL);
if (params.zoneTransfer !== undefined) zone.zoneTransfer = params.zoneTransfer;
if (params.zoneTransferNetworkACL !== undefined) zone.zoneTransferNetworkACL = list(params.zoneTransferNetworkACL);
if (params.zoneTransferTsigKeyNames !== undefined) zone.zoneTransferTsigKeyNames = list(params.zoneTransferTsigKeyNames);
if (params.notify !== undefined) zone.notify = params.notify;
if (params.notifyNameServers !== undefined) zone.notifyNameServers = list(params.notifyNameServers);
// A server that sets what it is not told to back to its default.
if (forgetUpdates) {
zone.update = "Deny";
zone.updateNetworkACL = [];
}
return send({ status: "ok" });
}
res.writeHead(404);
res.end("{}");
});
});
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();
});
const reset = () => {
zones = fresh();
forgetUpdates = false;
refuse = null;
seen.length = 0;
};
describe("what is sent to Technitium", () => {
const adapter = () => createTechnitiumAdapter({ url: `${fakeUrl}/`, token: "tok-1" });
test("the options are read with the token in the header, asking which TSIG keys there are; what the server says that is not edited is kept aside", async () => {
reset();
const o = await adapter().getZoneOptions!("home.lan");
assert.deepEqual(seen[0].path, "/api/zones/options/get");
assert.deepEqual([seen[0].auth, seen[0].form], ["Bearer tok-1", { zone: "home.lan", includeAvailableTsigKeyNames: "true", includeAvailableCatalogZoneNames: "false" }]);
assert.deepEqual([o.name, o.type, o.internal, o.disabled, o.queryAccess, o.zoneTransfer, o.notify, o.availableTsigKeyNames], ["home.lan", "Primary", false, false, "Allow", "Deny", "ZoneNameServers", ["key.lan", "catalog"]]);
assert.deepEqual(Object.keys(o.other).sort(), ["catalog", "dnssecStatus", "update", "updateNetworkACL"]);
assert.equal(o.other.updateNetworkACL, '["192.168.180.0/24"]');
});
test("a zone is switched off and on with its own two calls", async () => {
reset();
await adapter().setZoneEnabled!("home.lan", false);
assert.deepEqual([seen[0].path, seen[0].form], ["/api/zones/disable", { zone: "home.lan" }]);
assert.equal(zones.get("home.lan")!.disabled, true);
await adapter().setZoneEnabled!("home.lan", true);
assert.equal(seen[1].path, "/api/zones/enable");
assert.equal(zones.get("home.lan")!.disabled, false);
});
test("the options go as the parameters Technitium names, lists comma-separated; a list of none is the word false", async () => {
reset();
await adapter().setZoneOptions!("home.lan", {
queryAccess: "UseSpecifiedNetworkACL",
queryAccessNetworkACL: ["10.0.0.0/8", "!10.0.0.5"],
zoneTransfer: "Allow",
zoneTransferTsigKeyNames: [],
notify: "SpecifiedNameServers",
notifyNameServers: ["10.0.0.2", "10.0.0.3"],
});
assert.deepEqual(seen[0].form, {
zone: "home.lan",
queryAccess: "UseSpecifiedNetworkACL",
queryAccessNetworkACL: "10.0.0.0/8,!10.0.0.5",
zoneTransfer: "Allow",
zoneTransferTsigKeyNames: "false",
notify: "SpecifiedNameServers",
notifyNameServers: "10.0.0.2,10.0.0.3",
});
});
test("the zone list says which are switched off and what kind they are", async () => {
reset();
zones.get("mirror.lan")!.disabled = true;
const list = await adapter().listZones();
assert.deepEqual(list.map((z) => [z.id, z.type, z.disabled]), [["home.lan", "Primary", false], ["mirror.lan", "Secondary", true], ["corp.example", "Forwarder", false]]);
});
test("what Technitium says when it refuses is the error", async () => {
reset();
refuse = "Access was denied to use Zones: Modify";
await assert.rejects(() => adapter().setZoneOptions!("home.lan", { queryAccess: "Deny" }), /Access was denied/);
await assert.rejects(() => adapter().setZoneEnabled!("home.lan", false), /Access was denied/);
});
});
describe("the routes", () => {
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 getOptions = (id: number, zone: string, sub = "admin") => fetch(`${base}/providers/${id}/zones/${encodeURIComponent(zone)}/options`, { headers: as(sub) });
const patch = (id: number, zone: string, body: unknown, sub = "admin") => fetch(`${base}/providers/${id}/zones/${encodeURIComponent(zone)}/options`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) });
const enable = (id: number, zone: string, enabled: unknown, sub = "admin") => fetch(`${base}/providers/${id}/zones/${encodeURIComponent(zone)}/enabled`, { method: "POST", headers: as(sub), body: JSON.stringify({ enabled }) });
const writes = () => seen.filter((s) => /\/(set|enable|disable)$/.test(s.path));
const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action);
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 edit zones", async () => {
const body = (await (await fetch(`${base}/providers`, { headers: as("viewer") })).json()) as { providers: { id: number; canEditZones: boolean }[] };
const can = Object.fromEntries(body.providers.map((p) => [p.id, p.canEditZones]));
assert.deepEqual([can[technitium], can[disabled], can[cloudflare]], [true, true, false]);
});
test("only an administrator reads or changes a zone's options or switches it; nothing reaches Technitium for anyone else", async () => {
reset();
for (const sub of ["viewer", "operator"]) {
assert.equal((await getOptions(technitium, "home.lan", sub)).status, 403, sub);
assert.equal((await patch(technitium, "home.lan", { queryAccess: "Deny" }, sub)).status, 403, sub);
assert.equal((await enable(technitium, "home.lan", false, sub)).status, 403, sub);
}
assert.deepEqual(seen, []);
});
test("the options a zone has now, without what is only kept aside", async () => {
reset();
const res = await getOptions(technitium, "home.lan");
assert.equal(res.status, 200);
const { options } = (await res.json()) as { options: Record<string, unknown> };
assert.deepEqual([options.name, options.type, options.queryAccess, options.availableTsigKeyNames], ["home.lan", "Primary", "Allow", ["key.lan", "catalog"]]);
assert.equal("other" in options, false);
});
test("switching a zone off and on: Technitium is asked, the audit log says who, and what is already so asks nothing", async () => {
reset();
const off = await enable(technitium, "home.lan", false);
assert.deepEqual(await off.json(), { enabled: false, changed: true });
assert.equal(zones.get("home.lan")!.disabled, true);
assert.deepEqual(writes().map((s) => s.path), ["/api/zones/disable"]);
const again = await enable(technitium, "home.lan", false);
assert.deepEqual(await again.json(), { enabled: false, changed: false });
assert.equal(writes().length, 1);
assert.deepEqual(await (await enable(technitium, "home.lan", true)).json(), { enabled: true, changed: true });
const entries = await audit("disable_zone");
assert.deepEqual([entries.length, entries[0].category, entries[0].targetType, entries[0].targetId], [1, "dns", "dns_zone", "home.lan"]);
assert.equal((await audit("enable_zone")).length, 1);
});
test("the server's own zones, a zone that is not there and a body that does not say on or off are not switched", async () => {
reset();
assert.equal((await enable(technitium, "localhost", false)).status, 409);
assert.equal((await enable(technitium, "nothere.lan", false)).status, 502, "Technitium's own words for it");
assert.equal((await enable(technitium, "home.lan", "yes")).status, 400);
assert.deepEqual(writes(), []);
});
test("an edit sends the group that differs, whole, and answers with the zone as it is now; the audit log names what changed", async () => {
reset();
const res = await patch(technitium, "home.lan", { queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["10.0.0.0/8", " !10.0.0.5"], zoneTransfer: "Deny" });
assert.equal(res.status, 200);
const body = (await res.json()) as { changed: string[]; unexpected: string[]; options: { queryAccess: string; queryAccessNetworkACL: string[] } };
assert.deepEqual([body.changed, body.unexpected, body.options.queryAccess, body.options.queryAccessNetworkACL], [["queryAccess"], [], "UseSpecifiedNetworkACL", ["10.0.0.0/8", "!10.0.0.5"]]);
assert.deepEqual(writes().map((s) => s.form), [{ zone: "home.lan", queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: "10.0.0.0/8,!10.0.0.5" }]);
const [entry] = await audit("update_zone_options");
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { providerId: technitium, name: "home.lan", changed: ["queryAccess"] });
});
test("an edit that changes nothing sends nothing and writes nothing", async () => {
reset();
const before = (await audit("update_zone_options")).length;
const res = await patch(technitium, "home.lan", { queryAccess: "Allow", notify: "ZoneNameServers" });
assert.deepEqual(((await res.json()) as { changed: string[] }).changed, []);
assert.deepEqual(writes(), []);
assert.equal((await audit("update_zone_options")).length, before);
});
test("if the server also changed something that was not asked, the answer and the audit log say so", async () => {
reset();
forgetUpdates = true;
const res = await patch(technitium, "home.lan", { notify: "None" });
assert.equal(res.status, 200);
const body = (await res.json()) as { changed: string[]; unexpected: string[] };
assert.deepEqual([body.changed, body.unexpected], [["notify"], ["update", "updateNetworkACL"]]);
const entries = await audit("update_zone_options");
assert.deepEqual(JSON.parse(entries.at(-1)!.detail ?? "{}").unexpected, ["update", "updateNetworkACL"]);
});
test("what is wrong with an edit is said before anything is sent: a kind of zone, a missing list, a key or a field that does not exist, a value that is no mode", async () => {
reset();
const bad: [string, unknown][] = [
["corp.example", { zoneTransfer: "Allow" }],
["corp.example", { notify: "None" }],
["home.lan", { queryAccess: "UseSpecifiedNetworkACL" }],
["home.lan", { queryAccess: "UseSpecifiedNetworkACL", queryAccessNetworkACL: ["lan"] }],
["home.lan", { zoneTransfer: "Allow", zoneTransferTsigKeyNames: ["nope"] }],
["home.lan", { notify: "SpecifiedNameServers", notifyNameServers: [] }],
["home.lan", { queryAccess: "Everyone" }],
["home.lan", { notify: "SeparateNameServersForCatalogAndMemberZones" }],
["home.lan", { disabled: true }],
["home.lan", { queryAccessNetworkACL: "10.0.0.0/8" }],
];
for (const [zone, body] of bad) {
const res = await patch(technitium, zone, body);
assert.equal(res.status, 400, JSON.stringify([zone, body]));
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
}
assert.deepEqual(writes(), []);
});
test("a Forwarder's query access can be changed; a zone name that is not written as one, and the server's own zones, are refused", async () => {
reset();
assert.equal((await patch(technitium, "corp.example", { queryAccess: "Deny" })).status, 200);
assert.equal(zones.get("corp.example")!.queryAccess, "Deny");
for (const bad of ["Home.LAN", "home.lan.", "a b", "a/b"]) assert.equal((await patch(technitium, bad, { queryAccess: "Deny" })).status, 400, bad);
assert.equal((await patch(technitium, "localhost", { queryAccess: "Deny" })).status, 409);
assert.equal(zones.get("localhost")!.queryAccess, "Allow");
});
test("what Technitium says when it refuses is passed on, and nothing is written in the audit log", async () => {
reset();
const before = (await audit("update_zone_options")).length;
refuse = "Access was denied to use Zones: Modify";
const res = await patch(technitium, "home.lan", { queryAccess: "Deny" });
assert.equal(res.status, 502);
assert.match(((await res.json()) as { message: string }).message, /Access was denied/);
assert.equal((await audit("update_zone_options")).length, before);
});
test("a provider that cannot edit zones, a switched-off one, an unknown one and an id that is no id are not asked", async () => {
reset();
const unsupported = await patch(cloudflare, "home.lan", { queryAccess: "Deny" });
assert.equal(((await unsupported.json()) as { error: string }).error, "not_supported");
assert.equal(((await (await patch(disabled, "home.lan", { queryAccess: "Deny" })).json()) as { error: string }).error, "provider_disabled");
assert.equal((await patch(999999, "home.lan", { queryAccess: "Deny" })).status, 404);
assert.equal((await fetch(`${base}/providers/abc/zones/home.lan/options`, { headers: as("admin") })).status, 400);
assert.deepEqual(seen, []);
});
});