Create Authentik groups from Apps → Authentik

A New group form in the Groups section makes a group with a name and nothing
else: it starts empty and is never one that makes administrators of
Authentik. A name Authentik already has is refused in its own words, and a
name that decides a role in this app (Settings → Sign-in) is said to. Admin
only; audited with who made which group.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 00:58:33 +01:00
1 parent 6c5a5f0bd6
commit c9385387bc
9 files changed
+152 -12

No files matched your search

+12 -3
View File
@@ -5,9 +5,10 @@
* Making one takes three calls: the groups to offer (`GET /core/groups/`), the user (`POST /core/users/`) and a one-time recovery link for that user (`POST /core/users/{pk}/recovery/`), which is how the
* 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}/`), renaming one (`PATCH` with only `name`) and putting a user in or taking one out
* 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
* (`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 not changed from here.
* administrators of Authentik (`is_superuser`) is shown, and neither changed nor set when one is made, from here.
*
* Looking after them: the users (`GET /core/users/`, one `GET /core/users/{pk}/`), who the token is (`GET /core/users/me/`), switching one off or on (`PATCH /core/users/{pk}/` with only `is_active`),
* changing their name, email and groups (the same `PATCH`, with only what changed — never the user name, which is how a person is known elsewhere) and deleting one (`DELETE /core/users/{pk}/`). Service accounts — what an outpost or an integration signs in with — are not listed and are refused, and so are the account the token belongs to and the last
@@ -209,6 +210,7 @@ export interface AuthentikUsersAdapter {
listGroups(): Promise<AuthentikGroup[]>;
listGroupDetails(): Promise<AuthentikGroupDetail[]>;
getGroup(id: string): Promise<AuthentikGroupDetail>;
createGroup(name: string): Promise<AuthentikGroupDetail>;
renameGroup(id: string, name: string): Promise<AuthentikGroupDetail>;
addMember(id: string, userPk: number): Promise<void>;
removeMember(id: string, userPk: number): Promise<void>;
@@ -298,6 +300,13 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
return group;
}
async function createGroup(name: string): Promise<AuthentikGroupDetail> {
// Only a name, and never a group that makes administrators: that is decided in Authentik.
const group = parseGroupDetail(await call("POST", "/core/groups/", { name, is_superuser: false }));
if (!group) throw new AuthentikUserError("Authentik answered, but not with the group it made", "failed");
return group;
}
async function renameGroup(id: string, name: string): Promise<AuthentikGroupDetail> {
// Only the name: a PATCH leaves out what it does not mention, so whether the group makes administrators, its members and its parent are as they were.
const group = parseGroupDetail(await call("PATCH", `/core/groups/${groupId(id)}/`, { name }));
@@ -333,5 +342,5 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
return link;
}
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroupDetails, getGroup, renameGroup, addMember, removeMember, listGroups, createUser, recoveryLink });
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroupDetails, getGroup, createGroup, renameGroup, addMember, removeMember, listGroups, createUser, recoveryLink });
}
+21
View File
@@ -423,3 +423,24 @@ authentikRouter.patch("/:id/groups/:gid", requireRole("admin"), asyncHandler(asy
sendFailure(res, err);
}
}));
const newGroupSchema = z.object({ name: z.string().trim().min(1, "A group needs a name.").max(200) });
/**
* Makes a group: a name, nothing else — it has no members (they are put in with the editor, which asks first where a group decides roles here) and it is never one that makes administrators of
* Authentik. A name Authentik already has is its own refusal. The answer says whether the new name decides a role in this app, so the page can say what putting someone in it would mean.
*/
authentikRouter.post("/:id/groups", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = newGroupSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a group.", details: parsed.error.flatten() });
const target = await usersAdapterFor(req.params.id, res);
if (!target) return;
try {
const group = await target.adapter.createGroup(parsed.data.name);
await recordAudit({ actor: req.currentUser!, category: "integration", action: "create_authentik_group", targetType: "authentik_group", targetId: group.id, detail: { integrationId: target.id, integration: target.name, group: group.name } });
const settings = await getSettings();
res.status(201).json({ group: { ...group, decidesRole: roleForGroupName(settings.signIn, group.name) } });
} catch (err) {
sendFailure(res, err);
}
}));
+63 -1
View File
@@ -1,5 +1,5 @@
/**
* Looking after Authentik groups: reading them with who is in them, 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, 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.
*
@@ -8,6 +8,7 @@
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";
@@ -123,6 +124,13 @@ before(async () => {
};
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]);
@@ -189,6 +197,17 @@ describe("the calls", () => {
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");
@@ -221,6 +240,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 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) => {
@@ -378,12 +398,54 @@ describe("the routes", () => {
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("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, []);
});
});