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
@@ -5,8 +5,8 @@
|
||||
* 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 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`) 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
|
||||
* 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.
|
||||
*
|
||||
* Endpoints and field names are from Authentik's published API and have not been checked against a live server here; every field is read defensively. The link is built by Authentik from
|
||||
@@ -107,6 +107,8 @@ export interface AuthentikUser {
|
||||
lastLogin: string | null;
|
||||
/** internal, external, service_account, internal_service_account. */
|
||||
type: string;
|
||||
/** Group ids; null when Authentik did not say, which is not the same as none — and then they are not changed from here. */
|
||||
groups: string[] | null;
|
||||
}
|
||||
|
||||
/** What an outpost or an integration signs in with: not a person, and not this app's to switch off or delete. */
|
||||
@@ -118,7 +120,7 @@ export function parseUser(raw: unknown): AuthentikUser | null {
|
||||
const pk = typeof u.pk === "number" ? u.pk : Number.NaN;
|
||||
const username = str(u.username);
|
||||
if (!Number.isInteger(pk) || pk <= 0 || !username) return null;
|
||||
return { pk, username, name: str(u.name) ?? username, email: str(u.email), active: u.is_active !== false, admin: u.is_superuser === true, lastLogin: iso(u.last_login), type: str(u.type) ?? "internal" };
|
||||
return { pk, username, name: str(u.name) ?? username, email: str(u.email), active: u.is_active !== false, admin: u.is_superuser === true, lastLogin: iso(u.last_login), type: str(u.type) ?? "internal", groups: Array.isArray(u.groups) ? u.groups.filter((g): g is string => typeof g === "string" && UUID.test(g)) : null };
|
||||
}
|
||||
|
||||
/** Pure: the people of a `/core/users/` page (service accounts left out), and whether there are more pages than this one. */
|
||||
@@ -134,15 +136,25 @@ export function parseMe(raw: unknown): number | null {
|
||||
return typeof pk === "number" && Number.isInteger(pk) && pk > 0 ? pk : null;
|
||||
}
|
||||
|
||||
/** Pure: the groups a user is in after taking some out and putting some in, from the groups they are in now — so a membership somebody else gave them meanwhile is kept. */
|
||||
export function applyGroupChange(current: string[], add: string[], remove: string[]): string[] {
|
||||
const out = current.filter((g) => !remove.includes(g));
|
||||
for (const g of add) if (!out.includes(g)) out.push(g);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure: why this must not be done to this user, or null when it may. A service account is never touched. Switching on is always fine. Switching off or deleting is not for the account the token
|
||||
* belongs to (the app would cut off its own hand) nor for the only active administrator left (nobody could sign in to put it right).
|
||||
* Pure: why this must not be done to this user, or null when it may. A service account is never touched. Switching on is always fine. Switching off, deleting or changing is not for the account the
|
||||
* token belongs to (the app would cut off its own hand) nor, when it would leave Authentik without one (`losesAdmin`: an edit that takes them out of every group that makes them an administrator),
|
||||
* for the only active administrator left (nobody could sign in to put it right).
|
||||
*/
|
||||
export function refusalFor(user: AuthentikUser, action: "disable" | "enable" | "delete", self: number | null, activeAdmins: number[]): string | null {
|
||||
export function refusalFor(user: AuthentikUser, action: "disable" | "enable" | "delete" | "edit", self: number | null, activeAdmins: number[], losesAdmin = false): string | null {
|
||||
if (isServiceAccount(user)) return "That is a service account — an outpost or an integration signs in with it. It is looked after in Authentik.";
|
||||
if (action === "enable") return null;
|
||||
if (self !== null && user.pk === self) return "That is the account the token for managing users belongs to; switching it off or deleting it would cut off this very access. Do it in Authentik if you mean to.";
|
||||
if (user.admin && user.active && activeAdmins.includes(user.pk) && activeAdmins.length <= 1) return "That is the only active administrator Authentik has; with it gone nobody could sign in to put things right. Do it in Authentik if you mean to.";
|
||||
if (self !== null && user.pk === self) return "That is the account the token for managing users belongs to; switching it off, deleting it or changing it from here could cut off this very access. Do it in Authentik if you mean to.";
|
||||
const onlyAdmin = user.admin && user.active && activeAdmins.includes(user.pk) && activeAdmins.length <= 1;
|
||||
if (onlyAdmin && (action === "disable" || action === "delete")) return "That is the only active administrator Authentik has; with it gone nobody could sign in to put things right. Do it in Authentik if you mean to.";
|
||||
if (onlyAdmin && action === "edit" && losesAdmin) return "That is the only active administrator Authentik has; taking them out of the groups that make them one would leave nobody able to sign in to put things right. Do it in Authentik if you mean to.";
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -166,6 +178,7 @@ export interface AuthentikUsersAdapter {
|
||||
/** The pks of the active administrators (people), enough of them to tell whether there is more than one. */
|
||||
activeAdmins(): Promise<number[]>;
|
||||
setActive(pk: number, active: boolean): Promise<AuthentikUser>;
|
||||
updateUser(pk: number, changes: { name?: string; email?: string; groups?: string[] }): Promise<AuthentikUser>;
|
||||
deleteUser(pk: number): Promise<void>;
|
||||
listGroups(): Promise<AuthentikGroup[]>;
|
||||
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
|
||||
@@ -224,6 +237,17 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
||||
return user;
|
||||
}
|
||||
|
||||
async function updateUser(pk: number, changes: { name?: string; email?: string; groups?: string[] }): Promise<AuthentikUser> {
|
||||
// Only what is to change, and never the user name: a PATCH leaves out everything it does not mention.
|
||||
const body: Record<string, unknown> = {};
|
||||
if (changes.name !== undefined) body.name = changes.name;
|
||||
if (changes.email !== undefined) body.email = changes.email;
|
||||
if (changes.groups !== undefined) body.groups = changes.groups.filter((g) => UUID.test(g));
|
||||
const user = parseUser(await call("PATCH", `/core/users/${wholeNumber(pk)}/`, body));
|
||||
if (!user) throw new AuthentikUserError("Authentik answered, but not with the user", "failed");
|
||||
return user;
|
||||
}
|
||||
|
||||
async function deleteUser(pk: number): Promise<void> {
|
||||
await call("DELETE", `/core/users/${wholeNumber(pk)}/`);
|
||||
}
|
||||
@@ -248,5 +272,5 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
|
||||
return link;
|
||||
}
|
||||
|
||||
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, deleteUser, listGroups, createUser, recoveryLink });
|
||||
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, updateUser, deleteUser, listGroups, createUser, recoveryLink });
|
||||
}
|
||||
@@ -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