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:
1 parent
3618cb3ae8
commit
6c5a5f0bd6
10 files changed
+794
-9
No files matched your search
@@ -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);
|
||||
}
|
||||
}));
|
||||
Reference in new issue
Block a user