/** * Looking after Authentik groups: reading them with who is in them, making one, renaming one, deleting one, putting users in and taking them out — and what is refused (service accounts, the account the token belongs * to, the last active administrator losing that, a user whose groups Authentik did not say), that nothing is changed unless all of it may be, how far a failure got, who may, what is in the * audit log, and which groups decide roles in this app. * * 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 { randomUUID } from "node:crypto"; 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-groups-")); 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 { roleForGroupName } = await import("../src/auth/groups.js"); const { updateSettings } = await import("../src/services/settingsStore.js"); const { authentikRouter } = await import("../src/routes/authentik.js"); await runMigrations(); const G_ADMIN = "22222222-2222-4222-8222-222222222222"; const G_FAMILY = "11111111-1111-4111-8111-111111111111"; const G_OTHER = "44444444-4444-4444-8444-444444444444"; interface FakeGroup { pk: string; name: string; is_superuser: boolean; users: number[]; } 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 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 }); describe("what Authentik's answers are read as", () => { test("a group with who is in it: the ids of the users; none given is not the same as none", () => { assert.deepEqual(usersApi.parseGroupDetail({ pk: G_FAMILY, name: "Family", is_superuser: false, users: [3, 4, "x", 0, 1.5] }), { id: G_FAMILY, name: "Family", admin: false, members: [3, 4] }); assert.deepEqual(usersApi.parseGroupDetail({ pk: G_ADMIN, name: "admins", is_superuser: true, users: [] }), { id: G_ADMIN, name: "admins", admin: true, members: [] }); assert.equal(usersApi.parseGroupDetail({ pk: G_FAMILY, name: "Family" })!.members, null); assert.equal(usersApi.parseGroupDetail({ pk: "nope", name: "x" }), null); assert.equal(usersApi.parseGroupDetail({ pk: G_FAMILY, name: " " }), null); }); test("the list is by name", () => { const list = usersApi.parseGroupDetails({ results: [{ pk: G_OTHER, name: "other", users: [] }, { pk: G_FAMILY, name: "Family", users: [] }, { pk: "x", name: "junk" }] }); assert.deepEqual(list.map((g) => g.name), ["Family", "other"]); assert.deepEqual(usersApi.parseGroupDetails("nonsense"), []); }); test("a group decides a role here when roles follow the groups and its name is one of the named ones — compared the way sign-in compares", () => { const rules = { roleFromGroups: true, adminGroups: ["Homelab-Admins"], operatorGroups: [" ops "] }; assert.equal(roleForGroupName(rules, "homelab-admins"), "admin"); assert.equal(roleForGroupName(rules, "OPS"), "operator"); assert.equal(roleForGroupName(rules, "Family"), null); assert.equal(roleForGroupName({ ...rules, roleFromGroups: false }, "homelab-admins"), null); }); }); /** An Authentik with groups and users that remembers what it was asked. */ interface Seen { method: string; path: string; auth: string; body: string; } const seen: Seen[] = []; const freshGroups = (): FakeGroup[] => [ { pk: G_ADMIN, name: "admins", is_superuser: true, users: [1, 2] }, { pk: G_FAMILY, name: "Family", is_superuser: false, users: [3] }, { pk: G_OTHER, name: "Other", is_superuser: false, users: [] }, ]; const freshUsers = (): FakeUser[] => [ person(1, "akadmin", { is_superuser: true, groups: [G_ADMIN] }), person(2, "bob", { is_superuser: true, groups: [G_ADMIN] }), person(3, "carol", { groups: [G_FAMILY] }), person(4, "dave"), person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }), ]; let groupTable = freshGroups(); let userTable = freshUsers(); let meId = 1; /** A user id whose put-in or take-out Authentik answers with an error. */ let failMemberPk = 0; 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: groupTable }); if (req.method === "POST" && url.pathname === "/api/v3/core/groups/") { const b = JSON.parse(body) as { name: string; is_superuser?: boolean }; if (groupTable.some((g) => g.name === b.name)) return send(400, { name: ["A group with that name already exists."] }); const made: FakeGroup = { pk: randomUUID(), name: b.name, is_superuser: b.is_superuser === true, users: [] }; groupTable.push(made); return send(201, made); } const grp = /^\/api\/v3\/core\/groups\/([0-9a-f-]{36})\/(add_user\/|remove_user\/)?$/.exec(url.pathname); if (grp) { const group = groupTable.find((g) => g.pk === grp[1]); if (!group) return send(404, { detail: "Not found." }); if (!grp[2] && req.method === "GET") return send(200, group); if (!grp[2] && req.method === "DELETE") { groupTable = groupTable.filter((g) => g.pk !== group.pk); for (const u of userTable) if (u.groups) u.groups = u.groups.filter((g) => g !== group.pk); return send(204); } if (!grp[2] && req.method === "PATCH") { Object.assign(group, JSON.parse(body)); return send(200, group); } if (grp[2] && req.method === "POST") { const pk = (JSON.parse(body) as { pk: number }).pk; if (pk === failMemberPk) return send(500, { detail: "boom" }); const user = userTable.find((u) => u.pk === pk); if (!user) return send(404, { detail: "Not found." }); if (grp[2] === "add_user/") { if (!group.users.includes(pk)) group.users.push(pk); if (user.groups && !user.groups.includes(group.pk)) user.groups.push(group.pk); } else { group.users = group.users.filter((u) => u !== pk); if (user.groups) user.groups = user.groups.filter((g) => g !== group.pk); } user.is_superuser = (user.groups ?? []).some((g) => groupTable.find((x) => x.pk === g)?.is_superuser); return send(204); } } if (req.method === "GET" && url.pathname === "/api/v3/core/users/me/") return send(200, { user: userTable.find((u) => u.pk === meId) }); if (req.method === "GET" && url.pathname === "/api/v3/core/users/") { let list = userTable; 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); return send(200, { pagination: { total_pages: 1 }, results: list }); } const one = /^\/api\/v3\/core\/users\/(\d+)\/$/.exec(url.pathname); if (one && req.method === "GET") { const user = userTable.find((u) => u.pk === Number(one[1])); return user ? send(200, user) : send(404, { detail: "Not found." }); } 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(); }); const reset = () => { groupTable = freshGroups(); userTable = freshUsers(); meId = 1; failMemberPk = 0; seen.length = 0; }; describe("the calls", () => { const adapter = () => usersApi.createAuthentikUsersAdapter({ url: fakeUrl, writeToken: "write-tok" }); test("the groups are listed with their members, without the heavy user objects", async () => { reset(); const list = await adapter().listGroupDetails(); assert.deepEqual(list.map((g) => [g.name, g.admin, g.members]), [["admins", true, [1, 2]], ["Family", false, [3]], ["Other", false, []]]); assert.match(seen[0].path, /include_users=false/); assert.equal(seen[0].auth, "Bearer write-tok"); }); test("a group is made with a name and as one that does not make administrators — whatever else is asked of the adapter, only that is sent", async () => { reset(); const made = await adapter().createGroup("Gamers"); assert.deepEqual([made.name, made.admin, made.members], ["Gamers", false, []]); assert.deepEqual([seen[0].method, seen[0].path, seen[0].body], ["POST", "/api/v3/core/groups/", JSON.stringify({ name: "Gamers", is_superuser: false })]); await assert.rejects( () => adapter().createGroup("Gamers"), (err: Error & { kind?: string }) => err.kind === "invalid" && /name: A group with that name already exists\./.test(err.message), ); }); test("renaming is a PATCH of the name and nothing else; a member goes in or out with a POST of that one user", async () => { reset(); const renamed = await adapter().renameGroup(G_FAMILY, "Household"); assert.equal(renamed.name, "Household"); assert.deepEqual([seen[0].method, seen[0].path, seen[0].body], ["PATCH", `/api/v3/core/groups/${G_FAMILY}/`, JSON.stringify({ name: "Household" })]); await adapter().addMember(G_FAMILY, 4); await adapter().removeMember(G_FAMILY, 3); assert.deepEqual(seen.slice(1).map((s) => [s.method, s.path, s.body]), [["POST", `/api/v3/core/groups/${G_FAMILY}/add_user/`, '{"pk":4}'], ["POST", `/api/v3/core/groups/${G_FAMILY}/remove_user/`, '{"pk":3}']]); assert.deepEqual(groupTable.find((g) => g.pk === G_FAMILY)!.users, [4]); }); test("deleting is a DELETE of that group, answered with nothing", async () => { reset(); await adapter().deleteGroup(G_OTHER); assert.deepEqual([seen[0].method, seen[0].path], ["DELETE", `/api/v3/core/groups/${G_OTHER}/`]); assert.equal(groupTable.some((g) => g.pk === G_OTHER), false); await assert.rejects( () => adapter().deleteGroup(G_OTHER), (err: Error & { kind?: string }) => err.kind === "missing", ); seen.length = 0; await assert.rejects(() => adapter().deleteGroup("../x"), /not a group id/); assert.deepEqual(seen, []); }); test("a group id that is not an id and a user id that is not a whole number are never put in the address", async () => { reset(); for (const bad of ["../../x", "", "not-a-uuid", `${G_FAMILY}/../x`]) { await assert.rejects(() => adapter().getGroup(bad), /not a group id/); await assert.rejects(() => adapter().renameGroup(bad, "x"), /not a group id/); await assert.rejects(() => adapter().addMember(bad, 1), /not a group id/); } for (const pk of [0, -2, 1.5, Number.NaN]) await assert.rejects(() => adapter().removeMember(G_FAMILY, pk), /not a user id/); assert.deepEqual(seen, []); }); }); 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 details = (sub = "admin") => fetch(`${base}/${id}/group-details`, { headers: as(sub) }); const change = (gid: string, body: unknown, sub = "admin") => fetch(`${base}/${id}/groups/${gid}`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) }); const remove = (gid: string, name: unknown, sub = "admin") => fetch(`${base}/${id}/groups/${gid}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ name }) }); const make = (body: unknown, sub = "admin") => fetch(`${base}/${id}/groups`, { method: "POST", headers: as(sub), body: JSON.stringify(body) }); const writes = () => seen.filter((s) => s.method !== "GET"); const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action); const refused = async (res: Response, pattern: RegExp) => { assert.equal(res.status, 409); assert.match(((await res.json()) as { message: string }).message, pattern); }; 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; await updateSettings({ signIn: { roleFromGroups: true, groupsClaim: "groups", adminGroups: ["admins"], operatorGroups: ["family"], otherwise: "viewer" } }); 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 groups or changes them; nothing reaches Authentik for anyone else", async () => { reset(); for (const sub of ["viewer", "operator"]) { assert.equal((await details(sub)).status, 403, sub); assert.equal((await change(G_FAMILY, { name: "x" }, sub)).status, 403, sub); } assert.deepEqual(seen, []); }); test("the groups with their members and the people to name them by (not service accounts), which group decides a role here, and which user the token is", async () => { reset(); const res = await details(); assert.equal(res.status, 200); const text = await res.text(); assert.equal(/write-tok|read-tok/.test(text), false); const body = JSON.parse(text) as { groups: { name: string; admin: boolean; members: number[]; decidesRole: string | null }[]; people: { username: string }[]; self: number; more: boolean }; assert.deepEqual(body.groups.map((g) => [g.name, g.admin, g.members, g.decidesRole]), [["admins", true, [1, 2], "admin"], ["Family", false, [3], "operator"], ["Other", false, [], null]]); assert.deepEqual(body.people.map((p) => p.username), ["akadmin", "bob", "carol", "dave"]); assert.deepEqual([body.self, body.more], [1, false]); }); test("renaming and changing members: the name first, then each user, and the audit log says who was put in and taken out", async () => { reset(); const res = await change(G_FAMILY, { name: "Household", membersAdd: [4], membersRemove: [3] }); assert.equal(res.status, 200); assert.deepEqual(await res.json(), { changed: ["name", "members"], added: 1, removed: 1 }); assert.deepEqual(writes().map((s) => `${s.method} ${s.path.replace(G_FAMILY, "G")} ${s.body}`), ["PATCH /api/v3/core/groups/G/ {\"name\":\"Household\"}", "POST /api/v3/core/groups/G/add_user/ {\"pk\":4}", "POST /api/v3/core/groups/G/remove_user/ {\"pk\":3}"]); const [entry] = await audit("update_authentik_group"); assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_group", G_FAMILY]); assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: id, integration: "Front door", group: "Family", renamedTo: "Household", added: ["dave"], removed: ["carol"] }); }); test("members already in are not put in again, those not in are not taken out, and a change that changes nothing sends nothing and writes nothing", async () => { reset(); const before = (await audit("update_authentik_group")).length; const res = await change(G_FAMILY, { name: "Family", membersAdd: [3], membersRemove: [4] }); assert.deepEqual(await res.json(), { changed: [], added: 0, removed: 0 }); assert.deepEqual(writes(), []); assert.equal((await audit("update_authentik_group")).length, before); }); test("somebody who joined meanwhile is not dropped: members are put in and out one by one, never replaced", async () => { reset(); groupTable.find((g) => g.pk === G_OTHER)!.users = [4]; // dave joined after the page was read const res = await change(G_OTHER, { membersAdd: [3] }); assert.equal(res.status, 200); assert.deepEqual(groupTable.find((g) => g.pk === G_OTHER)!.users, [4, 3]); assert.deepEqual(writes().map((s) => s.path.split("/").slice(-2, -1)[0]), ["add_user"]); }); test("what is wrong with the change is said before Authentik is asked", async () => { reset(); for (const bad of [{ name: "" }, { membersAdd: ["x"] }, { membersAdd: [1.5] }, { membersAdd: [0] }, { membersAdd: [4], membersRemove: [4] }, { membersAdd: Array.from({ length: 26 }, (_, i) => i + 1) }]) { const res = await change(G_FAMILY, bad); assert.equal(res.status, 400, JSON.stringify(bad)); assert.equal(typeof ((await res.json()) as { message: string }).message, "string"); } assert.equal((await change("not-a-uuid", { name: "x" })).status, 400); assert.deepEqual(seen, []); }); test("a service account and the token's own account are refused, and nothing at all is changed — not even the name asked for in the same request", async () => { reset(); await refused(await change(G_FAMILY, { name: "Renamed", membersAdd: [5] }), /ak-outpost-front: .*service account/); await refused(await change(G_FAMILY, { name: "Renamed", membersAdd: [4, 1] }), /akadmin: .*token/); await refused(await change(G_ADMIN, { membersRemove: [1] }), /akadmin: .*token/); assert.deepEqual(writes(), []); assert.equal(groupTable.find((g) => g.pk === G_FAMILY)!.name, "Family"); assert.deepEqual(groupTable.find((g) => g.pk === G_FAMILY)!.users, [3], "dave, checked before akadmin, was not put in either"); }); test("the last active administrator can't be taken out of the group that makes them one — unless they are in another such group, or another administrator is active", async () => { reset(); meId = 3; userTable.find((u) => u.pk === 2)!.is_active = false; // bob is off: akadmin is the only active administrator await refused(await change(G_ADMIN, { membersRemove: [1] }), /akadmin: .*only active administrator/); assert.deepEqual(writes(), []); assert.equal((await change(G_ADMIN, { membersRemove: [2] })).status, 200, "bob is not an active administrator, so taking him out loses nothing"); // akadmin in a second administrators group: taking him out of the first leaves him an administrator. groupTable.push({ pk: "55555555-5555-4555-8555-555555555555", name: "root", is_superuser: true, users: [1] }); userTable.find((u) => u.pk === 1)!.groups!.push("55555555-5555-4555-8555-555555555555"); assert.equal((await change(G_ADMIN, { membersRemove: [1] })).status, 200); // And with another active administrator, one may come out of the only group. reset(); meId = 3; assert.equal((await change(G_ADMIN, { membersRemove: [1] })).status, 200); }); test("a user whose groups Authentik did not say can be put in a group, but not taken out of one that makes administrators", async () => { reset(); meId = 3; delete userTable.find((u) => u.pk === 2)!.groups; await refused(await change(G_ADMIN, { membersRemove: [2] }), /bob: .*did not say which groups/); assert.equal((await change(G_FAMILY, { membersAdd: [4] })).status, 200); assert.equal((await change(G_OTHER, { membersAdd: [2] })).status, 200); }); test("a group whose members Authentik did not say can be renamed but its members are not changed", async () => { reset(); delete (groupTable.find((g) => g.pk === G_OTHER) as Partial).users; await refused(await change(G_OTHER, { membersAdd: [4] }), /did not say who is in this group/); assert.equal((await change(G_OTHER, { name: "Others" })).status, 200); }); test("a failure part-way says how far it got, and the audit log has what was done", async () => { reset(); failMemberPk = 4; const res = await change(G_OTHER, { name: "Others", membersAdd: [3, 4] }); assert.equal(res.status, 502); assert.match(((await res.json()) as { message: string }).message, /boom|Authentik error/); assert.deepEqual(groupTable.find((g) => g.pk === G_OTHER)!.users, [3], "the name and carol were done; dave was not"); const entry = (await audit("update_authentik_group")).at(-1)!; const detail = JSON.parse(entry.detail ?? "{}") as { renamedTo?: string; added: string[] }; assert.deepEqual([detail.renamedTo, detail.added], ["Others", ["carol"]]); assert.match(((await (await change(G_OTHER, { membersAdd: [4] })).json()) as { message: string }).message, /0 of 1 changes had been made/); }); test("making a group: admin only; it is made empty and never as an administrators group, and the audit log says who made which", async () => { reset(); for (const sub of ["viewer", "operator"]) assert.equal((await make({ name: "Gamers" }, sub)).status, 403, sub); assert.deepEqual(seen, []); const res = await make({ name: " Gamers " }); assert.equal(res.status, 201); const body = (await res.json()) as { group: { id: string; name: string; admin: boolean; members: number[]; decidesRole: string | null } }; assert.deepEqual([body.group.name, body.group.admin, body.group.members, body.group.decidesRole], ["Gamers", false, [], null]); assert.deepEqual(writes().map((s) => [s.method, s.path, s.body]), [["POST", "/api/v3/core/groups/", JSON.stringify({ name: "Gamers", is_superuser: false })]]); assert.equal(groupTable.some((g) => g.name === "Gamers" && !g.is_superuser), true); const [entry] = await audit("create_authentik_group"); assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_group", body.group.id]); assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: id, integration: "Front door", group: "Gamers" }); }); test("a new group whose name decides a role here is said to; a name that is taken is Authentik's own words", async () => { reset(); const res = await make({ name: "Ops" }); assert.equal(res.status, 201); assert.equal(((await res.json()) as { group: { decidesRole: string | null } }).group.decidesRole, null); const mapped = await make({ name: "ADMINS-2" }); assert.equal(((await mapped.json()) as { group: { decidesRole: string | null } }).group.decidesRole, null, "only the names in Settings → Sign-in"); await updateSettings({ signIn: { roleFromGroups: true, groupsClaim: "groups", adminGroups: ["admins", "Root Team"], operatorGroups: ["family"], otherwise: "viewer" } }); const root = await make({ name: "root team" }); assert.equal(((await root.json()) as { group: { decidesRole: string | null } }).group.decidesRole, "admin", "compared the way sign-in compares"); seen.length = 0; const dup = await make({ name: "Family" }); assert.equal(dup.status, 400); assert.match(((await dup.json()) as { message: string }).message, /name: A group with that name already exists/); }); test("what is wrong with a new group is said before Authentik is asked", async () => { reset(); for (const bad of [{}, { name: "" }, { name: " " }, { name: "x".repeat(201) }, { name: 5 }]) { const res = await make(bad); assert.equal(res.status, 400, JSON.stringify(bad)); assert.equal(typeof ((await res.json()) as { message: string }).message, "string"); } assert.deepEqual(seen, []); }); test("deleting a group: admin only; the name has to match the group now; then it is gone, its members stay, and the audit log says so", async () => { reset(); await updateSettings({ signIn: { roleFromGroups: false, groupsClaim: "groups", adminGroups: [], operatorGroups: [], otherwise: "viewer" } }); for (const sub of ["viewer", "operator"]) assert.equal((await remove(G_OTHER, "Other", sub)).status, 403, sub); assert.deepEqual(seen, []); assert.equal((await remove(G_OTHER, undefined)).status, 400); assert.equal((await remove(G_OTHER, "")).status, 400); assert.equal((await remove("not-a-uuid", "Other")).status, 400); const wrong = await remove(G_OTHER, "Family"); assert.equal(wrong.status, 400); assert.equal(((await wrong.json()) as { error: string }).error, "name_mismatch"); assert.deepEqual(writes(), []); assert.equal(groupTable.some((g) => g.pk === G_OTHER), true); // Family has carol in it: she stays, just not in the group. assert.equal((await remove(G_FAMILY, "Family")).status, 204); assert.equal(groupTable.some((g) => g.pk === G_FAMILY), false); assert.equal(userTable.some((u) => u.username === "carol"), true); assert.deepEqual(writes().map((s) => [s.method, s.path]), [["DELETE", `/api/v3/core/groups/${G_FAMILY}/`]]); const [entry] = await audit("delete_authentik_group"); assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_group", G_FAMILY]); assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: id, integration: "Front door", group: "Family", members: 1, decidesRole: null }); }); test("a group that makes administrators is refused and not touched; one that decides roles here may be deleted, and the audit log says it was one", async () => { reset(); await updateSettings({ signIn: { roleFromGroups: true, groupsClaim: "groups", adminGroups: ["admins"], operatorGroups: ["Family"], otherwise: "viewer" } }); await refused(await remove(G_ADMIN, "admins"), /makes its members administrators/); assert.deepEqual(writes(), []); assert.equal(groupTable.some((g) => g.pk === G_ADMIN), true); assert.equal((await remove(G_FAMILY, "Family")).status, 204); const entry = (await audit("delete_authentik_group")).at(-1)!; assert.equal(JSON.parse(entry.detail ?? "{}").decidesRole, "operator"); }); test("a group that is gone is not found when deleting; an Authentik with no token for managing users is not asked", async () => { reset(); assert.equal((await remove("99999999-9999-4999-8999-999999999999", "x")).status, 404); seen.length = 0; assert.equal((await fetch(`${base}/${readOnly}/groups/${G_FAMILY}`, { method: "DELETE", headers: as("admin"), body: JSON.stringify({ name: "Family" }) })).status, 400); assert.deepEqual(seen, []); }); test("a group that is gone is not found; an Authentik with no token for managing users is not asked anything", async () => { reset(); assert.equal((await change("99999999-9999-4999-8999-999999999999", { name: "x" })).status, 404); seen.length = 0; assert.equal((await fetch(`${base}/${readOnly}/group-details`, { headers: as("admin") })).status, 400); assert.equal((await fetch(`${base}/${readOnly}/groups/${G_FAMILY}`, { method: "PATCH", headers: as("admin"), body: JSON.stringify({ name: "x" }) })).status, 400); assert.equal((await fetch(`${base}/${readOnly}/groups`, { method: "POST", headers: as("admin"), body: JSON.stringify({ name: "x" }) })).status, 400); assert.deepEqual(seen, []); }); });