Delete Authentik groups

Each group in Apps → Authentik → Users and groups gets a Delete button: the
group's name has to be typed, and the server checks it against the group as
Authentik has it now. A group that makes its members administrators is
refused (deleted in Authentik). A group that decides roles in this app may be
deleted after a warning, and the audit log records its member count and that
it decided a role. Members stay, just not in the group.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 04:00:47 +01:00
1 parent e7e3c73e77
commit e4cd01e9ba
8 files changed
+151 -12

No files matched your search

+7 -2
View File
@@ -6,7 +6,7 @@
* person gets to choose their own password: this app never sets, sees or keeps one. The link is handed back once and not stored.
*
* Looking after groups: the groups with who is in them (`GET /core/groups/`, one `GET /core/groups/{id}/`), making one (`POST /core/groups/` with a name and never as a group that makes administrators),
* renaming one (`PATCH` with only `name`) and putting a user in or taking one out
* renaming one (`PATCH` with only `name`), deleting one (`DELETE /core/groups/{id}/` — never one that makes administrators, which the caller refuses) and putting a user in or taking one out
* (`POST /core/groups/{id}/add_user/` and `remove_user/`, one user each — never a whole list of members, so someone who joined meanwhile is not dropped). Whether a group makes its members
* administrators of Authentik (`is_superuser`) is shown, and neither changed nor set when one is made, from here.
*
@@ -212,6 +212,7 @@ export interface AuthentikUsersAdapter {
getGroup(id: string): Promise<AuthentikGroupDetail>;
createGroup(name: string): Promise<AuthentikGroupDetail>;
renameGroup(id: string, name: string): Promise<AuthentikGroupDetail>;
deleteGroup(id: string): Promise<void>;
addMember(id: string, userPk: number): Promise<void>;
removeMember(id: string, userPk: number): Promise<void>;
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
@@ -314,6 +315,10 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
return group;
}
async function deleteGroup(id: string): Promise<void> {
await call("DELETE", `/core/groups/${groupId(id)}/`);
}
async function addMember(id: string, userPk: number): Promise<void> {
await call("POST", `/core/groups/${groupId(id)}/add_user/`, { pk: wholeNumber(userPk) }, true);
}
@@ -342,5 +347,5 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
return link;
}
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroupDetails, getGroup, createGroup, renameGroup, addMember, removeMember, listGroups, createUser, recoveryLink });
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroupDetails, getGroup, createGroup, renameGroup, deleteGroup, addMember, removeMember, listGroups, createUser, recoveryLink });
}
+34
View File
@@ -444,3 +444,37 @@ authentikRouter.post("/:id/groups", requireRole("admin"), asyncHandler(async (re
sendFailure(res, err);
}
}));
const deleteGroupSchema = z.object({ name: z.string().min(1).max(200) });
/**
* Deletes a group for good; its members stay, just not in it. The group's name has to be sent along and has to be the one it has now (a page that is minutes old cannot delete another group),
* and a group that makes its members administrators of Authentik is refused: deleting it would take that from all of them at once, possibly from the last administrator. A group that decides
* roles in this app (Settings → Sign-in) may be deleted — the page asks first — and the audit log says it was one.
*/
authentikRouter.delete("/:id/groups/:gid", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = deleteGroupSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "The name of the group has to be sent along to delete it." });
const gid = req.params.gid;
if (!GROUP_ID.test(gid)) return res.status(400).json({ error: "invalid_group" });
const target = await usersAdapterFor(req.params.id, res);
if (!target) return;
try {
const group = await target.adapter.getGroup(gid);
if (group.name !== parsed.data.name) return res.status(400).json({ error: "name_mismatch", message: "That is not the name of that group." });
if (group.admin) return res.status(409).json({ error: "refused", message: "That group makes its members administrators of Authentik; deleting it would take that from all of them at once. Do it in Authentik if you mean to." });
const settings = await getSettings();
await target.adapter.deleteGroup(gid);
await recordAudit({
actor: req.currentUser!,
category: "integration",
action: "delete_authentik_group",
targetType: "authentik_group",
targetId: gid,
detail: { integrationId: target.id, integration: target.name, group: group.name, members: group.members?.length ?? null, decidesRole: roleForGroupName(settings.signIn, group.name) },
});
res.status(204).end();
} catch (err) {
sendFailure(res, err);
}
}));
+63 -1
View File
@@ -1,5 +1,5 @@
/**
* Looking after Authentik groups: reading them with who is in them, making one, renaming one, putting users in and taking them out — and what is refused (service accounts, the account the token belongs
* 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.
*
@@ -136,6 +136,11 @@ before(async () => {
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);
@@ -219,6 +224,20 @@ describe("the calls", () => {
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`]) {
@@ -240,6 +259,7 @@ describe("the routes", () => {
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);
@@ -439,6 +459,48 @@ describe("the routes", () => {
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);