Apps → Authentik gets a Users section for administrators: a searchable list of people (service accounts left out) with status, administrator and last sign-in, and Switch off / Switch on / Delete. Switching off sends only is_active; deleting needs the user name typed and re-checked by the server. The server refuses service accounts, the account the token belongs to and the last active administrator. Each action is audited. The token field is now "Token for making and managing users". Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
359 lines
18 KiB
TypeScript
359 lines
18 KiB
TypeScript
/**
|
|
* Looking after Authentik users: reading the list, switching a user off and on, 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;
|
|
}
|
|
const person = (pk: number, username: string, extra: Partial<FakeUser> = {}): FakeUser => ({ pk, username, name: username.toUpperCase(), email: `${username}@example.com`, is_active: true, is_superuser: false, last_login: null, type: "internal", ...extra });
|
|
const fresh = (): FakeUser[] => [
|
|
person(1, "akadmin", { is_superuser: true, last_login: "2026-10-30T08:00:00Z" }),
|
|
person(2, "bob", { is_superuser: true }),
|
|
person(3, "carol"),
|
|
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("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);
|
|
});
|
|
});
|
|
|
|
/** 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/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." });
|
|
user.is_active = JSON.parse(body).is_active;
|
|
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<void>((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 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<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/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("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, []);
|
|
});
|
|
});
|