/** * Looking after Authentik users: reading the list, switching a user off and on, editing one, deleting one — and what is refused (service accounts, the account the token belongs to, the last active * administrator, a user name that does not match), who may, 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-authentik-useradmin-")); 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 usersApi = await import("../src/integrations/authentik/users.js"); const { authentikRouter } = await import("../src/routes/authentik.js"); await runMigrations(); interface FakeUser { pk: number; username: string; name: string; email: string; is_active: boolean; is_superuser: boolean; last_login: string | null; type: string; groups?: string[]; } const G_ADMIN = "22222222-2222-4222-8222-222222222222"; const G_FAMILY = "11111111-1111-4111-8111-111111111111"; const G_OTHER = "44444444-4444-4444-8444-444444444444"; const person = (pk: number, username: string, extra: Partial = {}): FakeUser => ({ pk, username, name: username.toUpperCase(), email: `${username}@example.com`, is_active: true, is_superuser: false, last_login: null, type: "internal", groups: [], ...extra }); const fresh = (): FakeUser[] => [ person(1, "akadmin", { is_superuser: true, last_login: "2026-10-30T08:00:00Z", groups: [G_ADMIN] }), person(2, "bob", { is_superuser: true, groups: [G_ADMIN] }), person(3, "carol", { groups: [G_FAMILY] }), person(4, "dave", { is_active: false }), person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }), ]; describe("what Authentik's answers are read as", () => { test("the list: people only, with whether they are on, administrators and when they last signed in; and whether there are more pages", () => { const { users: list, more } = usersApi.parseUsers({ pagination: { total_pages: 2 }, results: fresh() }); assert.deepEqual(list.map((u) => u.username), ["akadmin", "bob", "carol", "dave"], "the outpost's account is not a person"); assert.deepEqual([list[0].admin, list[0].lastLogin, list[3].active, list[2].email], [true, "2026-10-30T08:00:00.000Z", false, "carol@example.com"]); assert.equal(more, true); assert.equal(usersApi.parseUsers({ pagination: { total_pages: 1 }, results: [] }).more, false); assert.deepEqual(usersApi.parseUsers("nonsense"), { users: [], more: false }); }); test("a user needs a whole-number id and a user name; a version that does not say the type has only people", () => { assert.equal(usersApi.parseUser({ pk: "3", username: "x" }), null); assert.equal(usersApi.parseUser({ pk: 3 }), null); const u = usersApi.parseUser({ pk: 3, username: "x" })!; assert.deepEqual([u.type, u.active, u.admin, u.email, u.name], ["internal", true, false, null, "x"]); assert.equal(usersApi.isServiceAccount({ type: "service_account" }), true); assert.equal(usersApi.isServiceAccount({ type: "internal_service_account" }), true); assert.equal(usersApi.isServiceAccount({ type: "external" }), false); }); test("a user's groups are the ids Authentik gives; none given is not the same as none", () => { assert.deepEqual(usersApi.parseUser({ pk: 3, username: "x", groups: [G_FAMILY, "nope", 7] })!.groups, [G_FAMILY]); assert.deepEqual(usersApi.parseUser({ pk: 3, username: "x", groups: [] })!.groups, []); assert.equal(usersApi.parseUser({ pk: 3, username: "x" })!.groups, null); }); test("groups are changed from the ones there are now: what goes out goes, what comes in comes, once, and what neither mentions stays", () => { assert.deepEqual(usersApi.applyGroupChange([G_FAMILY, G_OTHER], [G_ADMIN], [G_FAMILY]), [G_OTHER, G_ADMIN]); assert.deepEqual(usersApi.applyGroupChange([G_FAMILY], [G_FAMILY], []), [G_FAMILY]); assert.deepEqual(usersApi.applyGroupChange([G_FAMILY], [], [G_OTHER]), [G_FAMILY]); }); test("who the token is comes out of /users/me/", () => { assert.equal(usersApi.parseMe({ user: { pk: 9 } }), 9); assert.equal(usersApi.parseMe({ user: { pk: "9" } }), null); assert.equal(usersApi.parseMe({}), null); }); test("what is refused: a service account always; the token's own account and the last active administrator when switching off or deleting; switching on, never", () => { const [akadmin, bob, carol, dave, outpost] = fresh().map((f) => usersApi.parseUser(f)!); assert.match(usersApi.refusalFor(outpost, "disable", 1, [1, 2]) ?? "", /service account/); assert.match(usersApi.refusalFor(outpost, "enable", 1, [1, 2]) ?? "", /service account/); assert.match(usersApi.refusalFor(akadmin, "disable", 1, [1, 2]) ?? "", /token/); assert.match(usersApi.refusalFor(akadmin, "delete", 1, [1, 2]) ?? "", /token/); assert.equal(usersApi.refusalFor(akadmin, "enable", 1, [1, 2]), null); assert.equal(usersApi.refusalFor(bob, "disable", 1, [1, 2]), null, "there is another administrator"); assert.match(usersApi.refusalFor(bob, "delete", 1, [2]) ?? "", /only active administrator/); assert.equal(usersApi.refusalFor({ ...bob, active: false }, "delete", 1, [1]), null, "one that is already off is not the one holding the door"); assert.equal(usersApi.refusalFor(carol, "delete", 1, [1]), null); assert.equal(usersApi.refusalFor(dave, "disable", null, []), null); // Editing: the token's own account and a service account never; the last administrator only when the edit would take them out of being one. assert.match(usersApi.refusalFor(akadmin, "edit", 1, [1, 2]) ?? "", /token/); assert.match(usersApi.refusalFor(outpost, "edit", 1, [1, 2]) ?? "", /service account/); assert.match(usersApi.refusalFor(bob, "edit", 1, [2], true) ?? "", /only active administrator/); assert.equal(usersApi.refusalFor(bob, "edit", 1, [2], false), null); assert.equal(usersApi.refusalFor(bob, "edit", 1, [1, 2], true), null); }); }); /** An Authentik with a few users that remembers what it was asked. */ interface Seen { method: string; path: string; auth: string; body: string; } const seen: Seen[] = []; let table = fresh(); let meId = 1; let patchStatus = 200; let fake: Server; let fakeUrl = ""; before(async () => { fake = createHttpServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { const path = req.url ?? ""; seen.push({ method: req.method ?? "", path, auth: String(req.headers.authorization ?? ""), body }); const send = (status: number, json?: unknown) => { if (json === undefined) { res.writeHead(status); return res.end(); } res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(json)); }; const url = new URL(path, "http://x"); if (req.method === "GET" && url.pathname === "/api/v3/core/groups/") return send(200, { results: [{ pk: G_ADMIN, name: "admins", is_superuser: true }, { pk: G_FAMILY, name: "Family", is_superuser: false }, { pk: G_OTHER, name: "Other", is_superuser: false }] }); if (req.method === "GET" && url.pathname === "/api/v3/core/users/me/") return send(200, { user: table.find((u) => u.pk === meId) ?? person(meId, "me") }); if (req.method === "GET" && url.pathname === "/api/v3/core/users/") { let list = table; if (url.searchParams.get("is_superuser") === "true") list = list.filter((u) => u.is_superuser); if (url.searchParams.get("is_active") === "true") list = list.filter((u) => u.is_active); const q = url.searchParams.get("search"); if (q) list = list.filter((u) => u.username.includes(q) || u.name.toLowerCase().includes(q.toLowerCase())); return send(200, { pagination: { total_pages: 1 }, results: list }); } const one = /^\/api\/v3\/core\/users\/(\d+)\/$/.exec(url.pathname); if (one) { const user = table.find((u) => u.pk === Number(one[1])); if (!user) return send(404, { detail: "Not found." }); if (req.method === "GET") return send(200, user); if (req.method === "PATCH") { if (patchStatus !== 200) return send(patchStatus, { detail: "You do not have permission to perform this action." }); const b = JSON.parse(body) as Partial; Object.assign(user, b); if (b.groups) user.is_superuser = b.groups.includes(G_ADMIN); return send(200, user); } if (req.method === "DELETE") { table = table.filter((u) => u.pk !== user.pk); return send(204); } } return send(200, { results: [] }); }); }); await new Promise((resolve) => fake.listen(0, "127.0.0.1", resolve)); fakeUrl = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`; }); after(() => { fake.close(); }); describe("the calls", () => { const adapter = () => usersApi.createAuthentikUsersAdapter({ url: fakeUrl, writeToken: "write-tok" }); const reset = () => { table = fresh(); meId = 1; patchStatus = 200; seen.length = 0; }; test("the list is asked for by name, with what was searched for, using the token for managing users", async () => { reset(); const all = await adapter().listUsers(); assert.deepEqual(all.users.map((u) => u.username), ["akadmin", "bob", "carol", "dave"]); const found = await adapter().listUsers(" car ol&x "); assert.deepEqual(found.users, [], "nothing is called that"); assert.match(seen[1].path, /search=car%20ol%26x$/); assert.deepEqual([...new Set(seen.map((s) => s.auth))], ["Bearer write-tok"]); assert.equal(await adapter().whoAmI(), 1); }); test("switching off is a PATCH of that one field and nothing else; deleting is a DELETE of that user", async () => { reset(); const off = await adapter().setActive(3, false); assert.equal(off.active, false); assert.deepEqual([seen[0].method, seen[0].path, seen[0].body], ["PATCH", "/api/v3/core/users/3/", JSON.stringify({ is_active: false })]); await adapter().deleteUser(4); assert.deepEqual([seen[1].method, seen[1].path], ["DELETE", "/api/v3/core/users/4/"]); assert.equal(table.some((u) => u.pk === 4), false); }); test("a user id that is not a whole number is never put in the address; a user that is gone is said so", async () => { reset(); for (const bad of [0, -1, 1.5, Number.NaN]) { await assert.rejects(() => adapter().setActive(bad, false), /not a user id/); await assert.rejects(() => adapter().deleteUser(bad), /not a user id/); await assert.rejects(() => adapter().getUser(bad), /not a user id/); } assert.deepEqual(seen, []); await assert.rejects( () => adapter().getUser(99), (err: Error & { kind?: string }) => err.kind === "missing", ); }); test("the active administrators are asked for as such", async () => { reset(); assert.deepEqual(await adapter().activeAdmins(), [1, 2]); assert.match(seen[0].path, /is_superuser=true/); assert.match(seen[0].path, /is_active=true/); }); }); describe("the routes", () => { let app: Server; let base = ""; let id = 0; let readOnly = 0; const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub }); const list = (sub = "admin", q = "") => fetch(`${base}/${id}/users${q}`, { headers: as(sub) }); const active = (pk: number, on: boolean, sub = "admin", integration = id) => fetch(`${base}/${integration}/users/${pk}/active`, { method: "POST", headers: as(sub), body: JSON.stringify({ active: on }) }); const del = (pk: number, username: unknown, sub = "admin") => fetch(`${base}/${id}/users/${pk}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ username }) }); const change = (pk: number, body: unknown, sub = "admin") => fetch(`${base}/${id}/users/${pk}`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) }); const writes = () => seen.filter((s) => s.method !== "GET"); const reset = () => { table = fresh(); meId = 1; patchStatus = 200; seen.length = 0; }; const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action); before(async () => { await db.insert(users).values([ { oidcSub: "admin", name: "Alma", role: "admin" }, { oidcSub: "operator", name: "Olle", role: "operator" }, { oidcSub: "viewer", name: "Vic", role: "viewer" }, ]); const cred = (await db.insert(integrationCredentials).values({ name: "authentik:Front door", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok", writeToken: "write-tok" })) }).returning({ id: integrationCredentials.id }))[0]; const credRead = (await db.insert(integrationCredentials).values({ name: "authentik:Watched", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok" })) }).returning({ id: integrationCredentials.id }))[0]; const config = JSON.stringify({ url: fakeUrl }); id = (await db.insert(integrations).values({ type: "authentik", name: "Front door", baseUrl: fakeUrl, config, credentialId: cred.id }).returning({ id: integrations.id }))[0].id; readOnly = (await db.insert(integrations).values({ type: "authentik", name: "Watched", baseUrl: fakeUrl, config, credentialId: credRead.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/authentik", authentikRouter); app = await new Promise((resolve) => { const s = a.listen(0, "127.0.0.1", () => resolve(s)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/authentik`; }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); test("only an administrator sees the users or changes them; nothing reaches Authentik for anyone else", async () => { reset(); for (const sub of ["viewer", "operator"]) { assert.equal((await list(sub)).status, 403, sub); assert.equal((await active(3, false, sub)).status, 403, sub); assert.equal((await del(3, "carol", sub)).status, 403, sub); } assert.deepEqual(seen, []); }); test("the list: the people, whether each is on, which one the token is, and what was searched for", async () => { reset(); const res = await list(); assert.equal(res.status, 200); const body = (await res.json()) as { users: { pk: number; username: string; active: boolean; admin: boolean; lastLogin: string | null }[]; more: boolean; self: number }; assert.deepEqual(body.users.map((u) => [u.pk, u.username, u.active, u.admin]), [[1, "akadmin", true, true], [2, "bob", true, true], [3, "carol", true, false], [4, "dave", false, false]]); assert.deepEqual([body.self, body.more], [1, false]); const found = (await (await list("admin", "?search=carol")).json()) as { users: { username: string }[] }; assert.deepEqual(found.users.map((u) => u.username), ["carol"]); assert.equal(/write-tok|read-tok/.test(JSON.stringify(body)), false); }); test("switching a user off and on: Authentik is asked for exactly that, and the audit log says who did it to whom", async () => { reset(); const off = await active(3, false); assert.equal(off.status, 200); assert.equal(((await off.json()) as { user: { active: boolean } }).user.active, false); assert.deepEqual(writes().map((s) => [s.method, s.path, s.body]), [["PATCH", "/api/v3/core/users/3/", JSON.stringify({ is_active: false })]]); assert.equal(table.find((u) => u.pk === 3)!.is_active, false); const on = await active(3, true); assert.equal(on.status, 200); assert.equal(table.find((u) => u.pk === 3)!.is_active, true); const [d] = await audit("disable_authentik_user"); const [e] = await audit("enable_authentik_user"); for (const entry of [d, e]) { assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "3"]); assert.match(entry.detail ?? "", /carol/); } }); test("a service account, the account the token belongs to, and the last active administrator are refused — and not touched", async () => { reset(); const refused = async (res: Response, pattern: RegExp) => { assert.equal(res.status, 409); assert.match(((await res.json()) as { message: string }).message, pattern); }; await refused(await active(5, false), /service account/); await refused(await del(5, "ak-outpost-front"), /service account/); await refused(await active(1, false), /token/); await refused(await del(1, "akadmin"), /token/); assert.deepEqual(writes(), []); // The token is somebody else's now, and bob is the only other administrator: with bob off, akadmin is the last one holding the door. meId = 3; assert.equal((await active(2, false)).status, 200, "there is still akadmin"); await refused(await active(1, false), /only active administrator/); await refused(await del(1, "akadmin"), /only active administrator/); assert.deepEqual(writes().map((s) => s.path), ["/api/v3/core/users/2/"]); assert.equal((await active(5, true)).status, 409, "not even to switch one on"); }); test("deleting: the user name has to match the user now; then they are gone, and it is written down", async () => { reset(); assert.equal((await del(4, undefined)).status, 400); assert.equal((await del(4, "")).status, 400); const wrong = await del(4, "carol"); assert.equal(wrong.status, 400); assert.equal(((await wrong.json()) as { error: string }).error, "username_mismatch"); assert.deepEqual(writes(), []); assert.equal(table.some((u) => u.pk === 4), true); assert.equal((await del(4, "dave")).status, 204); assert.equal(table.some((u) => u.pk === 4), false); assert.deepEqual(writes().map((s) => [s.method, s.path]), [["DELETE", "/api/v3/core/users/4/"]]); const [entry] = await audit("delete_authentik_user"); assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "4"]); assert.match(entry.detail ?? "", /dave/); }); test("a user that is gone, an id that is no id, and a refusal from Authentik itself are told as such", async () => { reset(); assert.equal((await active(99, false)).status, 404); assert.equal((await del(99, "x")).status, 404); assert.equal((await active(Number.NaN, false)).status, 400); assert.equal((await fetch(`${base}/${id}/users/1e3/active`, { method: "POST", headers: as("admin"), body: JSON.stringify({ active: false }) })).status, 400); assert.equal((await fetch(`${base}/${id}/users/3/active`, { method: "POST", headers: as("admin"), body: JSON.stringify({ active: "yes" }) })).status, 400); const before = (await audit("disable_authentik_user")).length; patchStatus = 403; const res = await active(3, false); assert.equal(res.status, 502); assert.match(((await res.json()) as { message: string }).message, /did not accept the token/); assert.equal((await audit("disable_authentik_user")).length, before, "nothing was done, so nothing more is written down"); }); test("editing: only what differs is sent, never the user name; the audit log names the fields, not what they were changed to", async () => { reset(); const res = await change(3, { name: "Carol C", email: "carol@new.example" }); assert.equal(res.status, 200); assert.deepEqual(((await res.json()) as { changed: string[] }).changed, ["name", "email"]); assert.deepEqual(writes().map((s) => [s.method, s.path, s.body]), [["PATCH", "/api/v3/core/users/3/", JSON.stringify({ name: "Carol C", email: "carol@new.example" })]]); assert.deepEqual([table.find((u) => u.pk === 3)!.name, table.find((u) => u.pk === 3)!.username], ["Carol C", "carol"]); const entry = (await audit("update_authentik_user")).at(-1)!; assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "3"]); assert.match(entry.detail ?? "", /carol/); assert.match(entry.detail ?? "", /"changed":\["name","email"\]/); assert.equal(/new\.example|Carol C/.test(entry.detail ?? ""), false); // The same again changes nothing, so nothing is sent and nothing is written down. const before = (await audit("update_authentik_user")).length; seen.length = 0; const again = await change(3, { name: "Carol C", email: "carol@new.example", groupsAdd: [], groupsRemove: [] }); assert.deepEqual(((await again.json()) as { changed: string[] }).changed, []); assert.deepEqual(writes(), []); assert.equal((await audit("update_authentik_user")).length, before); // An empty email clears it. assert.equal((await change(3, { email: "" })).status, 200); assert.equal(writes().at(-1)!.body, JSON.stringify({ email: "" })); }); test("groups are changed by what goes in and out, on top of the groups the user has now", async () => { reset(); // Somebody put carol in another group after the page was read: that stays. table.find((u) => u.pk === 3)!.groups = [G_FAMILY, G_OTHER]; const res = await change(3, { groupsAdd: [G_ADMIN], groupsRemove: [G_FAMILY] }); assert.equal(res.status, 200); assert.deepEqual(JSON.parse(writes()[0].body), { groups: [G_OTHER, G_ADMIN] }); seen.length = 0; const same = await change(3, { groupsAdd: [G_OTHER], groupsRemove: [G_FAMILY] }); assert.deepEqual(((await same.json()) as { changed: string[] }).changed, [], "putting in what is there and taking out what is not changes nothing"); assert.deepEqual(writes(), []); }); test("what is wrong with the change is said before Authentik is asked", async () => { reset(); for (const bad of [{ name: "" }, { email: "not-an-email" }, { groupsAdd: ["not-a-uuid"] }, { groupsAdd: [G_FAMILY], groupsRemove: [G_FAMILY] }, { groupsRemove: "x" }]) { const res = await change(3, bad); assert.equal(res.status, 400, JSON.stringify(bad)); assert.equal(typeof ((await res.json()) as { message: string }).message, "string"); } assert.equal((await fetch(`${base}/${id}/users/1e3`, { method: "PATCH", headers: as("admin"), body: JSON.stringify({ name: "x" }) })).status, 400); assert.deepEqual(seen, []); }); test("editing is refused for a service account, for the token's own account, and for the last administrator when it would take them out of being one", async () => { reset(); const refused = async (res: Response, pattern: RegExp) => { assert.equal(res.status, 409); assert.match(((await res.json()) as { message: string }).message, pattern); }; await refused(await change(5, { name: "x" }), /service account/); await refused(await change(1, { name: "x" }), /token/); assert.deepEqual(writes(), []); // The token is carol's account now; bob is off, so akadmin is the only active administrator. meId = 3; table.find((u) => u.pk === 2)!.is_active = false; await refused(await change(1, { groupsRemove: [G_ADMIN] }), /only active administrator/); assert.deepEqual(writes(), []); assert.equal((await change(1, { name: "Root" })).status, 200, "a name is no danger"); assert.equal((await change(1, { groupsAdd: [G_FAMILY] })).status, 200, "nor is another group"); assert.equal((await change(1, { groupsRemove: [G_FAMILY] })).status, 200); // With another administrator on, they may be taken out of the group. table.find((u) => u.pk === 2)!.is_active = true; assert.equal((await change(1, { groupsRemove: [G_ADMIN] })).status, 200); assert.deepEqual(table.find((u) => u.pk === 1)!.groups, []); }); test("a user whose groups Authentik did not say can be renamed but not moved between groups", async () => { reset(); delete table.find((u) => u.pk === 3)!.groups; const res = await change(3, { groupsAdd: [G_FAMILY] }); assert.equal(res.status, 409); assert.match(((await res.json()) as { message: string }).message, /did not say which groups/); assert.deepEqual(writes(), []); assert.equal((await change(3, { name: "Only Name" })).status, 200); }); test("only an administrator edits; a user that is gone is not found; a token that may not is a bad gateway", async () => { reset(); for (const sub of ["viewer", "operator"]) assert.equal((await change(3, { name: "x" }, sub)).status, 403, sub); assert.deepEqual(seen, []); assert.equal((await change(99, { name: "x" })).status, 404); patchStatus = 403; const res = await change(3, { name: "Someone Else" }); assert.equal(res.status, 502); assert.match(((await res.json()) as { message: string }).message, /did not accept the token/); }); test("the list carries each person's groups", async () => { reset(); const body = (await (await list()).json()) as { users: { username: string; groups: string[] | null }[] }; assert.deepEqual(body.users.map((u) => [u.username, u.groups]), [["akadmin", [G_ADMIN]], ["bob", [G_ADMIN]], ["carol", [G_FAMILY]], ["dave", []]]); }); test("an Authentik with no token for managing users is not asked anything", async () => { reset(); const res = await fetch(`${base}/${readOnly}/users`, { headers: as("admin") }); assert.equal(res.status, 400); assert.equal(((await res.json()) as { error: string }).error, "no_write_token"); assert.equal((await active(3, false, "admin", readOnly)).status, 400); assert.deepEqual(seen, []); }); });