Edit Authentik groups: rename and change members

Apps → Authentik gets a Groups section for administrators: the groups with
member counts, and an Edit form to rename one and put users in and take them
out. Members are changed one user at a time, never by replacing the list.
Everything is checked first and nothing changes unless all of it may; service
accounts, the token's own account and the last active administrator losing
that are refused. Whether a group makes administrators is shown, not changed.
Groups that decide roles in this app (Settings → Sign-in) are marked and ask
first. Audited with who was put in and taken out.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 00:49:43 +01:00
1 parent 3618cb3ae8
commit 6c5a5f0bd6
10 files changed
+794 -9

No files matched your search

+9
View File
@@ -42,6 +42,15 @@ export function extractGroups(sources: Record<string, unknown>[], claim: string)
const norm = (s: string) => s.trim().toLowerCase();
/** The role a group of this name decides in this app, if any: "admin" or "operator" when roles follow the groups and the name is one of the named ones (compared the way sign-in does); otherwise null. */
export function roleForGroupName(settings: Pick<SignInRoleSettings, "roleFromGroups" | "adminGroups" | "operatorGroups">, name: string): "admin" | "operator" | null {
if (!settings.roleFromGroups) return null;
const n = norm(name);
if (settings.adminGroups.some((g) => norm(g) === n)) return "admin";
if (settings.operatorGroups.some((g) => norm(g) === n)) return "operator";
return null;
}
/** The role these groups give: admin if any is an admin group, else operator if any is an operator group, else what `otherwise` says. */
export function roleFromGroups(settings: SignInRoleSettings, groups: string[], current: UserRole): UserRole {
const have = new Set(groups.map(norm));
+66 -5
View File
@@ -5,6 +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
* (`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.
*
* 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
* active administrator, so this cannot be used to lock everyone out or to cut off the sign-in in front of everything else.
@@ -95,6 +99,28 @@ export function parseRecoveryLink(raw: unknown): string | null {
}
}
/** A group with who is in it. */
export interface AuthentikGroupDetail extends AuthentikGroup {
/** User ids; null when Authentik did not say, which is not the same as none — and then they are not changed from here. */
members: number[] | null;
}
/** Pure: one group with its members; null when the answer is not a group. */
export function parseGroupDetail(raw: unknown): AuthentikGroupDetail | null {
const g = obj(raw);
const id = str(g.pk);
const name = str(g.name);
if (!id || !name || !UUID.test(id)) return null;
const members = Array.isArray(g.users) ? g.users.filter((u): u is number => typeof u === "number" && Number.isInteger(u) && u > 0) : null;
return { id, name, admin: g.is_superuser === true, members };
}
/** Pure: the groups of a `/core/groups/` page, by name, each with who is in it. */
export function parseGroupDetails(raw: unknown): AuthentikGroupDetail[] {
const list = Array.isArray(raw) ? raw : Array.isArray(obj(raw).results) ? (obj(raw).results as unknown[]) : [];
return list.map(parseGroupDetail).filter((g): g is AuthentikGroupDetail => g !== null).sort((a, b) => a.name.localeCompare(b.name));
}
/** A user as the list shows them. */
export interface AuthentikUser {
pk: number;
@@ -181,6 +207,11 @@ export interface AuthentikUsersAdapter {
updateUser(pk: number, changes: { name?: string; email?: string; groups?: string[] }): Promise<AuthentikUser>;
deleteUser(pk: number): Promise<void>;
listGroups(): Promise<AuthentikGroup[]>;
listGroupDetails(): Promise<AuthentikGroupDetail[]>;
getGroup(id: string): Promise<AuthentikGroupDetail>;
renameGroup(id: string, name: string): Promise<AuthentikGroupDetail>;
addMember(id: string, userPk: number): Promise<void>;
removeMember(id: string, userPk: number): Promise<void>;
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
recoveryLink(pk: number): Promise<string>;
}
@@ -190,7 +221,7 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
const insecure = config.insecure === true;
const headers = { Authorization: `Bearer ${config.writeToken ?? ""}`, Accept: "application/json" };
async function call(method: "GET" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown): Promise<unknown> {
async function call(method: "GET" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown, emptyOk = method === "DELETE"): Promise<unknown> {
let res;
try {
res = await requestJson(`${base}/api/v3${path}`, { method, headers, body, insecure });
@@ -201,8 +232,8 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
if (res.status === 404) throw new AuthentikUserError("Authentik has no such thing there — a user that is gone, or an address that is not Authentik's", "missing");
if (res.status === 400) throw new AuthentikUserError(describeComplaint(res.json) ?? "Authentik did not accept that", "invalid");
if (res.status < 200 || res.status >= 300) throw new AuthentikUserError(`Authentik error: HTTP ${res.status}`, "failed");
// A delete is answered with nothing; everything else with JSON.
if (res.json === null && method !== "DELETE") throw new AuthentikUserError("Authentik answered with something that isn't JSON — is the address its own?", "failed");
// A delete, and putting a user in or out of a group, are answered with nothing; everything else with JSON.
if (res.json === null && !emptyOk) throw new AuthentikUserError("Authentik answered with something that isn't JSON — is the address its own?", "failed");
return res.json;
}
@@ -252,8 +283,38 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
await call("DELETE", `/core/users/${wholeNumber(pk)}/`);
}
const groupId = (id: string) => {
if (!UUID.test(id)) throw new AuthentikUserError("That is not a group id", "invalid");
return id;
};
async function listGroupDetails(): Promise<AuthentikGroupDetail[]> {
return parseGroupDetails(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name&include_users=false`));
}
async function getGroup(id: string): Promise<AuthentikGroupDetail> {
const group = parseGroupDetail(await call("GET", `/core/groups/${groupId(id)}/?include_users=false`));
if (!group) throw new AuthentikUserError("Authentik answered, but not with a group", "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 }));
if (!group) throw new AuthentikUserError("Authentik answered, but not with the group", "failed");
return group;
}
async function addMember(id: string, userPk: number): Promise<void> {
await call("POST", `/core/groups/${groupId(id)}/add_user/`, { pk: wholeNumber(userPk) }, true);
}
async function removeMember(id: string, userPk: number): Promise<void> {
await call("POST", `/core/groups/${groupId(id)}/remove_user/`, { pk: wholeNumber(userPk) }, true);
}
async function listGroups(): Promise<AuthentikGroup[]> {
return parseGroups(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name`));
return parseGroups(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name&include_users=false`));
}
async function createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser> {
@@ -272,5 +333,5 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
return link;
}
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroups, createUser, recoveryLink });
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroupDetails, getGroup, renameGroup, addMember, removeMember, listGroups, createUser, recoveryLink });
}
+114
View File
@@ -7,7 +7,9 @@ import { requireAuth, requireRole } from "../auth/middleware.js";
import { decryptSecret, encryptSecret } from "../crypto.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { applyGroupChange, AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
import { roleForGroupName } from "../auth/groups.js";
import { recordAudit } from "../services/audit.js";
import { getSettings } from "../services/settingsStore.js";
import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -309,3 +311,115 @@ authentikRouter.patch("/:id/users/:pk", requireRole("admin"), asyncHandler(async
sendFailure(res, err);
}
}));
const GROUP_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/**
* The groups with who is in each, for the page that looks after them — and the people to name the members by (not the service accounts), and which one the token is. Every group says
* whether it decides somebody's role in this app (Settings → Sign-in), because changing its name or its members changes that at their next sign-in.
*/
authentikRouter.get("/:id/group-details", requireRole("admin"), asyncHandler(async (req, res) => {
const target = await usersAdapterFor(req.params.id, res);
if (!target) return;
try {
const [groups, people, self, settings] = await Promise.all([target.adapter.listGroupDetails(), target.adapter.listUsers(), target.adapter.whoAmI(), getSettings()]);
res.json({
groups: groups.map((g) => ({ ...g, decidesRole: roleForGroupName(settings.signIn, g.name) })),
people: people.users.map((u) => ({ pk: u.pk, username: u.username, name: u.name, active: u.active })),
more: people.more,
self,
});
} catch (err) {
sendFailure(res, err);
}
}));
const groupEditSchema = z
.object({
name: z.string().trim().min(1, "A group needs a name.").max(200).optional(),
// Members are changed by who goes in and who comes out, never by a whole list: somebody who joined meanwhile is not dropped.
membersAdd: z.array(z.number().int().positive()).max(25).default([]),
membersRemove: z.array(z.number().int().positive()).max(25).default([]),
})
.refine((d) => !d.membersAdd.some((m) => d.membersRemove.includes(m)), { message: "A user can't be both put in and taken out." });
/**
* Renames a group and/or puts users in it and takes them out. Everything is checked first, against Authentik as it is now, and nothing is changed if anything is refused — a service account, the
* account the token belongs to, someone whose groups Authentik did not say (when taking them out of a group that makes administrators), or the last active administrator losing that. Then the
* name, then the users one by one; if Authentik fails part-way the answer says how far it got and the audit log has what was done. Whether the group makes administrators is not changed here.
*/
authentikRouter.patch("/:id/groups/:gid", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = groupEditSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a change.", details: parsed.error.flatten() });
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;
const { adapter } = target;
const { name, membersAdd, membersRemove } = parsed.data;
try {
const group = await adapter.getGroup(gid);
const rename = name !== undefined && name !== group.name ? name : null;
let add: number[] = [];
let remove: number[] = [];
if (membersAdd.length > 0 || membersRemove.length > 0) {
if (group.members === null) return res.status(409).json({ error: "refused", message: "Authentik did not say who is in this group, so its members are not changed from here." });
add = membersAdd.filter((m) => !group.members!.includes(m));
remove = membersRemove.filter((m) => group.members!.includes(m));
}
if (rename === null && add.length === 0 && remove.length === 0) return res.json({ changed: [], added: 0, removed: 0 });
// Look at everyone first: nothing is changed unless all of it may be.
const people = new Map<number, AuthentikUser>();
for (const pk of [...add, ...remove]) {
const user = await adapter.getUser(pk);
people.set(pk, user);
let refusal: string | null;
if (remove.includes(pk) && group.admin && user.groups === null && !isServiceAccount(user)) refusal = "Authentik did not say which groups they are in, so they are not taken out of a group that makes administrators from here.";
else refusal = await judge(adapter, user, "edit", remove.includes(pk) && group.admin && user.groups ? user.groups.filter((g) => g !== gid) : undefined);
if (refusal) return res.status(409).json({ error: "refused", message: `${user.username}: ${refusal}` });
}
const total = (rename === null ? 0 : 1) + add.length + remove.length;
let done = 0;
const doneAdded: string[] = [];
const doneRemoved: string[] = [];
let failure: unknown = null;
try {
if (rename !== null) {
await adapter.renameGroup(gid, rename);
done += 1;
}
for (const pk of add) {
await adapter.addMember(gid, pk);
done += 1;
doneAdded.push(people.get(pk)!.username);
}
for (const pk of remove) {
await adapter.removeMember(gid, pk);
done += 1;
doneRemoved.push(people.get(pk)!.username);
}
} catch (err) {
failure = err;
}
if (done > 0) {
await recordAudit({
actor: req.currentUser!,
category: "integration",
action: "update_authentik_group",
targetType: "authentik_group",
targetId: gid,
detail: { integrationId: target.id, integration: target.name, group: group.name, ...(rename !== null && done > 0 ? { renamedTo: rename } : {}), added: doneAdded, removed: doneRemoved },
});
}
if (failure !== null) {
const kind = failure instanceof AuthentikUserError ? failure.kind : "failed";
const message = failure instanceof Error ? failure.message : String(failure);
return sendFailure(res, new AuthentikUserError(`${message} — ${done} of ${total} changes had been made`, kind));
}
res.json({ changed: [...(rename !== null ? ["name"] : []), ...(add.length + remove.length > 0 ? ["members"] : [])], added: add.length, removed: remove.length });
} catch (err) {
sendFailure(res, err);
}
}));