Manage Nginx Proxy Manager proxy hosts from the Proxy hosts page
With an optional second user on the NPM integration (Manage on Proxy Hosts, no two-factor sign-in) an administrator can make, change, switch off and delete proxy hosts: names, where it forwards to, an existing certificate and what is switched on. Only what differs is sent, a host's access list, locations and custom configuration are never touched, and combinations NPM would quietly undo (Force HTTPS, HTTP/2 or HSTS without a certificate) are refused with the reason. Delete asks for the host's first name, checked against the host as NPM has it. The user that reads is still view-only and never writes. Audited; the managing user can be taken away again. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
672c7f2f66
commit
4dd7901f1c
13 files changed
+1286
-14
No files matched your search
@@ -0,0 +1,531 @@
|
||||
/**
|
||||
* Managing the proxy hosts of Nginx Proxy Manager: what a host's settings may be and what a change comes to, what is sent (only what differs), that the user that reads is never used to write, who
|
||||
* may, what is refused before NPM is asked, what NPM says when it refuses, 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-npm-manage-"));
|
||||
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, integrations, integrationCredentials, auditLog } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const { encryptSecret } = await import("../src/crypto.js");
|
||||
const { INTEGRATION_FIELDS } = await import("../src/integrations/fieldSchemas.js");
|
||||
const { hostFrom } = await import("../src/integrations/npm/adapter.js");
|
||||
const plan = await import("../src/integrations/npm/hostPlan.js");
|
||||
const { createNpmManageAdapter } = await import("../src/integrations/npm/manage.js");
|
||||
const { loadIntegrationConfig } = await import("../src/integrations/loadIntegration.js");
|
||||
const { clearNpmCacheForTests } = await import("../src/services/npmReader.js");
|
||||
const { npmRouter } = await import("../src/routes/npm.js");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
const settings = (over: Partial<import("../src/integrations/npm/hostPlan.js").HostSettings> = {}): import("../src/integrations/npm/hostPlan.js").HostSettings => ({
|
||||
domains: ["app.example.com"],
|
||||
scheme: "http",
|
||||
host: "10.0.0.5",
|
||||
port: 8080,
|
||||
certificateId: null,
|
||||
sslForced: false,
|
||||
http2: false,
|
||||
hsts: false,
|
||||
hstsSubdomains: false,
|
||||
blockExploits: true,
|
||||
caching: false,
|
||||
websocket: false,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("what a proxy host may be", () => {
|
||||
test("a name is written lower case, without a space round it; NPM's own idea of what is not a name is refused", () => {
|
||||
assert.equal(plan.normaliseDomain(" App.Example.COM "), "app.example.com");
|
||||
assert.equal(plan.normaliseDomain("*.example.com"), "*.example.com");
|
||||
for (const bad of ["", " ", "a b.com", "a/b.com", "a@b.com", "a:80", "a,b.com", "a;b", "a?b", "a&b", "a|b", "a'b", 'a"b', "a`b", "x".repeat(254)]) assert.equal(plan.normaliseDomain(bad), null, JSON.stringify(bad));
|
||||
});
|
||||
|
||||
test("the whole is checked: names, where it forwards, and the combinations NPM would quietly undo", () => {
|
||||
assert.equal(plan.checkHost(settings()), null);
|
||||
assert.match(plan.checkHost(settings({ domains: [] })) ?? "", /at least one name/);
|
||||
assert.match(plan.checkHost(settings({ domains: ["a.com", "a.com"] })) ?? "", /twice/);
|
||||
assert.match(plan.checkHost(settings({ domains: ["A.com"] })) ?? "", /not a name NPM takes/);
|
||||
assert.match(plan.checkHost(settings({ host: "a b" })) ?? "", /without spaces/);
|
||||
assert.match(plan.checkHost(settings({ port: 0 })) ?? "", /1 to 65535/);
|
||||
assert.match(plan.checkHost(settings({ port: 70000 })) ?? "", /1 to 65535/);
|
||||
assert.match(plan.checkHost(settings({ sslForced: true })) ?? "", /need a certificate/);
|
||||
assert.match(plan.checkHost(settings({ http2: true })) ?? "", /need a certificate/);
|
||||
assert.match(plan.checkHost(settings({ certificateId: 3, hsts: true })) ?? "", /HSTS needs Force HTTPS/);
|
||||
assert.match(plan.checkHost(settings({ certificateId: 3, sslForced: true, hstsSubdomains: true })) ?? "", /subdomains needs HSTS/);
|
||||
assert.equal(plan.checkHost(settings({ certificateId: 3, sslForced: true, http2: true, hsts: true, hstsSubdomains: true })), null);
|
||||
});
|
||||
|
||||
test("a host is made with NPM's own names for everything, and a certificate of none is 0", () => {
|
||||
assert.deepEqual(plan.createBody(settings({ certificateId: 3, sslForced: true, websocket: true })), {
|
||||
domain_names: ["app.example.com"],
|
||||
forward_scheme: "http",
|
||||
forward_host: "10.0.0.5",
|
||||
forward_port: 8080,
|
||||
certificate_id: 3,
|
||||
ssl_forced: true,
|
||||
http2_support: false,
|
||||
hsts_enabled: false,
|
||||
hsts_subdomains: false,
|
||||
block_exploits: true,
|
||||
caching_enabled: false,
|
||||
allow_websocket_upgrade: true,
|
||||
});
|
||||
assert.equal(plan.createBody(settings()).certificate_id, 0);
|
||||
});
|
||||
|
||||
test("a change is only what differs, after the whole is checked; nothing different is nothing to send", () => {
|
||||
const cur = settings({ certificateId: 3, sslForced: true });
|
||||
const p = plan.planHostEdit(cur, { port: 9090, websocket: true, sslForced: true });
|
||||
assert.deepEqual(p, { send: { forward_port: 9090, allow_websocket_upgrade: true }, changed: ["port", "websocket"] });
|
||||
assert.deepEqual(plan.planHostEdit(cur, { port: 8080, domains: ["app.example.com"] }), { send: {}, changed: [] });
|
||||
const names = plan.planHostEdit(cur, { domains: ["a.example.com", "b.example.com"] });
|
||||
assert.deepEqual(names, { send: { domain_names: ["a.example.com", "b.example.com"] }, changed: ["domains"] });
|
||||
});
|
||||
|
||||
test("taking the certificate away is only fine if what needs one goes with it; it is sent as 0", () => {
|
||||
const cur = settings({ certificateId: 3, sslForced: true, http2: true });
|
||||
assert.match((plan.planHostEdit(cur, { certificateId: null }) as { error: string }).error, /need a certificate/);
|
||||
const p = plan.planHostEdit(cur, { certificateId: null, sslForced: false, http2: false });
|
||||
assert.deepEqual(p, { send: { certificate_id: 0, ssl_forced: false, http2_support: false }, changed: ["certificateId", "sslForced", "http2"] });
|
||||
});
|
||||
|
||||
test("an edit that would leave something inconsistent is refused with the reason", () => {
|
||||
assert.match((plan.planHostEdit(settings(), { sslForced: true }) as { error: string }).error, /need a certificate/);
|
||||
assert.match((plan.planHostEdit(settings({ certificateId: 3, sslForced: true, hsts: true }), { sslForced: false }) as { error: string }).error, /HSTS needs Force HTTPS/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("what NPM says of a host", () => {
|
||||
test("the settings are read, and the certificate id is the host's even when NPM did not say which certificate it is", () => {
|
||||
const h = hostFrom({ id: 4, domain_names: ["a.com"], forward_scheme: "https", forward_host: "h", forward_port: "443", enabled: 1, ssl_forced: 1, http2_support: true, hsts_enabled: 0, hsts_subdomains: false, block_exploits: true, caching_enabled: 1, allow_websocket_upgrade: false, certificate_id: 7, certificate: null, meta: {} })!;
|
||||
assert.deepEqual([h.forwardPort, h.sslForced, h.http2, h.hsts, h.blockExploits, h.caching, h.websocket, h.certificateId, h.certificate], [443, true, true, false, true, true, false, 7, null]);
|
||||
assert.equal(hostFrom({ id: 5, domain_names: ["b.com"], certificate_id: 0 })!.certificateId, null);
|
||||
});
|
||||
|
||||
test("the user for managing is an optional pair of fields of the integration, the password a secret", () => {
|
||||
const fields = INTEGRATION_FIELDS.npm!;
|
||||
assert.deepEqual([fields.find((f) => f.key === "manageEmail")?.optional, fields.find((f) => f.key === "managePassword")?.secret, fields.find((f) => f.key === "managePassword")?.optional], [true, true, true]);
|
||||
});
|
||||
});
|
||||
|
||||
/** An NPM that keeps its hosts, tells the user that may only view from the one that may manage, and does what NPM does quietly with SSL settings. */
|
||||
interface FakeHost {
|
||||
id: number;
|
||||
domain_names: string[];
|
||||
forward_scheme: string;
|
||||
forward_host: string;
|
||||
forward_port: number;
|
||||
enabled: boolean;
|
||||
ssl_forced: boolean;
|
||||
http2_support: boolean;
|
||||
hsts_enabled: boolean;
|
||||
hsts_subdomains: boolean;
|
||||
block_exploits: boolean;
|
||||
caching_enabled: boolean;
|
||||
allow_websocket_upgrade: boolean;
|
||||
certificate_id: number;
|
||||
advanced_config: string;
|
||||
}
|
||||
const fresh = (): FakeHost[] => [
|
||||
{ id: 1, domain_names: ["app.example.com"], forward_scheme: "http", forward_host: "10.0.0.5", forward_port: 8080, enabled: true, ssl_forced: true, http2_support: true, hsts_enabled: false, hsts_subdomains: false, block_exploits: true, caching_enabled: false, allow_websocket_upgrade: false, certificate_id: 1, advanced_config: "proxy_set_header X-Test 1;" },
|
||||
{ id: 2, domain_names: ["old.example.com", "legacy.example.com"], forward_scheme: "http", forward_host: "10.0.0.6", forward_port: 80, enabled: false, ssl_forced: false, http2_support: false, hsts_enabled: false, hsts_subdomains: false, block_exploits: false, caching_enabled: false, allow_websocket_upgrade: false, certificate_id: 0, advanced_config: "" },
|
||||
];
|
||||
let hosts = fresh();
|
||||
let nextId = 10;
|
||||
interface Seen {
|
||||
method: string;
|
||||
path: string;
|
||||
as: string;
|
||||
body: string;
|
||||
}
|
||||
const seen: Seen[] = [];
|
||||
|
||||
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 bearer = String(req.headers.authorization ?? "").replace(/^Bearer /, "");
|
||||
const as = bearer === "view-token" ? "view" : bearer === "manage-token" ? "manage" : bearer === "" ? "nobody" : "unknown";
|
||||
seen.push({ method: req.method ?? "", path: u.pathname + u.search, as, body });
|
||||
const send = (status: number, json: unknown) => {
|
||||
res.writeHead(status, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify(json));
|
||||
};
|
||||
const fail = (status: number, message: string) => send(status, { error: { code: status, message } });
|
||||
const parsed = body ? (JSON.parse(body) as Record<string, unknown>) : {};
|
||||
if (u.pathname === "/api/tokens") {
|
||||
if (parsed.identity === "manage@x" && parsed.secret === "manage-pass") return send(200, { token: "manage-token", expires: "2030-01-01T00:00:00Z" });
|
||||
if (parsed.identity === "view@x" && parsed.secret === "view-pass") return send(200, { token: "view-token", expires: "2030-01-01T00:00:00Z" });
|
||||
if (parsed.identity === "tfa@x") return send(200, { requires_2fa: true, challenge_token: "c" });
|
||||
return fail(400, "Invalid email or password");
|
||||
}
|
||||
if (as === "nobody" || as === "unknown") return fail(401, "Unauthorised");
|
||||
const out = (h: FakeHost) => ({ ...h, certificate: h.certificate_id > 0 ? { id: h.certificate_id, nice_name: "example cert", domain_names: ["example.com"], provider: "letsencrypt", expires_on: "2031-01-01 00:00:00" } : null, meta: { nginx_online: true } });
|
||||
if (u.pathname === "/api/") return send(200, { status: "OK", version: { major: 2, minor: 11, revision: 3 } });
|
||||
if (u.pathname === "/api/nginx/certificates") return send(200, []);
|
||||
if (u.pathname === "/api/nginx/proxy-hosts" && req.method === "GET") return send(200, hosts.map(out));
|
||||
const writing = req.method !== "GET";
|
||||
if (writing && as !== "manage") return fail(403, "Permission Denied");
|
||||
const apply = (h: FakeHost, data: Record<string, unknown>) => {
|
||||
Object.assign(h, data);
|
||||
// What NPM does without saying so.
|
||||
if (!h.certificate_id) {
|
||||
h.ssl_forced = false;
|
||||
h.http2_support = false;
|
||||
}
|
||||
if (!h.ssl_forced) h.hsts_enabled = false;
|
||||
if (!h.hsts_enabled) h.hsts_subdomains = false;
|
||||
};
|
||||
const taken = (names: unknown, except?: number) => (Array.isArray(names) ? (names as string[]).find((n) => hosts.some((h) => h.id !== except && h.domain_names.includes(n))) : undefined);
|
||||
if (u.pathname === "/api/nginx/proxy-hosts" && req.method === "POST") {
|
||||
const t = taken(parsed.domain_names);
|
||||
if (t) return fail(400, `${t} is already in use`);
|
||||
const h: FakeHost = { id: nextId++, domain_names: [], forward_scheme: "http", forward_host: "", forward_port: 80, enabled: true, ssl_forced: false, http2_support: false, hsts_enabled: false, hsts_subdomains: false, block_exploits: false, caching_enabled: false, allow_websocket_upgrade: false, certificate_id: 0, advanced_config: "" };
|
||||
apply(h, parsed);
|
||||
hosts.push(h);
|
||||
return send(201, out(h));
|
||||
}
|
||||
const one = /^\/api\/nginx\/proxy-hosts\/(\d+)(\/enable|\/disable)?$/.exec(u.pathname);
|
||||
if (one) {
|
||||
const h = hosts.find((x) => x.id === Number(one[1]));
|
||||
if (!h) return fail(404, `Not Found - ${one[1]}`);
|
||||
if (req.method === "GET") return send(200, out(h));
|
||||
if (req.method === "PUT") {
|
||||
const t = taken(parsed.domain_names, h.id);
|
||||
if (t) return fail(400, `${t} is already in use`);
|
||||
apply(h, parsed);
|
||||
return send(200, out(h));
|
||||
}
|
||||
if (req.method === "POST" && one[2]) {
|
||||
const on = one[2] === "/enable";
|
||||
if (h.enabled === on) return fail(400, `Host is already ${on ? "enabled" : "disabled"}`);
|
||||
h.enabled = on;
|
||||
return send(200, true);
|
||||
}
|
||||
if (req.method === "DELETE") {
|
||||
hosts = hosts.filter((x) => x.id !== h.id);
|
||||
return send(200, true);
|
||||
}
|
||||
}
|
||||
return fail(404, "Not Found");
|
||||
});
|
||||
});
|
||||
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 = () => {
|
||||
hosts = fresh();
|
||||
nextId = 10;
|
||||
seen.length = 0;
|
||||
clearNpmCacheForTests();
|
||||
};
|
||||
const writes = () => seen.filter((s) => s.method !== "GET" && s.path !== "/api/tokens");
|
||||
|
||||
describe("what is sent to NPM", () => {
|
||||
const adapter = (over: Record<string, unknown> = {}) => createNpmManageAdapter({ url: `${fakeUrl}/`, manageEmail: "manage@x", managePassword: "manage-pass", ...over } as never);
|
||||
|
||||
test("every call signs in first, as the user for managing, and nothing else", async () => {
|
||||
reset();
|
||||
await adapter().getHost(1);
|
||||
assert.deepEqual(seen.map((s) => [s.method, s.path, s.as]), [["POST", "/api/tokens", "nobody"], ["GET", "/api/nginx/proxy-hosts/1?expand=certificate", "manage"]]);
|
||||
assert.deepEqual(JSON.parse(seen[0].body), { identity: "manage@x", secret: "manage-pass" });
|
||||
});
|
||||
|
||||
test("a host is made, changed (only what is in the body), switched and deleted with the calls NPM's own page makes", async () => {
|
||||
reset();
|
||||
const made = await adapter().createHost(settings({ domains: ["new.example.com"], certificateId: 1, sslForced: true }));
|
||||
assert.deepEqual([made.id, made.domains, made.sslForced, made.certificateId], [10, ["new.example.com"], true, 1]);
|
||||
assert.deepEqual(writes().map((s) => [s.method, s.path]), [["POST", "/api/nginx/proxy-hosts"]]);
|
||||
const changed = await adapter().updateHost(10, { forward_port: 9000 });
|
||||
assert.equal(changed.forwardPort, 9000);
|
||||
assert.equal(seen.at(-1)!.method + " " + seen.at(-1)!.path, "PUT /api/nginx/proxy-hosts/10");
|
||||
assert.equal(seen.at(-1)!.body, JSON.stringify({ forward_port: 9000 }));
|
||||
await adapter().setEnabled(10, false);
|
||||
assert.equal(seen.at(-1)!.path, "/api/nginx/proxy-hosts/10/disable");
|
||||
await adapter().setEnabled(10, true);
|
||||
assert.equal(seen.at(-1)!.path, "/api/nginx/proxy-hosts/10/enable");
|
||||
await adapter().deleteHost(10);
|
||||
assert.equal(seen.at(-1)!.method + " " + seen.at(-1)!.path, "DELETE /api/nginx/proxy-hosts/10");
|
||||
assert.equal(hosts.some((h) => h.id === 10), false);
|
||||
});
|
||||
|
||||
test("what NPM says when it refuses is the error, said in kind; a user that may only view cannot write; two-factor and a wrong password are said", async () => {
|
||||
reset();
|
||||
await assert.rejects(
|
||||
() => adapter().createHost(settings({ domains: ["app.example.com"] })),
|
||||
(err: Error & { kind?: string }) => err.kind === "invalid" && /app\.example\.com is already in use/.test(err.message),
|
||||
);
|
||||
await assert.rejects(
|
||||
() => adapter().getHost(99),
|
||||
(err: Error & { kind?: string }) => err.kind === "missing" && /Not Found - 99/.test(err.message),
|
||||
);
|
||||
await assert.rejects(
|
||||
() => adapter({ manageEmail: "view@x", managePassword: "view-pass" }).updateHost(1, { forward_port: 81 }),
|
||||
(err: Error & { kind?: string }) => err.kind === "denied" && /Manage on Proxy Hosts/.test(err.message),
|
||||
);
|
||||
await assert.rejects(() => adapter({ manageEmail: "tfa@x" }).getHost(1), /two-factor/);
|
||||
await assert.rejects(
|
||||
() => adapter({ managePassword: "nope" }).getHost(1),
|
||||
(err: Error & { kind?: string }) => err.kind === "denied" && /did not accept the email and password/.test(err.message),
|
||||
);
|
||||
await assert.rejects(() => createNpmManageAdapter({ url: "http://127.0.0.1:1", manageEmail: "a", managePassword: "b" }).getHost(1), /could not be reached/);
|
||||
});
|
||||
|
||||
test("an id that is not a whole number is never put in an address", async () => {
|
||||
reset();
|
||||
for (const bad of [0, -1, 1.5, Number.NaN]) {
|
||||
await assert.rejects(() => adapter().getHost(bad), /not a proxy host id/);
|
||||
await assert.rejects(() => adapter().deleteHost(bad), /not a proxy host id/);
|
||||
}
|
||||
assert.deepEqual(seen, []);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the routes", () => {
|
||||
let app: Server;
|
||||
let base = "";
|
||||
let managed = 0;
|
||||
let readOnly = 0;
|
||||
let off = 0;
|
||||
let other = 0;
|
||||
|
||||
const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub });
|
||||
const create = (id: number, body: unknown, sub = "admin") => fetch(`${base}/${id}/hosts`, { method: "POST", headers: as(sub), body: JSON.stringify(body) });
|
||||
const edit = (id: number, hostId: number | string, body: unknown, sub = "admin") => fetch(`${base}/${id}/hosts/${hostId}`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) });
|
||||
const enable = (id: number, hostId: number, enabled: unknown, sub = "admin") => fetch(`${base}/${id}/hosts/${hostId}/enabled`, { method: "POST", headers: as(sub), body: JSON.stringify({ enabled }) });
|
||||
const remove = (id: number, hostId: number, domain: unknown, sub = "admin") => fetch(`${base}/${id}/hosts/${hostId}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ domain }) });
|
||||
const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action);
|
||||
const newHost = { domains: ["Fresh.Example.com ", "fresh.example.com"], scheme: "http", host: "10.0.0.9", port: 3000, certificateId: null, sslForced: false, http2: false, hsts: false, hstsSubdomains: false, blockExploits: true, caching: false, websocket: true };
|
||||
|
||||
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 both = (await db.insert(integrationCredentials).values({ name: "npm:Front", encryptedSecret: encryptSecret(JSON.stringify({ password: "view-pass", managePassword: "manage-pass" })) }).returning({ id: integrationCredentials.id }))[0];
|
||||
const viewOnly = (await db.insert(integrationCredentials).values({ name: "npm:Watched", encryptedSecret: encryptSecret(JSON.stringify({ password: "view-pass" })) }).returning({ id: integrationCredentials.id }))[0];
|
||||
managed = (await db.insert(integrations).values({ type: "npm", name: "Front", baseUrl: fakeUrl, config: JSON.stringify({ url: fakeUrl, email: "view@x", manageEmail: "manage@x" }), credentialId: both.id }).returning({ id: integrations.id }))[0].id;
|
||||
readOnly = (await db.insert(integrations).values({ type: "npm", name: "Watched", baseUrl: fakeUrl, config: JSON.stringify({ url: fakeUrl, email: "view@x" }), credentialId: viewOnly.id }).returning({ id: integrations.id }))[0].id;
|
||||
off = (await db.insert(integrations).values({ type: "npm", name: "Off", baseUrl: fakeUrl, config: JSON.stringify({ url: fakeUrl, email: "view@x", manageEmail: "manage@x" }), credentialId: both.id, enabled: false }).returning({ id: integrations.id }))[0].id;
|
||||
other = (await db.insert(integrations).values({ type: "jellyfin", name: "Media", baseUrl: fakeUrl, config: "{}", credentialId: both.id }).returning({ id: integrations.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/npm", npmRouter);
|
||||
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/npm`;
|
||||
});
|
||||
after(() => {
|
||||
app.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits.
|
||||
}
|
||||
});
|
||||
|
||||
test("the page says which NPM has a user to manage with — a yes or no, never who or the password — and reading never uses that user", async () => {
|
||||
reset();
|
||||
const res = await fetch(base, { headers: as("viewer") });
|
||||
const text = await res.text();
|
||||
assert.equal(/manage@x|manage-pass|view-pass/.test(text), false);
|
||||
const body = JSON.parse(text) as { integrations: { id: number; canManage: boolean; hosts: unknown[] }[] };
|
||||
const can = Object.fromEntries(body.integrations.map((i) => [i.id, i.canManage]));
|
||||
assert.deepEqual([can[managed], can[readOnly]], [true, false]);
|
||||
assert.equal(seen.some((s) => s.as === "manage"), false, "the reading was done as the user that views");
|
||||
});
|
||||
|
||||
test("only an administrator makes, changes, switches or deletes a host; nothing reaches NPM for anyone else", async () => {
|
||||
reset();
|
||||
for (const sub of ["viewer", "operator"]) {
|
||||
assert.equal((await create(managed, newHost, sub)).status, 403, sub);
|
||||
assert.equal((await edit(managed, 1, { port: 81 }, sub)).status, 403, sub);
|
||||
assert.equal((await enable(managed, 1, false, sub)).status, 403, sub);
|
||||
assert.equal((await remove(managed, 1, "app.example.com", sub)).status, 403, sub);
|
||||
}
|
||||
assert.deepEqual(seen, []);
|
||||
});
|
||||
|
||||
test("a host is made with its names written for NPM and listed once, and the page then shows it; the audit log says who made what", async () => {
|
||||
reset();
|
||||
const res = await create(managed, newHost);
|
||||
assert.equal(res.status, 201);
|
||||
const { host } = (await res.json()) as { host: { id: number; domains: string[] } };
|
||||
assert.deepEqual(host.domains, ["fresh.example.com"]);
|
||||
assert.deepEqual(writes().map((s) => [s.method, s.path, s.as]), [["POST", "/api/nginx/proxy-hosts", "manage"]]);
|
||||
assert.deepEqual(JSON.parse(writes()[0].body), {
|
||||
domain_names: ["fresh.example.com"],
|
||||
forward_scheme: "http",
|
||||
forward_host: "10.0.0.9",
|
||||
forward_port: 3000,
|
||||
certificate_id: 0,
|
||||
ssl_forced: false,
|
||||
http2_support: false,
|
||||
hsts_enabled: false,
|
||||
hsts_subdomains: false,
|
||||
block_exploits: true,
|
||||
caching_enabled: false,
|
||||
allow_websocket_upgrade: true,
|
||||
});
|
||||
const page = (await (await fetch(base, { headers: as("viewer") })).json()) as { integrations: { id: number; hosts: { domains: string[] }[] }[] };
|
||||
assert.equal(page.integrations.find((i) => i.id === managed)!.hosts.some((h) => h.domains[0] === "fresh.example.com"), true, "the cache was refreshed");
|
||||
const [entry] = await audit("create_proxy_host");
|
||||
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "proxy_host", String(host.id)]);
|
||||
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: managed, integration: "Front", domains: ["fresh.example.com"], forwardsTo: "http://10.0.0.9:3000" });
|
||||
});
|
||||
|
||||
test("what is wrong with a host is said before NPM is asked", async () => {
|
||||
reset();
|
||||
const bad: unknown[] = [
|
||||
{},
|
||||
{ ...newHost, domains: [] },
|
||||
{ ...newHost, domains: ["a b.example.com"] },
|
||||
{ ...newHost, domains: ["a/b.example.com"] },
|
||||
{ ...newHost, host: "" },
|
||||
{ ...newHost, host: "a b" },
|
||||
{ ...newHost, port: 0 },
|
||||
{ ...newHost, port: 70000 },
|
||||
{ ...newHost, scheme: "ftp" },
|
||||
{ ...newHost, sslForced: true },
|
||||
{ ...newHost, certificateId: 1, hsts: true },
|
||||
{ ...newHost, certificateId: 1, sslForced: true, hstsSubdomains: true },
|
||||
{ ...newHost, certificateId: 0 },
|
||||
];
|
||||
for (const body of bad) {
|
||||
const res = await create(managed, body);
|
||||
assert.equal(res.status, 400, JSON.stringify(body));
|
||||
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
|
||||
}
|
||||
assert.deepEqual(seen, []);
|
||||
});
|
||||
|
||||
test("a name another host has is NPM's own words, and nothing is written in the audit log", async () => {
|
||||
reset();
|
||||
const before = (await audit("create_proxy_host")).length;
|
||||
const res = await create(managed, { ...newHost, domains: ["app.example.com"] });
|
||||
assert.equal(res.status, 400);
|
||||
assert.match(((await res.json()) as { message: string }).message, /app\.example\.com is already in use/);
|
||||
assert.equal((await audit("create_proxy_host")).length, before);
|
||||
});
|
||||
|
||||
test("an edit sends only what differs, and what NPM keeps of the host that was not asked (its custom configuration) is not in it", async () => {
|
||||
reset();
|
||||
const res = await edit(managed, 1, { port: 9090, websocket: true, domains: ["App.Example.com"], sslForced: true });
|
||||
assert.equal(res.status, 200);
|
||||
const body = (await res.json()) as { changed: string[]; host: { forwardPort: number; websocket: boolean } };
|
||||
assert.deepEqual([body.changed, body.host.forwardPort, body.host.websocket], [["port", "websocket"], 9090, true]);
|
||||
assert.deepEqual(writes().map((s) => [s.method, s.path, JSON.parse(s.body)]), [["PUT", "/api/nginx/proxy-hosts/1", { forward_port: 9090, allow_websocket_upgrade: true }]]);
|
||||
assert.equal(hosts.find((h) => h.id === 1)!.advanced_config, "proxy_set_header X-Test 1;");
|
||||
const [entry] = await audit("update_proxy_host");
|
||||
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: managed, integration: "Front", domains: ["app.example.com"], changed: ["port", "websocket"] });
|
||||
});
|
||||
|
||||
test("an edit that changes nothing sends nothing and writes nothing", async () => {
|
||||
reset();
|
||||
const before = (await audit("update_proxy_host")).length;
|
||||
const res = await edit(managed, 1, { port: 8080, scheme: "http", blockExploits: true });
|
||||
assert.deepEqual(((await res.json()) as { changed: string[] }).changed, []);
|
||||
assert.deepEqual(writes(), []);
|
||||
assert.equal((await audit("update_proxy_host")).length, before);
|
||||
});
|
||||
|
||||
test("an edit that NPM would quietly undo is refused with the reason; so is an unknown field, an empty edit, a host that is not there and an id that is no id", async () => {
|
||||
reset();
|
||||
assert.match(((await (await edit(managed, 2, { sslForced: true })).json()) as { message: string }).message, /need a certificate/);
|
||||
assert.match(((await (await edit(managed, 1, { certificateId: null })).json()) as { message: string }).message, /need a certificate/);
|
||||
assert.equal((await edit(managed, 1, { advancedConfig: "x" })).status, 400);
|
||||
assert.equal((await edit(managed, 1, { port: "x" })).status, 400);
|
||||
assert.equal((await edit(managed, 99, { port: 81 })).status, 404);
|
||||
assert.equal((await edit(managed, "abc", { port: 81 })).status, 400);
|
||||
assert.deepEqual(writes(), []);
|
||||
// Taking the certificate away with what needs it is fine, and the host ends as asked.
|
||||
const ok = await edit(managed, 1, { certificateId: null, sslForced: false, http2: false });
|
||||
assert.equal(ok.status, 200);
|
||||
assert.deepEqual([hosts.find((h) => h.id === 1)!.certificate_id, hosts.find((h) => h.id === 1)!.ssl_forced], [0, false]);
|
||||
});
|
||||
|
||||
test("a host is switched off and on; what is already so asks nothing", async () => {
|
||||
reset();
|
||||
assert.deepEqual(await (await enable(managed, 1, false)).json(), { enabled: false, changed: true });
|
||||
assert.equal(hosts.find((h) => h.id === 1)!.enabled, false);
|
||||
assert.deepEqual(writes().map((s) => s.path), ["/api/nginx/proxy-hosts/1/disable"]);
|
||||
assert.deepEqual(await (await enable(managed, 1, false)).json(), { enabled: false, changed: false });
|
||||
assert.equal(writes().length, 1);
|
||||
assert.deepEqual(await (await enable(managed, 2, true)).json(), { enabled: true, changed: true });
|
||||
assert.equal((await enable(managed, 1, "yes")).status, 400);
|
||||
assert.equal((await audit("disable_proxy_host")).length, 1);
|
||||
assert.equal((await audit("enable_proxy_host")).length, 1);
|
||||
});
|
||||
|
||||
test("a host is deleted with its first name typed, checked against the host as NPM has it now; a wrong name deletes nothing", async () => {
|
||||
reset();
|
||||
assert.equal((await remove(managed, 2, undefined)).status, 400);
|
||||
const wrong = await remove(managed, 2, "app.example.com");
|
||||
assert.equal(wrong.status, 400);
|
||||
assert.equal(((await wrong.json()) as { error: string }).error, "name_mismatch");
|
||||
assert.equal((await remove(managed, 2, "legacy.example.com")).status, 400, "the first name, not any");
|
||||
assert.equal(hosts.length, 2);
|
||||
assert.deepEqual(writes(), []);
|
||||
assert.equal((await remove(managed, 2, " Old.Example.com ")).status, 204);
|
||||
assert.deepEqual(hosts.map((h) => h.id), [1]);
|
||||
const [entry] = await audit("delete_proxy_host");
|
||||
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: managed, integration: "Front", domains: ["old.example.com", "legacy.example.com"], forwardsTo: "http://10.0.0.6:80" });
|
||||
assert.equal((await remove(managed, 99, "x")).status, 404);
|
||||
});
|
||||
|
||||
test("an NPM with no user to manage with, a switched-off one, another kind of integration and an unknown one are not written to", async () => {
|
||||
reset();
|
||||
const none = await create(readOnly, newHost);
|
||||
assert.equal(none.status, 400);
|
||||
assert.equal(((await none.json()) as { error: string }).error, "no_manage_login");
|
||||
assert.equal(((await (await create(off, newHost)).json()) as { error: string }).error, "integration_disabled");
|
||||
assert.equal(((await (await create(other, newHost)).json()) as { error: string }).error, "wrong_type");
|
||||
assert.equal((await create(999999, newHost)).status, 404);
|
||||
assert.equal((await fetch(`${base}/abc/hosts`, { method: "POST", headers: as("admin"), body: JSON.stringify(newHost) })).status, 400);
|
||||
assert.deepEqual(seen, []);
|
||||
});
|
||||
|
||||
test("the user for managing can be taken away; the one that reads stays, and the audit log says it", async () => {
|
||||
reset();
|
||||
assert.equal((await fetch(`${base}/${managed}/manage`, { method: "DELETE", headers: as("operator") })).status, 403);
|
||||
assert.equal((await fetch(`${base}/${managed}/manage`, { method: "DELETE", headers: as("admin") })).status, 204);
|
||||
const loaded = await loadIntegrationConfig(managed);
|
||||
assert.deepEqual([loaded?.config.manageEmail, loaded?.config.managePassword, loaded?.config.email, loaded?.config.password], [undefined, undefined, "view@x", "view-pass"]);
|
||||
assert.equal((await create(managed, newHost)).status, 400);
|
||||
assert.equal((await audit("remove_npm_manage_login")).length, 1);
|
||||
assert.equal((await fetch(`${base}/${managed}/manage`, { method: "DELETE", headers: as("admin") })).status, 204);
|
||||
assert.equal((await audit("remove_npm_manage_login")).length, 1, "nothing more to take away, nothing more written");
|
||||
assert.equal((await fetch(`${base}/${other}/manage`, { method: "DELETE", headers: as("admin") })).status, 400);
|
||||
assert.equal((await fetch(`${base}/999999/manage`, { method: "DELETE", headers: as("admin") })).status, 404);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user