diff --git a/README.md b/README.md index bb87fc3..344d1f7 100644 --- a/README.md +++ b/README.md @@ -349,6 +349,9 @@ caches nothing, so an installed copy always shows the current build. ## 2. Local development +_Tests:_ `npm test --workspace server` runs the server's regression tests (Node's built-in runner, no extra setup) — among them a check that an ID in a +request can't be turned into a different call to a connected system (Tailscale, Proxmox, Gitea, Dockhand, Cloudflare, Azure). + ```bash cp .env.example .env # fill in AUTHENTIK_*, SESSION_SECRET, CREDENTIALS_ENCRYPTION_KEY npm install diff --git a/server/package.json b/server/package.json index 8ef9270..209d1f9 100644 --- a/server/package.json +++ b/server/package.json @@ -7,6 +7,7 @@ "dev": "tsx watch src/index.ts", "build": "tsc -p tsconfig.json", "start": "node dist/index.js", + "test": "tsx --test \"test/**/*.test.ts\"", "db:generate": "drizzle-kit generate", "db:migrate": "tsx src/db/migrate.ts" }, diff --git a/server/src/dns/adapters/azure.ts b/server/src/dns/adapters/azure.ts index d02554e..a05fef9 100644 --- a/server/src/dns/adapters/azure.ts +++ b/server/src/dns/adapters/azure.ts @@ -10,6 +10,7 @@ */ import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone } from "../types.js"; import { withDiagLogging } from "../../services/diagLog.js"; +import { ID_PATTERNS, InvalidIdentifierError, pathSegment } from "../../utils/pathSegment.js"; const ARM_BASE = "https://management.azure.com"; const API_VERSION = "2018-05-01"; @@ -80,8 +81,22 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter { return `${resourceGroup}::${zoneName}`; } + // Resource group, zone, record name and type all come from the request (a zone ID, a record ID, a record's name), so each is + // checked before it goes into an ARM path — see utils/pathSegment. "@" (the zone apex) is a legal path character, kept as is. + function zonePath(resourceGroup: string, zoneName: string) { + const group = pathSegment(resourceGroup, "resource group", ID_PATTERNS.azureResourceGroup); + const zone = pathSegment(zoneName, "DNS zone", ID_PATTERNS.azureZone); + return `/subscriptions/${config.subscriptionId}/resourceGroups/${group}/providers/Microsoft.Network/dnsZones/${zone}`; + } + function recordPath(resourceGroup: string, zoneName: string, type: string, relName: string) { + const kind = pathSegment(type, "record type", ID_PATTERNS.azureRecordType); + const name = pathSegment(relName, "record name", ID_PATTERNS.azureRecordSet).replace(/%40/g, "@"); + return `${zonePath(resourceGroup, zoneName)}/${kind}/${name}`; + } + function decodeZoneId(zoneId: string) { const idx = zoneId.indexOf("::"); + if (idx < 0) throw new InvalidIdentifierError("zone ID"); return { resourceGroup: zoneId.slice(0, idx), zoneName: zoneId.slice(idx + 2) }; } @@ -127,7 +142,7 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter { async function listRecords(zoneId: string): Promise { const { resourceGroup, zoneName } = decodeZoneId(zoneId); - const path = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/recordSets`; + const path = `${zonePath(resourceGroup, zoneName)}/recordSets`; const data = await armFetch(path); const records: DnsRecord[] = []; @@ -232,7 +247,7 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter { if (relName.endsWith(`.${zoneName}`)) relName = relName.slice(0, -(zoneName.length + 1)); if (relName === zoneName) relName = "@"; - const path = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/${record.type}/${relName}`; + const path = recordPath(resourceGroup, zoneName, record.type, relName); let existing: any = null; try { @@ -268,8 +283,8 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter { if (newRelName.endsWith(`.${zoneName}`)) newRelName = newRelName.slice(0, -(zoneName.length + 1)); if (newRelName === zoneName) newRelName = "@"; - const oldPath = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/${type}/${oldRelName}`; - const newPath = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/${type}/${newRelName}`; + const oldPath = recordPath(resourceGroup, zoneName, type, oldRelName); + const newPath = recordPath(resourceGroup, zoneName, type, newRelName); let existing: any = null; try { @@ -313,7 +328,7 @@ export function createAzureAdapter(config: AzureConfig): DnsAdapter { const type = parts[1]; const content = parts.slice(2).join("::"); - const path = `/subscriptions/${config.subscriptionId}/resourceGroups/${resourceGroup}/providers/Microsoft.Network/dnsZones/${zoneName}/${type}/${relName}`; + const path = recordPath(resourceGroup, zoneName, type, relName); const existing = await armFetch(path); const props = existing.properties; diff --git a/server/src/dns/adapters/cloudflare.ts b/server/src/dns/adapters/cloudflare.ts index f6d9e98..85951ff 100644 --- a/server/src/dns/adapters/cloudflare.ts +++ b/server/src/dns/adapters/cloudflare.ts @@ -4,6 +4,7 @@ */ import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone } from "../types.js"; import { withDiagLogging } from "../../services/diagLog.js"; +import { ID_PATTERNS, pathSegment } from "../../utils/pathSegment.js"; const BASE = "https://api.cloudflare.com/client/v4"; @@ -19,6 +20,10 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter { }; } + // Zone and record IDs come from the request. Cloudflare's are always 32 hex characters (see utils/pathSegment). + const zone = (id: string) => pathSegment(id, "zone ID", ID_PATTERNS.cloudflareId); + const rec = (id: string) => pathSegment(id, "record ID", ID_PATTERNS.cloudflareId); + async function cfFetch(path: string, options: RequestInit = {}) { const res = await fetch(`${BASE}${path}`, { ...options, headers: headers() }); const data = await res.json(); @@ -45,7 +50,7 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter { let page = 1; let all: any[] = []; while (true) { - const result = await cfFetch(`/zones/${zoneId}/dns_records?per_page=100&page=${page}`); + const result = await cfFetch(`/zones/${zone(zoneId)}/dns_records?per_page=100&page=${page}`); all = all.concat(result); if (result.length < 100) break; page++; @@ -75,7 +80,7 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter { async function addRecord(zoneId: string, record: DnsRecordInput): Promise { const body = toBody(record); - const result = await cfFetch(`/zones/${zoneId}/dns_records`, { + const result = await cfFetch(`/zones/${zone(zoneId)}/dns_records`, { method: "POST", body: JSON.stringify(body), }); @@ -84,7 +89,7 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter { async function updateRecord(zoneId: string, recordId: string, record: DnsRecordInput): Promise { const body = toBody(record); - const result = await cfFetch(`/zones/${zoneId}/dns_records/${recordId}`, { + const result = await cfFetch(`/zones/${zone(zoneId)}/dns_records/${rec(recordId)}`, { method: "PATCH", body: JSON.stringify(body), }); @@ -92,7 +97,7 @@ export function createCloudflareAdapter(config: CloudflareConfig): DnsAdapter { } async function deleteRecord(zoneId: string, recordId: string): Promise { - await cfFetch(`/zones/${zoneId}/dns_records/${recordId}`, { method: "DELETE" }); + await cfFetch(`/zones/${zone(zoneId)}/dns_records/${rec(recordId)}`, { method: "DELETE" }); } return withDiagLogging("cloudflare", { listZones, listRecords, addRecord, updateRecord, deleteRecord }); diff --git a/server/src/integrations/dockhand/adapter.ts b/server/src/integrations/dockhand/adapter.ts index a6c12a3..c227dc3 100644 --- a/server/src/integrations/dockhand/adapter.ts +++ b/server/src/integrations/dockhand/adapter.ts @@ -10,6 +10,7 @@ * (https://github.com/strausmann/mcp-dockhand/blob/main/docs/dockhand-openapi.json). */ import { withDiagLogging } from "../../services/diagLog.js"; +import { ID_PATTERNS, numericSegment, pathSegment } from "../../utils/pathSegment.js"; export interface DockhandConfig { url: string; @@ -140,15 +141,15 @@ export function createDockhandAdapter(config: DockhandConfig): DockhandAdapter { } async function startContainer(environmentId: number, containerId: string): Promise { - await api("POST", `/api/containers/${encodeURIComponent(containerId)}/start?env=${environmentId}`); + await api("POST", `/api/containers/${pathSegment(containerId, "container ID", ID_PATTERNS.container)}/start?env=${numericSegment(environmentId, "environment ID")}`); } async function stopContainer(environmentId: number, containerId: string): Promise { - await api("POST", `/api/containers/${encodeURIComponent(containerId)}/stop?env=${environmentId}`); + await api("POST", `/api/containers/${pathSegment(containerId, "container ID", ID_PATTERNS.container)}/stop?env=${numericSegment(environmentId, "environment ID")}`); } async function restartContainer(environmentId: number, containerId: string): Promise { - await api("POST", `/api/containers/${encodeURIComponent(containerId)}/restart?env=${environmentId}`); + await api("POST", `/api/containers/${pathSegment(containerId, "container ID", ID_PATTERNS.container)}/restart?env=${numericSegment(environmentId, "environment ID")}`); } async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> { diff --git a/server/src/integrations/gitea/adapter.ts b/server/src/integrations/gitea/adapter.ts index 489775d..2746125 100644 --- a/server/src/integrations/gitea/adapter.ts +++ b/server/src/integrations/gitea/adapter.ts @@ -6,6 +6,7 @@ * Verified against Gitea 1.27. */ import { withDiagLogging } from "../../services/diagLog.js"; +import { ID_PATTERNS, numericSegment, pathSegment } from "../../utils/pathSegment.js"; export interface GiteaConfig { url: string; @@ -112,7 +113,7 @@ export function createGiteaAdapter(config: GiteaConfig): GiteaAdapter { try { const data = await api( "GET", - `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/runs?limit=1&page=1`, + `/repos/${pathSegment(owner, "repository owner", ID_PATTERNS.giteaName)}/${pathSegment(repo, "repository name", ID_PATTERNS.giteaName)}/actions/runs?limit=1&page=1`, ); const run = data?.workflow_runs?.[0]; return run ? mapRun(run) : null; @@ -137,7 +138,7 @@ export function createGiteaAdapter(config: GiteaConfig): GiteaAdapter { async function rerunFailedJobs(owner: string, repo: string, runId: number): Promise { await api( "POST", - `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/runs/${runId}/rerun-failed-jobs`, + `/repos/${pathSegment(owner, "repository owner", ID_PATTERNS.giteaName)}/${pathSegment(repo, "repository name", ID_PATTERNS.giteaName)}/actions/runs/${numericSegment(runId, "run ID")}/rerun-failed-jobs`, ); } diff --git a/server/src/integrations/proxmox/adapter.ts b/server/src/integrations/proxmox/adapter.ts index 775597e..50dec5f 100644 --- a/server/src/integrations/proxmox/adapter.ts +++ b/server/src/integrations/proxmox/adapter.ts @@ -23,6 +23,7 @@ */ import * as https from "node:https"; import { withDiagLogging } from "../../services/diagLog.js"; +import { ID_PATTERNS, InvalidIdentifierError, numericSegment, pathSegment } from "../../utils/pathSegment.js"; export interface ProxmoxConfig { url: string; @@ -224,6 +225,14 @@ function request(url: string, insecure: boolean, options: { method?: string; hea export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter { const insecure = config.insecure === true; + // Node, guest type and VM number all end up in the request path, and they can come from a request — see utils/pathSegment. + const nodeSeg = (node: string) => pathSegment(node, "node name", ID_PATTERNS.proxmoxNode); + const typeSeg = (type: string) => { + if (type !== "qemu" && type !== "lxc") throw new InvalidIdentifierError("guest type"); + return type; + }; + const vmidSeg = (vmid: number) => numericSegment(vmid, "VM ID"); + function base() { return config.url.replace(/\/$/, ""); } @@ -258,7 +267,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter { } async function listGuestsForNode(node: string, type: ProxmoxGuestType): Promise { - const data = await api("GET", `/nodes/${node}/${type}`); + const data = await api("GET", `/nodes/${nodeSeg(node)}/${typeSeg(type)}`); return (Array.isArray(data) ? data : []).map((g: any) => ({ vmid: g.vmid, name: g.name, @@ -293,8 +302,8 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter { async function getGuestDetail(node: string, type: ProxmoxGuestType, vmid: number): Promise { const [config, status] = await Promise.all([ - api("GET", `/nodes/${node}/${type}/${vmid}/config`), - api("GET", `/nodes/${node}/${type}/${vmid}/status/current`), + api("GET", `/nodes/${nodeSeg(node)}/${typeSeg(type)}/${vmidSeg(vmid)}/config`), + api("GET", `/nodes/${nodeSeg(node)}/${typeSeg(type)}/${vmidSeg(vmid)}/status/current`), ]); let cpuCores: number | null = null; @@ -338,7 +347,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter { diskBytes = foundDisk ? totalDisk : null; try { - const agentData = await api("GET", `/nodes/${node}/qemu/${vmid}/agent/network-get-interfaces`); + const agentData = await api("GET", `/nodes/${nodeSeg(node)}/qemu/${vmidSeg(vmid)}/agent/network-get-interfaces`); const interfaces = agentData?.result ?? []; for (const iface of interfaces) { for (const addr of iface["ip-addresses"] ?? []) { @@ -358,7 +367,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter { // failing, e.g. on an older guest agent version, shouldn't hide IPs // the other command already got, or vice versa). try { - const fsData = await api("GET", `/nodes/${node}/qemu/${vmid}/agent/get-fsinfo`); + const fsData = await api("GET", `/nodes/${nodeSeg(node)}/qemu/${vmidSeg(vmid)}/agent/get-fsinfo`); for (const fs of fsData?.result ?? []) { // Entries with no backing "disk" (tmpfs, proc, overlay, snap loop // mounts, ...) aren't real storage — skip them, same convention @@ -421,8 +430,8 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter { // the other, so fetch them independently rather than losing both to // Promise.all's fail-fast behavior. const [statusResult, storageResult] = await Promise.allSettled([ - api("GET", `/nodes/${node}/status`), - api("GET", `/nodes/${node}/storage`), + api("GET", `/nodes/${nodeSeg(node)}/status`), + api("GET", `/nodes/${nodeSeg(node)}/storage`), ]); const status = statusResult.status === "fulfilled" ? statusResult.value : null; @@ -500,7 +509,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter { const perNode = await Promise.all( nodes.map(async (node) => { try { - const data = await api("GET", `/nodes/${node}/tasks?typefilter=vzdump&limit=${limitPerNode}`); + const data = await api("GET", `/nodes/${nodeSeg(node)}/tasks?typefilter=vzdump&limit=${limitPerNode}`); return (Array.isArray(data) ? data : []).map((t: any) => ({ node, upid: t.upid, @@ -520,7 +529,7 @@ export function createProxmoxAdapter(config: ProxmoxConfig): ProxmoxAdapter { } async function statusAction(node: string, type: ProxmoxGuestType, vmid: number, action: string): Promise { - await api("POST", `/nodes/${node}/${type}/${vmid}/status/${action}`); + await api("POST", `/nodes/${nodeSeg(node)}/${typeSeg(type)}/${vmidSeg(vmid)}/status/${action}`); } const startGuest = (node: string, type: ProxmoxGuestType, vmid: number) => statusAction(node, type, vmid, "start"); diff --git a/server/src/integrations/tailscale/adapter.ts b/server/src/integrations/tailscale/adapter.ts index e29380f..2000561 100644 --- a/server/src/integrations/tailscale/adapter.ts +++ b/server/src/integrations/tailscale/adapter.ts @@ -17,6 +17,7 @@ * needed. */ import { withDiagLogging } from "../../services/diagLog.js"; +import { ID_PATTERNS, pathSegment } from "../../utils/pathSegment.js"; const BASE = "https://api.tailscale.com"; @@ -113,11 +114,11 @@ export function createTailscaleAdapter(config: TailscaleConfig): TailscaleAdapte } async function deleteDevice(deviceId: string): Promise { - await api("DELETE", `/api/v2/device/${deviceId}`); + await api("DELETE", `/api/v2/device/${pathSegment(deviceId, "device ID", ID_PATTERNS.tailscaleDevice)}`); } async function setAuthorized(deviceId: string, authorized: boolean): Promise { - await api("POST", `/api/v2/device/${deviceId}/authorized`, { authorized }); + await api("POST", `/api/v2/device/${pathSegment(deviceId, "device ID", ID_PATTERNS.tailscaleDevice)}/authorized`, { authorized }); } async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> { diff --git a/server/src/routes/dns.ts b/server/src/routes/dns.ts index 99c4763..6d8239e 100644 --- a/server/src/routes/dns.ts +++ b/server/src/routes/dns.ts @@ -15,6 +15,7 @@ import { createDnsAdapter } from "../dns/registry.js"; import { loadDnsProviderConfig, getDnsAdapterForProvider } from "../dns/loadProvider.js"; import { getDnsStats } from "../dns/stats.js"; import { asyncHandler } from "../utils/asyncHandler.js"; +import { InvalidIdentifierError } from "../utils/pathSegment.js"; import { notifyDnsRecordAdded, notifyDnsRecordUpdated, notifyDnsRecordDeleted } from "../services/notify.js"; async function zoneNameFor(providerId: number, zoneId: string): Promise { @@ -354,6 +355,8 @@ dnsRouter.post("/providers/:id/zones/:zoneId/sync", requireRole("operator"), asy res.json({ records, syncedAt: now }); } catch (err) { + // A zone or record ID that isn't the kind of ID this provider uses (see utils/pathSegment.ts) — nothing was sent. + if (err instanceof InvalidIdentifierError) return res.status(400).json({ error: "invalid_id", message: err.message }); res.status(502).json({ error: err instanceof Error ? err.message : String(err) }); } })); @@ -406,6 +409,8 @@ dnsRouter.post("/providers/:id/zones/:zoneId/records", requireRole("operator"), res.status(201).json({ record: result }); } catch (err) { + // A zone or record ID that isn't the kind of ID this provider uses (see utils/pathSegment.ts) — nothing was sent. + if (err instanceof InvalidIdentifierError) return res.status(400).json({ error: "invalid_id", message: err.message }); res.status(502).json({ error: err instanceof Error ? err.message : String(err) }); } })); @@ -459,6 +464,8 @@ dnsRouter.put("/providers/:id/zones/:zoneId/records/:recordId", requireRole("ope res.json({ record: result }); } catch (err) { + // A zone or record ID that isn't the kind of ID this provider uses (see utils/pathSegment.ts) — nothing was sent. + if (err instanceof InvalidIdentifierError) return res.status(400).json({ error: "invalid_id", message: err.message }); res.status(502).json({ error: err instanceof Error ? err.message : String(err) }); } })); @@ -510,6 +517,8 @@ dnsRouter.delete("/providers/:id/zones/:zoneId/records/:recordId", requireRole(" res.status(204).end(); } catch (err) { + // A zone or record ID that isn't the kind of ID this provider uses (see utils/pathSegment.ts) — nothing was sent. + if (err instanceof InvalidIdentifierError) return res.status(400).json({ error: "invalid_id", message: err.message }); res.status(502).json({ error: err instanceof Error ? err.message : String(err) }); } })); diff --git a/server/src/routes/integrations.ts b/server/src/routes/integrations.ts index 0339f8d..17b1e83 100644 --- a/server/src/routes/integrations.ts +++ b/server/src/routes/integrations.ts @@ -25,6 +25,7 @@ import { createPbsAdapter } from "../integrations/pbs/adapter.js"; import { createOsTicketAdapter } from "../integrations/osticket/adapter.js"; import { attachMatchedServers, summarizeMonitors, toMatchableServers } from "../services/uptimeKumaMatch.js"; import { asyncHandler } from "../utils/asyncHandler.js"; +import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js"; export const integrationsRouter = Router(); @@ -315,6 +316,12 @@ integrationsRouter.post("/test", requireRole("admin"), asyncHandler(async (req, res.json(result); })); +// IDs taken from the URL end up in the request made to the connected system, under the integration's own credential. They're +// checked here (clear 400, nothing sent) and again inside each adapter (see utils/pathSegment.ts) — either alone would do. +function rejectInvalidId(res: Response, what: string) { + return res.status(400).json({ error: "invalid_id", message: `That isn't a valid ${what}.` }); +} + // ─── Tailscale ─────────────────────────────────────────────────────────────── /** @@ -370,6 +377,8 @@ integrationsRouter.post( const found = await requireTailscaleAdapter(req, res); if (!found) return; + if (!isValidId(req.params.deviceId, ID_PATTERNS.tailscaleDevice)) return rejectInvalidId(res, "device ID"); + const parsed = authorizeSchema.safeParse(req.body); if (!parsed.success) { return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() }); @@ -399,6 +408,8 @@ integrationsRouter.delete( const found = await requireTailscaleAdapter(req, res); if (!found) return; + if (!isValidId(req.params.deviceId, ID_PATTERNS.tailscaleDevice)) return rejectInvalidId(res, "device ID"); + try { await found.adapter.deleteDevice(req.params.deviceId); await recordAudit({ @@ -455,6 +466,9 @@ integrationsRouter.post( const found = await requireGiteaAdapter(req, res); if (!found) return; + if (!isValidId(req.params.owner, ID_PATTERNS.giteaName)) return rejectInvalidId(res, "repository owner"); + if (!isValidId(req.params.repo, ID_PATTERNS.giteaName)) return rejectInvalidId(res, "repository name"); + const runId = Number(req.params.runId); if (!Number.isInteger(runId)) { return res.status(400).json({ error: "invalid_run_id" }); @@ -549,6 +563,8 @@ for (const action of dockhandActions) { const found = await requireDockhandAdapter(req, res); if (!found) return; + if (!isValidId(req.params.containerId, ID_PATTERNS.container)) return rejectInvalidId(res, "container ID"); + const envId = Number(req.params.envId); if (!Number.isInteger(envId)) { return res.status(400).json({ error: "invalid_environment_id" }); @@ -716,6 +732,8 @@ for (const action of proxmoxActions) { const found = await requireProxmoxAdapter(req, res); if (!found) return; + if (!isValidId(req.params.node, ID_PATTERNS.proxmoxNode)) return rejectInvalidId(res, "node name"); + const vmid = Number(req.params.vmid); if (!Number.isInteger(vmid)) { return res.status(400).json({ error: "invalid_vmid" }); diff --git a/server/src/routes/servers.ts b/server/src/routes/servers.ts index 50da597..7ca5436 100644 --- a/server/src/routes/servers.ts +++ b/server/src/routes/servers.ts @@ -7,6 +7,7 @@ import { requireAuth, requireRole } from "../auth/middleware.js"; import { generateApiToken } from "../services/tokens.js"; import { recordAudit } from "../services/audit.js"; import { asyncHandler } from "../utils/asyncHandler.js"; +import { ID_PATTERNS } from "../utils/pathSegment.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { createProxmoxAdapter, type ProxmoxGuestType } from "../integrations/proxmox/adapter.js"; import { serverPortsRouter } from "./serverPorts.js"; @@ -106,7 +107,7 @@ const updateServerSchema = z hostname: z.string().max(255).optional(), description: z.string().max(500).optional(), proxmoxIntegrationId: z.number().int().nullable().optional(), - proxmoxNode: z.string().nullable().optional(), + proxmoxNode: z.string().regex(ID_PATTERNS.proxmoxNode, "Not a valid Proxmox node name.").nullable().optional(), proxmoxGuestType: z.enum(["qemu", "lxc"]).nullable().optional(), proxmoxVmid: z.number().int().nullable().optional(), hideProxmoxLink: z.boolean().optional(), diff --git a/server/src/utils/pathSegment.ts b/server/src/utils/pathSegment.ts new file mode 100644 index 0000000..97f9370 --- /dev/null +++ b/server/src/utils/pathSegment.ts @@ -0,0 +1,53 @@ +/** + * Keeping a value inside the one URL path segment it was meant for. + * + * Several routes take an ID from the request (a Tailscale device, a Proxmox node, a DNS record) and the adapter puts it into + * a call to that system, made with the integration's own credential. Left as it was typed, `x/../../tailnet/-/keys/k1` in a + * "delete device" request turns into a request for a different endpoint — one that button never offered, sent with a key + * that may be allowed to do far more. So every such ID is checked against what a real ID of that kind looks like, and only + * then encoded. Checking matters as much as encoding: encodeURIComponent leaves ".." untouched, and ".." is all it takes. + */ + +export class InvalidIdentifierError extends Error { + constructor(public readonly what: string) { + super(`That isn't a valid ${what}.`); + } +} + +/** + * What each kind of ID may look like. All of them must start with a letter or digit (or, for Gitea, be anything but "." + * and ".."), so a lone "." or ".." can never match, and none of them allow "/", "?", "#" or "%". + */ +export const ID_PATTERNS = { + /** Tailscale device IDs: "12345" or "nABC123CNTRL". */ + tailscaleDevice: /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/, + /** Proxmox node names are hostnames. */ + proxmoxNode: /^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$/, + /** Gitea user/organisation and repository names. */ + giteaName: /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/, + /** Docker container IDs and names. */ + container: /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/, + /** Cloudflare zone and record IDs: 32 hex characters. */ + cloudflareId: /^[a-f0-9]{32}$/, + /** Azure: resource group, DNS zone, record-set name ("@" is the zone apex, "*" a wildcard) and record type. */ + azureResourceGroup: /^[A-Za-z0-9_()-][A-Za-z0-9_.()-]{0,89}$/, + azureZone: /^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$/, + azureRecordSet: /^(?:@|[A-Za-z0-9_*][A-Za-z0-9_.*-]{0,253})$/, + azureRecordType: /^[A-Za-z]{1,10}$/, +} as const; + +export function isValidId(value: unknown, pattern: RegExp): value is string { + return typeof value === "string" && pattern.test(value); +} + +/** The value, encoded for use as one path segment — or an InvalidIdentifierError if it isn't the kind of ID it should be. */ +export function pathSegment(value: unknown, what: string, pattern: RegExp): string { + if (!isValidId(value, pattern)) throw new InvalidIdentifierError(what); + return encodeURIComponent(value); +} + +/** A whole number, for IDs like a VM number. */ +export function numericSegment(value: unknown, what: string): string { + if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new InvalidIdentifierError(what); + return String(value); +} diff --git a/server/test/pathInjection.test.ts b/server/test/pathInjection.test.ts new file mode 100644 index 0000000..9ffc060 --- /dev/null +++ b/server/test/pathInjection.test.ts @@ -0,0 +1,406 @@ +/** + * Regression tests for path injection into calls made to connected systems. + * + * An operator can start "delete device", "stop guest" or "delete DNS record" — each of which sends a request to another system + * under that integration's own credential. These tests send the crafted IDs that once let such a request be turned into a + * different one (an auth key deleted, every guest on a node stopped, a whole DNS zone deleted) and check that nothing is sent. + * Nothing here talks to a real system: outgoing HTTP calls are captured, and the Proxmox host is an address nothing listens on. + * + * Run with: npm test --workspace server + */ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import http from "node:http"; + +const dir = mkdtempSync(join(tmpdir(), "hm-path-test-")); +process.env.DATABASE_PATH = join(dir, "test.sqlite"); +process.env.SESSION_DIR = join(dir, "sessions"); +process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); + +const { ID_PATTERNS, InvalidIdentifierError, numericSegment, pathSegment, isValidId } = await import("../src/utils/pathSegment.js"); +const { createTailscaleAdapter } = await import("../src/integrations/tailscale/adapter.js"); +const { createProxmoxAdapter } = await import("../src/integrations/proxmox/adapter.js"); +const { createGiteaAdapter } = await import("../src/integrations/gitea/adapter.js"); +const { createDockhandAdapter } = await import("../src/integrations/dockhand/adapter.js"); +const { createCloudflareAdapter } = await import("../src/dns/adapters/cloudflare.js"); +const { createAzureAdapter } = await import("../src/dns/adapters/azure.js"); + +// The adapters record each call in the diagnostic log, so the database has to exist before any of them is used. +const { runMigrations } = await import("../src/db/migrate.js"); +await runMigrations(); + +// ─── Capturing outgoing calls ─────────────────────────────────────────────── + +type Call = { method: string; url: string }; +let calls: Call[] = []; +const realFetch = globalThis.fetch; +const ZONE = "a".repeat(32); +const RECORD = "b".repeat(32); + +globalThis.fetch = (async (input: unknown, init?: { method?: string }) => { + const url = String(input); + if (url.startsWith("http://127.0.0.1")) return realFetch(input as string, init as RequestInit); // the test's own requests to its app + calls.push({ method: init?.method ?? "GET", url: new URL(url).href }); // new URL(): what the request would really be after dot-segments are resolved + if (url.includes("login.microsoftonline.com")) { + return new Response(JSON.stringify({ access_token: "t", expires_in: 3600 }), { status: 200, headers: { "content-type": "application/json" } }); + } + if (url.startsWith("https://management.azure.com")) { + return new Response(JSON.stringify({ properties: { TTL: 300, ARecords: [{ ipv4Address: "1.2.3.4" }] }, value: [] }), { status: 200, headers: { "content-type": "application/json" } }); + } + return new Response(JSON.stringify({ success: true, result: { id: RECORD }, data: [], devices: [] }), { status: 200, headers: { "content-type": "application/json" } }); +}) as typeof fetch; + +const calledNothing = () => assert.deepEqual(calls, [], `a request was sent: ${JSON.stringify(calls)}`); +const refused = (what?: string) => (err: unknown) => err instanceof InvalidIdentifierError && (what === undefined || err.what === what); + +// What a crafted ID looks like: slashes (as Express decodes %2F), query/fragment characters, encoded and bare dot segments. +const CRAFTED = ["..", ".", "x/../../tailnet/-/keys/k1", "x/..", "../x", "pve/stopall?", "a?b", "a#b", "a%2f..%2f", "%2e%2e", "a/b", "a\\b", "", " ", "a b", "x".repeat(300)]; + +// ─── The helper ───────────────────────────────────────────────────────────── + +describe("pathSegment", () => { + test("accepts ordinary IDs and encodes them", () => { + assert.equal(pathSegment("nABC123CNTRL", "device ID", ID_PATTERNS.tailscaleDevice), "nABC123CNTRL"); + assert.equal(pathSegment("pve-1", "node name", ID_PATTERNS.proxmoxNode), "pve-1"); + assert.equal(pathSegment("my.repo-name_2", "repo", ID_PATTERNS.giteaName), "my.repo-name_2"); + assert.equal(pathSegment(ZONE, "zone", ID_PATTERNS.cloudflareId), ZONE); + }); + + test("refuses anything that could leave its path segment", () => { + for (const bad of CRAFTED) { + for (const [name, pattern] of Object.entries(ID_PATTERNS)) { + assert.equal(isValidId(bad, pattern), false, `${JSON.stringify(bad)} was accepted as ${name}`); + } + } + }); + + test("a dot segment is refused even though encodeURIComponent would leave it alone", () => { + assert.equal(encodeURIComponent(".."), ".."); + assert.throws(() => pathSegment("..", "device ID", ID_PATTERNS.tailscaleDevice), refused()); + assert.throws(() => pathSegment("..", "repository name", ID_PATTERNS.giteaName), refused()); + }); + + test("numbers", () => { + assert.equal(numericSegment(100, "VM ID"), "100"); + for (const bad of [-1, 1.5, NaN, Infinity, "100" as unknown as number, null as unknown as number]) assert.throws(() => numericSegment(bad, "VM ID"), refused()); + }); + + test("Azure record names keep the zone apex '@' and wildcards", () => { + assert.ok(isValidId("@", ID_PATTERNS.azureRecordSet)); + assert.ok(isValidId("*", ID_PATTERNS.azureRecordSet)); + assert.ok(isValidId("_dmarc", ID_PATTERNS.azureRecordSet)); + assert.ok(isValidId("www.sub", ID_PATTERNS.azureRecordSet)); + assert.ok(!isValidId("@/..", ID_PATTERNS.azureRecordSet)); + }); +}); + +// ─── The adapters, directly ───────────────────────────────────────────────── + +describe("adapters send nothing for a crafted ID, and the right thing for a real one", () => { + const tailscale = () => createTailscaleAdapter({ apiKey: "k", tailnet: "example.com" } as never); + const cloudflare = () => createCloudflareAdapter({ apiToken: "t" }); + const gitea = () => createGiteaAdapter({ url: "https://gitea.test", token: "t" }); + const dockhand = () => createDockhandAdapter({ url: "https://dockhand.test", token: "t" }); + const azure = () => createAzureAdapter({ tenantId: "t", clientId: "c", clientSecret: "s", subscriptionId: "sub" }); + // Nothing listens here, so a request that *was* attempted fails with a connection error — never with InvalidIdentifierError. + const proxmox = () => createProxmoxAdapter({ url: "https://127.0.0.1:1", tokenId: "u@pam!t", tokenSecret: "s", insecure: true } as never); + + test("Tailscale", async () => { + for (const bad of CRAFTED) { + calls = []; + await assert.rejects(() => tailscale().deleteDevice(bad), refused()); + await assert.rejects(() => tailscale().setAuthorized(bad, true), refused()); + calledNothing(); + } + calls = []; + await tailscale().deleteDevice("nabc123"); + assert.deepEqual(calls, [{ method: "DELETE", url: "https://api.tailscale.com/api/v2/device/nabc123" }]); + calls = []; + await tailscale().setAuthorized("nabc123", true); + assert.deepEqual(calls, [{ method: "POST", url: "https://api.tailscale.com/api/v2/device/nabc123/authorized" }]); + }); + + test("Cloudflare", async () => { + const record = { type: "A", name: "a.example.com", content: "1.2.3.4", ttl: 300 }; + for (const bad of CRAFTED) { + calls = []; + await assert.rejects(() => cloudflare().deleteRecord(ZONE, bad), refused()); + await assert.rejects(() => cloudflare().deleteRecord(bad, RECORD), refused()); + await assert.rejects(() => cloudflare().updateRecord(ZONE, bad, record), refused()); + await assert.rejects(() => cloudflare().updateRecord(bad, RECORD, record), refused()); + await assert.rejects(() => cloudflare().addRecord(bad, record), refused()); + await assert.rejects(() => cloudflare().listRecords(bad), refused()); + calledNothing(); + } + calls = []; + await cloudflare().deleteRecord(ZONE, RECORD); + assert.deepEqual(calls, [{ method: "DELETE", url: `https://api.cloudflare.com/client/v4/zones/${ZONE}/dns_records/${RECORD}` }]); + }); + + test("Gitea", async () => { + for (const bad of CRAFTED) { + calls = []; + await assert.rejects(() => gitea().rerunFailedJobs(bad, "repo", 1), refused()); + await assert.rejects(() => gitea().rerunFailedJobs("owner", bad, 1), refused()); + calledNothing(); + } + await assert.rejects(() => gitea().rerunFailedJobs("owner", "repo", -1), refused()); + calls = []; + await gitea().rerunFailedJobs("owner", "my.repo", 12); + assert.deepEqual(calls, [{ method: "POST", url: "https://gitea.test/api/v1/repos/owner/my.repo/actions/runs/12/rerun-failed-jobs" }]); + }); + + test("Dockhand", async () => { + for (const bad of CRAFTED) { + calls = []; + await assert.rejects(() => dockhand().stopContainer(1, bad), refused()); + await assert.rejects(() => dockhand().startContainer(1, bad), refused()); + await assert.rejects(() => dockhand().restartContainer(1, bad), refused()); + calledNothing(); + } + calls = []; + await dockhand().stopContainer(2, "abc123def"); + assert.equal(calls.length, 1); + assert.equal(new URL(calls[0].url).pathname.endsWith("/containers/abc123def/stop"), true); + assert.equal(new URL(calls[0].url).searchParams.get("env"), "2"); + }); + + test("Azure DNS", async () => { + const record = { type: "A", name: "a.example.com", content: "1.2.3.4", ttl: 300 }; + const zone = "rg-dns::example.com"; + for (const bad of CRAFTED.filter((v) => v !== "")) { + calls = []; + await assert.rejects(() => azure().deleteRecord(zone, `${bad}::A::1.2.3.4`), refused()); + await assert.rejects(() => azure().deleteRecord(zone, `www::${bad}::1.2.3.4`), refused()); + await assert.rejects(() => azure().deleteRecord(`${bad}::example.com`, "www::A::1.2.3.4"), refused()); + await assert.rejects(() => azure().deleteRecord(`rg-dns::${bad}`, "www::A::1.2.3.4"), refused()); + await assert.rejects(() => azure().updateRecord(zone, `${bad}::A::1.2.3.4`, record), refused()); + await assert.rejects(() => azure().addRecord(zone, { ...record, name: bad }), refused()); + await assert.rejects(() => azure().addRecord(zone, { ...record, type: bad }), refused()); + await assert.rejects(() => azure().listRecords(`rg-dns::${bad}`), refused()); + assert.equal(calls.filter((c) => c.url.startsWith("https://management.azure.com")).length, 0, `ARM was called for ${JSON.stringify(bad)}`); + } + // A missing "::" in a zone ID is a malformed ID too, not a path. + await assert.rejects(() => azure().listRecords("no-separator"), refused()); + + calls = []; + await azure().deleteRecord(zone, "www::A::1.2.3.4"); + const arm = calls.filter((c) => c.url.startsWith("https://management.azure.com")); + assert.ok(arm[0].url.includes("/resourceGroups/rg-dns/providers/Microsoft.Network/dnsZones/example.com/A/www?"), arm[0].url); + calls = []; + await azure().deleteRecord(zone, "@::A::1.2.3.4"); + assert.ok(calls.filter((c) => c.url.startsWith("https://management.azure.com"))[0].url.includes("/dnsZones/example.com/A/@?"), "the zone apex must stay '@'"); + }); + + test("Proxmox", async () => { + for (const bad of CRAFTED) { + await assert.rejects(() => proxmox().stopGuest(bad, "qemu", 100), refused("node name")); + await assert.rejects(() => proxmox().startGuest(bad, "lxc", 100), refused("node name")); + await assert.rejects(() => proxmox().getGuestDetail(bad, "qemu", 100), refused("node name")); + } + for (const bad of ["qemu/..", "..", "", "vm", "QEMU"]) await assert.rejects(() => proxmox().stopGuest("pve", bad as never, 100), refused("guest type")); + for (const bad of [-1, 1.5, NaN]) await assert.rejects(() => proxmox().stopGuest("pve", "qemu", bad), refused("VM ID")); + // A real node name is let through: the failure is now the connection (nothing listens on port 1), not the ID. + await assert.rejects( + () => proxmox().stopGuest("pve-1", "qemu", 100), + (err: unknown) => !(err instanceof InvalidIdentifierError), + ); + }); +}); + +// ─── The routes, as a signed-in operator ──────────────────────────────────── + +describe("routes", () => { + let server: http.Server; + let port = 0; + let operator = ""; + let viewer = ""; + let admin = ""; + let serverId = 0; + const lastBody = { text: "" }; + + before(async () => { + const express = (await import("express")).default; + const session = (await import("express-session")).default; + const { db } = await import("../src/db/client.js"); + const { users, integrations, integrationCredentials, dnsProviders, servers } = await import("../src/db/schema.js"); + const { encryptSecret } = await import("../src/crypto.js"); + const { integrationsRouter } = await import("../src/routes/integrations.js"); + const { dnsRouter } = await import("../src/routes/dns.js"); + const { serversRouter } = await import("../src/routes/servers.js"); + await db.insert(users).values([ + { oidcSub: "op", email: "op@x", name: "Operator", role: "operator" }, + { oidcSub: "vw", email: "vw@x", name: "Viewer", role: "viewer" }, + { oidcSub: "ad", email: "ad@x", name: "Admin", role: "admin" }, + ]); + const cred = async (name: string, secret: object) => + (await db.insert(integrationCredentials).values({ name, encryptedSecret: encryptSecret(JSON.stringify(secret)) }).returning())[0].id; + await db.insert(integrations).values([ + { type: "tailscale", name: "ts", baseUrl: "https://api.tailscale.com", credentialId: await cred("ts", { apiKey: "k" }), config: JSON.stringify({ tailnet: "example.com" }) }, + { type: "proxmox", name: "pve", baseUrl: "https://127.0.0.1:1", credentialId: await cred("pve", { tokenSecret: "s" }), config: JSON.stringify({ url: "https://127.0.0.1:1", tokenId: "u@pam!t", insecure: true }) }, + { type: "gitea", name: "git", baseUrl: "https://gitea.test", credentialId: await cred("git", { token: "t" }), config: JSON.stringify({ url: "https://gitea.test" }) }, + { type: "dockhand", name: "dock", baseUrl: "https://dockhand.test", credentialId: await cred("dock", { token: "t" }), config: JSON.stringify({ url: "https://dockhand.test" }) }, + ]); + await db.insert(dnsProviders).values([ + { providerType: "cloudflare", name: "cf", credentialId: await cred("cf", { apiToken: "t" }), config: JSON.stringify({}) }, + { providerType: "azure", name: "az", credentialId: await cred("az", { clientSecret: "s" }), config: JSON.stringify({ tenantId: "t", clientId: "c", subscriptionId: "sub" }) }, + ]); + serverId = (await db.insert(servers).values({ name: "s1", apiTokenHash: "h", apiTokenPrefix: "p" }).returning())[0].id; + + const app = express(); + app.use(express.json()); + app.use(session({ secret: "t", resave: false, saveUninitialized: true })); + app.post("/login/:sub", (req, res) => { + req.session.user = { sub: req.params.sub } as never; + res.json({}); + }); + app.use("/api/integrations", integrationsRouter); + app.use("/api/dns", dnsRouter); + app.use("/api/servers", serversRouter); + server = app.listen(0); + port = (server.address() as { port: number }).port; + + const login = async (sub: string) => (await realFetch(`http://127.0.0.1:${port}/login/${sub}`, { method: "POST" })).headers.get("set-cookie")!.split(";")[0]; + operator = await login("op"); + viewer = await login("vw"); + admin = await login("ad"); + }); + + after(() => { + server?.close(); + globalThis.fetch = realFetch; + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows keeps the SQLite file locked until the process exits; the folder is in the OS temp directory either way. + } + }); + + /** Sends the path exactly as written — no client-side tidying of dot segments, like `curl --path-as-is`. */ + function send(cookie: string, method: string, path: string, body?: object): Promise { + return new Promise((resolve, reject) => { + const payload = body ? JSON.stringify(body) : undefined; + const headers: Record = { cookie }; + if (payload) { + headers["content-type"] = "application/json"; + headers["content-length"] = String(Buffer.byteLength(payload)); + } + const req = http.request({ host: "127.0.0.1", port, method, path, headers }, (res) => { + let text = ""; + res.on("data", (c) => (text += c)); + res.on("end", () => { + lastBody.text = text; + resolve(res.statusCode ?? 0); + }); + }); + req.on("error", reject); + if (payload) req.write(payload); + req.end(); + }); + } + + const encoded = (id: string) => encodeURIComponent(id); // what a client puts in the URL; Express decodes it back to `id` + const record = { type: "A", name: "a.example.com", content: "1.2.3.4", ttl: 300 }; + + test("Tailscale: a crafted device ID is a 400 and nothing is sent", async () => { + for (const bad of ["x/../../tailnet/-/keys/k123", "x/../../tailnet/-/acl?", "..", "a?b"]) { + calls = []; + assert.equal(await send(operator, "DELETE", `/api/integrations/1/tailscale/devices/${encoded(bad)}`), 400, `DELETE ${bad}`); + assert.equal(await send(operator, "POST", `/api/integrations/1/tailscale/devices/${encoded(bad)}/authorize`, { authorized: true }), 400, `authorize ${bad}`); + calledNothing(); + } + }); + + test("Tailscale: a real device ID still works", async () => { + calls = []; + assert.equal(await send(operator, "DELETE", "/api/integrations/1/tailscale/devices/nabc123"), 204); + assert.deepEqual(calls, [{ method: "DELETE", url: "https://api.tailscale.com/api/v2/device/nabc123" }]); + calls = []; + assert.equal(await send(operator, "POST", "/api/integrations/1/tailscale/devices/nabc123/authorize", { authorized: true }), 204); + assert.deepEqual(calls, [{ method: "POST", url: "https://api.tailscale.com/api/v2/device/nabc123/authorized" }]); + }); + + test("Proxmox: a crafted node name is a 400 (it used to become 'stop every guest on the node')", async () => { + for (const action of ["start", "stop", "restart", "shutdown"]) { + for (const bad of ["pve/stopall?", "pve/../../access/users", "..", "a b"]) { + assert.equal(await send(operator, "POST", `/api/integrations/2/proxmox/nodes/${encoded(bad)}/qemu/100/${action}`), 400, `${action} ${bad}`); + assert.match(lastBody.text, /invalid_id/); + } + } + }); + + test("Proxmox: a real node name gets past the check (and fails only at the unreachable host)", async () => { + assert.equal(await send(operator, "POST", "/api/integrations/2/proxmox/nodes/pve-1/qemu/100/stop"), 502); + assert.doesNotMatch(lastBody.text, /invalid_id/); + }); + + test("Gitea: crafted owner or repository is a 400", async () => { + for (const bad of ["..", "x/../y", "a?b"]) { + calls = []; + assert.equal(await send(operator, "POST", `/api/integrations/3/gitea/repos/${encoded(bad)}/repo/runs/1/rerun-failed`), 400, `owner ${bad}`); + assert.equal(await send(operator, "POST", `/api/integrations/3/gitea/repos/owner/${encoded(bad)}/runs/1/rerun-failed`), 400, `repo ${bad}`); + calledNothing(); + } + calls = []; + assert.equal(await send(operator, "POST", "/api/integrations/3/gitea/repos/owner/my.repo/runs/1/rerun-failed"), 204); + assert.equal(calls.length, 1); + }); + + test("Dockhand: a crafted container ID is a 400", async () => { + for (const action of ["start", "stop", "restart"]) { + for (const bad of ["..", "x/../y", "a?b"]) { + calls = []; + assert.equal(await send(operator, "POST", `/api/integrations/4/dockhand/environments/1/containers/${encoded(bad)}/${action}`), 400, `${action} ${bad}`); + calledNothing(); + } + } + calls = []; + assert.equal(await send(operator, "POST", "/api/integrations/4/dockhand/environments/1/containers/abc123/stop"), 204); + }); + + test("Cloudflare DNS: crafted zone or record IDs are a 400 (a record ID of '../..' used to delete the whole zone)", async () => { + for (const bad of ["x/../..", "x/../../../user/tokens", "..", "a?b", "short"]) { + calls = []; + assert.equal(await send(operator, "DELETE", `/api/dns/providers/1/zones/${ZONE}/records/${encoded(bad)}`), 400, `delete record ${bad}`); + assert.equal(await send(operator, "PUT", `/api/dns/providers/1/zones/${ZONE}/records/${encoded(bad)}`, record), 400, `update record ${bad}`); + assert.equal(await send(operator, "POST", `/api/dns/providers/1/zones/${encoded(bad)}/records`, record), 400, `add record ${bad}`); + assert.equal(await send(operator, "POST", `/api/dns/providers/1/zones/${encoded(bad)}/sync`, {}), 400, `sync ${bad}`); + calledNothing(); + } + }); + + test("Cloudflare DNS: real IDs still work", async () => { + calls = []; + assert.equal(await send(operator, "DELETE", `/api/dns/providers/1/zones/${ZONE}/records/${RECORD}`), 204); + assert.deepEqual(calls, [{ method: "DELETE", url: `https://api.cloudflare.com/client/v4/zones/${ZONE}/dns_records/${RECORD}` }]); + }); + + test("Azure DNS: crafted IDs are a 400, nothing reaches Azure's management API", async () => { + for (const bad of ["x/../..", "..", "a?b"]) { + calls = []; + assert.equal(await send(operator, "DELETE", `/api/dns/providers/2/zones/${encoded("rg::example.com")}/records/${encoded(`${bad}::A::1.2.3.4`)}`), 400, `record ${bad}`); + assert.equal(await send(operator, "DELETE", `/api/dns/providers/2/zones/${encoded(`rg::${bad}`)}/records/${encoded("www::A::1.2.3.4")}`), 400, `zone ${bad}`); + assert.equal(await send(operator, "POST", `/api/dns/providers/2/zones/${encoded("rg::example.com")}/records`, { ...record, name: bad }), 400, `new name ${bad}`); + assert.equal(calls.filter((c) => c.url.startsWith("https://management.azure.com")).length, 0); + } + }); + + test("a server's Proxmox node can't be set to a crafted value either", async () => { + const base = { proxmoxIntegrationId: 2, proxmoxGuestType: "qemu", proxmoxVmid: 100 }; + assert.equal(await send(admin, "PATCH", `/api/servers/${serverId}`, { ...base, proxmoxNode: "pve/../../access" }), 400); + assert.equal(await send(admin, "PATCH", `/api/servers/${serverId}`, { ...base, proxmoxNode: "pve-1" }), 200); + }); + + test("role checks still hold: a viewer is refused on every one of these", async () => { + calls = []; + assert.equal(await send(viewer, "DELETE", "/api/integrations/1/tailscale/devices/nabc123"), 403); + assert.equal(await send(viewer, "POST", "/api/integrations/2/proxmox/nodes/pve/qemu/100/stop"), 403); + assert.equal(await send(viewer, "POST", "/api/integrations/3/gitea/repos/o/r/runs/1/rerun-failed"), 403); + assert.equal(await send(viewer, "POST", "/api/integrations/4/dockhand/environments/1/containers/abc/stop"), 403); + assert.equal(await send(viewer, "DELETE", `/api/dns/providers/1/zones/${ZONE}/records/${RECORD}`), 403); + calledNothing(); + }); +});