Edit Authentik users: name, email and groups
Each person in Apps → Authentik → Users gets an Edit form. The user name is shown but not changeable. Authentik is sent only what differs, and groups as what goes in and what comes out on top of the user's current groups, so a membership added meanwhile is kept; a user whose groups Authentik doesn't report can't have them changed. The server refuses service accounts, the token's own account, and an edit that would leave no active administrator. Audited by field name, never by value. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0cd11268ee
commit
3618cb3ae8
9 files changed
+370
-30
No files matched your search
@@ -6,7 +6,7 @@ import { authentikState, integrationCredentials, integrations } from "../db/sche
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { decryptSecret, encryptSecret } from "../crypto.js";
|
||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||
import { AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
|
||||
import { applyGroupChange, AuthentikUserError, createAuthentikUsersAdapter, isServiceAccount, refusalFor, type AuthentikUser, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
@@ -61,13 +61,25 @@ function sendFailure(res: Response, err: unknown) {
|
||||
|
||||
const pkOf = (raw: string) => (/^\d{1,12}$/.test(raw) ? Number(raw) : Number.NaN);
|
||||
|
||||
/** The user as Authentik has them now, and whether this may be done to them — asked of Authentik itself, not taken from the page, which may be minutes old. */
|
||||
async function guard(adapter: AuthentikUsersAdapter, pk: number, action: "disable" | "enable" | "delete"): Promise<{ user: AuthentikUser; refusal: string | null }> {
|
||||
const user = await adapter.getUser(pk);
|
||||
if (action === "enable" || isServiceAccount(user)) return { user, refusal: refusalFor(user, action, null, []) };
|
||||
type UserAction = "disable" | "enable" | "delete" | "edit";
|
||||
|
||||
/** Whether this may be done to this user, asked of Authentik itself — not taken from the page, which may be minutes old. For an edit, `newGroups` is what their groups would be. */
|
||||
async function judge(adapter: AuthentikUsersAdapter, user: AuthentikUser, action: UserAction, newGroups?: string[]): Promise<string | null> {
|
||||
if (action === "enable" || isServiceAccount(user)) return refusalFor(user, action, null, []);
|
||||
const self = await adapter.whoAmI();
|
||||
const admins = user.admin && user.active ? await adapter.activeAdmins() : [];
|
||||
return { user, refusal: refusalFor(user, action, self, admins) };
|
||||
let losesAdmin = false;
|
||||
if (action === "edit" && newGroups && user.admin && user.active) {
|
||||
const adminGroups = new Set((await adapter.listGroups()).filter((g) => g.admin).map((g) => g.id));
|
||||
losesAdmin = !newGroups.some((g) => adminGroups.has(g));
|
||||
}
|
||||
return refusalFor(user, action, self, admins, losesAdmin);
|
||||
}
|
||||
|
||||
/** The user as Authentik has them now, and whether this may be done to them. */
|
||||
async function guard(adapter: AuthentikUsersAdapter, pk: number, action: Exclude<UserAction, "edit">): Promise<{ user: AuthentikUser; refusal: string | null }> {
|
||||
const user = await adapter.getUser(pk);
|
||||
return { user, refusal: await judge(adapter, user, action) };
|
||||
}
|
||||
|
||||
const newUserSchema = z.object({
|
||||
@@ -248,3 +260,52 @@ authentikRouter.delete("/:id/users/:pk", requireRole("admin"), asyncHandler(asyn
|
||||
sendFailure(res, err);
|
||||
}
|
||||
}));
|
||||
|
||||
const editSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1, "A name is needed.").max(200).optional(),
|
||||
// An empty email clears it.
|
||||
email: z.union([z.literal(""), z.string().trim().email("That is not an email address.").max(254)]).optional(),
|
||||
// Groups are changed by what to put in and what to take out, never by a whole list: a membership somebody gave them meanwhile is kept.
|
||||
groupsAdd: z.array(z.string().uuid()).max(50).default([]),
|
||||
groupsRemove: z.array(z.string().uuid()).max(50).default([]),
|
||||
})
|
||||
.refine((d) => !d.groupsAdd.some((g) => d.groupsRemove.includes(g)), { message: "A group can't be both put in and taken out." });
|
||||
|
||||
/**
|
||||
* Changes a user's name, email and groups — what they are called and where they belong; not the user name, which is how a person is known elsewhere. Authentik is sent only what differs
|
||||
* from the user as it has them now (nothing at all when nothing does), and the groups as that user's current ones with the changes made.
|
||||
*/
|
||||
authentikRouter.patch("/:id/users/:pk", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const parsed = editSchema.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 pk = pkOf(req.params.pk);
|
||||
if (!Number.isInteger(pk) || pk <= 0) return res.status(400).json({ error: "invalid_user" });
|
||||
const target = await usersAdapterFor(req.params.id, res);
|
||||
if (!target) return;
|
||||
const { name, email, groupsAdd, groupsRemove } = parsed.data;
|
||||
try {
|
||||
const user = await target.adapter.getUser(pk);
|
||||
const changes: { name?: string; email?: string; groups?: string[] } = {};
|
||||
if (name !== undefined && name !== user.name) changes.name = name;
|
||||
if (email !== undefined && email !== (user.email ?? "")) changes.email = email;
|
||||
let newGroups: string[] | undefined;
|
||||
if (groupsAdd.length > 0 || groupsRemove.length > 0) {
|
||||
if (user.groups === null) return res.status(409).json({ error: "refused", message: "Authentik did not say which groups this user is in, so they are not changed from here." });
|
||||
const next = applyGroupChange(user.groups, groupsAdd, groupsRemove);
|
||||
if (next.length !== user.groups.length || next.some((g) => !user.groups!.includes(g))) {
|
||||
changes.groups = next;
|
||||
newGroups = next;
|
||||
}
|
||||
}
|
||||
const changed = Object.keys(changes);
|
||||
if (changed.length === 0) return res.json({ user, changed });
|
||||
const refusal = await judge(target.adapter, user, "edit", newGroups);
|
||||
if (refusal) return res.status(409).json({ error: "refused", message: refusal });
|
||||
const updated = await target.adapter.updateUser(pk, changes);
|
||||
await recordAudit({ actor: req.currentUser!, category: "integration", action: "update_authentik_user", targetType: "authentik_user", targetId: pk, detail: { integrationId: target.id, integration: target.name, username: user.username, changed } });
|
||||
res.json({ user: updated, changed });
|
||||
} catch (err) {
|
||||
sendFailure(res, err);
|
||||
}
|
||||
}));
|
||||
Reference in new issue
Block a user