Files
Homelab-manager/server/test/pathInjection.test.ts
T
bobbanandClaude Sonnet 5.5 a641211484 Stop IDs in a request from being turned into other calls to connected systems
The Tailscale device, Proxmox node, Cloudflare zone/record and Azure record/zone IDs
were put into the outgoing request path as typed. An operator could send a crafted ID
("x/../../tailnet/-/keys/k1") and make the app call a different endpoint than the button
meant -- delete an auth key instead of a device, stop every guest on a node, delete a whole
DNS zone -- under the integration's own credential. Gitea and Dockhand encoded their IDs but
still passed "..".

- utils/pathSegment.ts: checks an ID against what a real one looks like, then encodes it
  (encodeURIComponent alone leaves ".." untouched). Used by the Tailscale, Proxmox,
  Cloudflare, Azure, Gitea and Dockhand adapters.
- The routes refuse a bad ID with a 400 before anything is sent, and the DNS routes turn the
  adapters' refusal into a 400. A server's Proxmox node name is validated when saved.
- Azure: a zone ID without "::" is now refused instead of being cut into two bogus pieces.
- Regression tests (npm test --workspace server, Node's built-in runner): the crafted IDs
  are refused for every adapter and route, real IDs still work, viewers are still refused.
  Against the old code 13 of the 22 tests fail.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-06 21:02:22 +02:00

407 lines
23 KiB
TypeScript

/**
* 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<number> {
return new Promise((resolve, reject) => {
const payload = body ? JSON.stringify(body) : undefined;
const headers: Record<string, string> = { 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();
});
});