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);
|
||||
}
|
||||
}));
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Looking after Authentik users: reading the list, switching a user off and on, deleting one — and what is refused (service accounts, the account the token belongs to, the last active
|
||||
* Looking after Authentik users: reading the list, switching a user off and on, editing one, deleting one — and what is refused (service accounts, the account the token belongs to, the last active
|
||||
* administrator, a user name that does not match), who may, and what is written in the audit log.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
@@ -36,12 +36,16 @@ interface FakeUser {
|
||||
is_superuser: boolean;
|
||||
last_login: string | null;
|
||||
type: string;
|
||||
groups?: string[];
|
||||
}
|
||||
const person = (pk: number, username: string, extra: Partial<FakeUser> = {}): FakeUser => ({ pk, username, name: username.toUpperCase(), email: `${username}@example.com`, is_active: true, is_superuser: false, last_login: null, type: "internal", ...extra });
|
||||
const G_ADMIN = "22222222-2222-4222-8222-222222222222";
|
||||
const G_FAMILY = "11111111-1111-4111-8111-111111111111";
|
||||
const G_OTHER = "44444444-4444-4444-8444-444444444444";
|
||||
const person = (pk: number, username: string, extra: Partial<FakeUser> = {}): FakeUser => ({ pk, username, name: username.toUpperCase(), email: `${username}@example.com`, is_active: true, is_superuser: false, last_login: null, type: "internal", groups: [], ...extra });
|
||||
const fresh = (): FakeUser[] => [
|
||||
person(1, "akadmin", { is_superuser: true, last_login: "2026-10-30T08:00:00Z" }),
|
||||
person(2, "bob", { is_superuser: true }),
|
||||
person(3, "carol"),
|
||||
person(1, "akadmin", { is_superuser: true, last_login: "2026-10-30T08:00:00Z", groups: [G_ADMIN] }),
|
||||
person(2, "bob", { is_superuser: true, groups: [G_ADMIN] }),
|
||||
person(3, "carol", { groups: [G_FAMILY] }),
|
||||
person(4, "dave", { is_active: false }),
|
||||
person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }),
|
||||
];
|
||||
@@ -66,6 +70,18 @@ describe("what Authentik's answers are read as", () => {
|
||||
assert.equal(usersApi.isServiceAccount({ type: "external" }), false);
|
||||
});
|
||||
|
||||
test("a user's groups are the ids Authentik gives; none given is not the same as none", () => {
|
||||
assert.deepEqual(usersApi.parseUser({ pk: 3, username: "x", groups: [G_FAMILY, "nope", 7] })!.groups, [G_FAMILY]);
|
||||
assert.deepEqual(usersApi.parseUser({ pk: 3, username: "x", groups: [] })!.groups, []);
|
||||
assert.equal(usersApi.parseUser({ pk: 3, username: "x" })!.groups, null);
|
||||
});
|
||||
|
||||
test("groups are changed from the ones there are now: what goes out goes, what comes in comes, once, and what neither mentions stays", () => {
|
||||
assert.deepEqual(usersApi.applyGroupChange([G_FAMILY, G_OTHER], [G_ADMIN], [G_FAMILY]), [G_OTHER, G_ADMIN]);
|
||||
assert.deepEqual(usersApi.applyGroupChange([G_FAMILY], [G_FAMILY], []), [G_FAMILY]);
|
||||
assert.deepEqual(usersApi.applyGroupChange([G_FAMILY], [], [G_OTHER]), [G_FAMILY]);
|
||||
});
|
||||
|
||||
test("who the token is comes out of /users/me/", () => {
|
||||
assert.equal(usersApi.parseMe({ user: { pk: 9 } }), 9);
|
||||
assert.equal(usersApi.parseMe({ user: { pk: "9" } }), null);
|
||||
@@ -84,6 +100,12 @@ describe("what Authentik's answers are read as", () => {
|
||||
assert.equal(usersApi.refusalFor({ ...bob, active: false }, "delete", 1, [1]), null, "one that is already off is not the one holding the door");
|
||||
assert.equal(usersApi.refusalFor(carol, "delete", 1, [1]), null);
|
||||
assert.equal(usersApi.refusalFor(dave, "disable", null, []), null);
|
||||
// Editing: the token's own account and a service account never; the last administrator only when the edit would take them out of being one.
|
||||
assert.match(usersApi.refusalFor(akadmin, "edit", 1, [1, 2]) ?? "", /token/);
|
||||
assert.match(usersApi.refusalFor(outpost, "edit", 1, [1, 2]) ?? "", /service account/);
|
||||
assert.match(usersApi.refusalFor(bob, "edit", 1, [2], true) ?? "", /only active administrator/);
|
||||
assert.equal(usersApi.refusalFor(bob, "edit", 1, [2], false), null);
|
||||
assert.equal(usersApi.refusalFor(bob, "edit", 1, [1, 2], true), null);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -118,6 +140,7 @@ before(async () => {
|
||||
res.end(JSON.stringify(json));
|
||||
};
|
||||
const url = new URL(path, "http://x");
|
||||
if (req.method === "GET" && url.pathname === "/api/v3/core/groups/") return send(200, { results: [{ pk: G_ADMIN, name: "admins", is_superuser: true }, { pk: G_FAMILY, name: "Family", is_superuser: false }, { pk: G_OTHER, name: "Other", is_superuser: false }] });
|
||||
if (req.method === "GET" && url.pathname === "/api/v3/core/users/me/") return send(200, { user: table.find((u) => u.pk === meId) ?? person(meId, "me") });
|
||||
if (req.method === "GET" && url.pathname === "/api/v3/core/users/") {
|
||||
let list = table;
|
||||
@@ -134,7 +157,9 @@ before(async () => {
|
||||
if (req.method === "GET") return send(200, user);
|
||||
if (req.method === "PATCH") {
|
||||
if (patchStatus !== 200) return send(patchStatus, { detail: "You do not have permission to perform this action." });
|
||||
user.is_active = JSON.parse(body).is_active;
|
||||
const b = JSON.parse(body) as Partial<FakeUser>;
|
||||
Object.assign(user, b);
|
||||
if (b.groups) user.is_superuser = b.groups.includes(G_ADMIN);
|
||||
return send(200, user);
|
||||
}
|
||||
if (req.method === "DELETE") {
|
||||
@@ -214,6 +239,7 @@ describe("the routes", () => {
|
||||
const list = (sub = "admin", q = "") => fetch(`${base}/${id}/users${q}`, { headers: as(sub) });
|
||||
const active = (pk: number, on: boolean, sub = "admin", integration = id) => fetch(`${base}/${integration}/users/${pk}/active`, { method: "POST", headers: as(sub), body: JSON.stringify({ active: on }) });
|
||||
const del = (pk: number, username: unknown, sub = "admin") => fetch(`${base}/${id}/users/${pk}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ username }) });
|
||||
const change = (pk: number, body: unknown, sub = "admin") => fetch(`${base}/${id}/users/${pk}`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) });
|
||||
const writes = () => seen.filter((s) => s.method !== "GET");
|
||||
const reset = () => {
|
||||
table = fresh();
|
||||
@@ -347,6 +373,104 @@ describe("the routes", () => {
|
||||
assert.equal((await audit("disable_authentik_user")).length, before, "nothing was done, so nothing more is written down");
|
||||
});
|
||||
|
||||
test("editing: only what differs is sent, never the user name; the audit log names the fields, not what they were changed to", async () => {
|
||||
reset();
|
||||
const res = await change(3, { name: "Carol C", email: "carol@new.example" });
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(((await res.json()) as { changed: string[] }).changed, ["name", "email"]);
|
||||
assert.deepEqual(writes().map((s) => [s.method, s.path, s.body]), [["PATCH", "/api/v3/core/users/3/", JSON.stringify({ name: "Carol C", email: "carol@new.example" })]]);
|
||||
assert.deepEqual([table.find((u) => u.pk === 3)!.name, table.find((u) => u.pk === 3)!.username], ["Carol C", "carol"]);
|
||||
const entry = (await audit("update_authentik_user")).at(-1)!;
|
||||
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "3"]);
|
||||
assert.match(entry.detail ?? "", /carol/);
|
||||
assert.match(entry.detail ?? "", /"changed":\["name","email"\]/);
|
||||
assert.equal(/new\.example|Carol C/.test(entry.detail ?? ""), false);
|
||||
// The same again changes nothing, so nothing is sent and nothing is written down.
|
||||
const before = (await audit("update_authentik_user")).length;
|
||||
seen.length = 0;
|
||||
const again = await change(3, { name: "Carol C", email: "carol@new.example", groupsAdd: [], groupsRemove: [] });
|
||||
assert.deepEqual(((await again.json()) as { changed: string[] }).changed, []);
|
||||
assert.deepEqual(writes(), []);
|
||||
assert.equal((await audit("update_authentik_user")).length, before);
|
||||
// An empty email clears it.
|
||||
assert.equal((await change(3, { email: "" })).status, 200);
|
||||
assert.equal(writes().at(-1)!.body, JSON.stringify({ email: "" }));
|
||||
});
|
||||
|
||||
test("groups are changed by what goes in and out, on top of the groups the user has now", async () => {
|
||||
reset();
|
||||
// Somebody put carol in another group after the page was read: that stays.
|
||||
table.find((u) => u.pk === 3)!.groups = [G_FAMILY, G_OTHER];
|
||||
const res = await change(3, { groupsAdd: [G_ADMIN], groupsRemove: [G_FAMILY] });
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(JSON.parse(writes()[0].body), { groups: [G_OTHER, G_ADMIN] });
|
||||
seen.length = 0;
|
||||
const same = await change(3, { groupsAdd: [G_OTHER], groupsRemove: [G_FAMILY] });
|
||||
assert.deepEqual(((await same.json()) as { changed: string[] }).changed, [], "putting in what is there and taking out what is not changes nothing");
|
||||
assert.deepEqual(writes(), []);
|
||||
});
|
||||
|
||||
test("what is wrong with the change is said before Authentik is asked", async () => {
|
||||
reset();
|
||||
for (const bad of [{ name: "" }, { email: "not-an-email" }, { groupsAdd: ["not-a-uuid"] }, { groupsAdd: [G_FAMILY], groupsRemove: [G_FAMILY] }, { groupsRemove: "x" }]) {
|
||||
const res = await change(3, bad);
|
||||
assert.equal(res.status, 400, JSON.stringify(bad));
|
||||
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
|
||||
}
|
||||
assert.equal((await fetch(`${base}/${id}/users/1e3`, { method: "PATCH", headers: as("admin"), body: JSON.stringify({ name: "x" }) })).status, 400);
|
||||
assert.deepEqual(seen, []);
|
||||
});
|
||||
|
||||
test("editing is refused for a service account, for the token's own account, and for the last administrator when it would take them out of being one", async () => {
|
||||
reset();
|
||||
const refused = async (res: Response, pattern: RegExp) => {
|
||||
assert.equal(res.status, 409);
|
||||
assert.match(((await res.json()) as { message: string }).message, pattern);
|
||||
};
|
||||
await refused(await change(5, { name: "x" }), /service account/);
|
||||
await refused(await change(1, { name: "x" }), /token/);
|
||||
assert.deepEqual(writes(), []);
|
||||
// The token is carol's account now; bob is off, so akadmin is the only active administrator.
|
||||
meId = 3;
|
||||
table.find((u) => u.pk === 2)!.is_active = false;
|
||||
await refused(await change(1, { groupsRemove: [G_ADMIN] }), /only active administrator/);
|
||||
assert.deepEqual(writes(), []);
|
||||
assert.equal((await change(1, { name: "Root" })).status, 200, "a name is no danger");
|
||||
assert.equal((await change(1, { groupsAdd: [G_FAMILY] })).status, 200, "nor is another group");
|
||||
assert.equal((await change(1, { groupsRemove: [G_FAMILY] })).status, 200);
|
||||
// With another administrator on, they may be taken out of the group.
|
||||
table.find((u) => u.pk === 2)!.is_active = true;
|
||||
assert.equal((await change(1, { groupsRemove: [G_ADMIN] })).status, 200);
|
||||
assert.deepEqual(table.find((u) => u.pk === 1)!.groups, []);
|
||||
});
|
||||
|
||||
test("a user whose groups Authentik did not say can be renamed but not moved between groups", async () => {
|
||||
reset();
|
||||
delete table.find((u) => u.pk === 3)!.groups;
|
||||
const res = await change(3, { groupsAdd: [G_FAMILY] });
|
||||
assert.equal(res.status, 409);
|
||||
assert.match(((await res.json()) as { message: string }).message, /did not say which groups/);
|
||||
assert.deepEqual(writes(), []);
|
||||
assert.equal((await change(3, { name: "Only Name" })).status, 200);
|
||||
});
|
||||
|
||||
test("only an administrator edits; a user that is gone is not found; a token that may not is a bad gateway", async () => {
|
||||
reset();
|
||||
for (const sub of ["viewer", "operator"]) assert.equal((await change(3, { name: "x" }, sub)).status, 403, sub);
|
||||
assert.deepEqual(seen, []);
|
||||
assert.equal((await change(99, { name: "x" })).status, 404);
|
||||
patchStatus = 403;
|
||||
const res = await change(3, { name: "Someone Else" });
|
||||
assert.equal(res.status, 502);
|
||||
assert.match(((await res.json()) as { message: string }).message, /did not accept the token/);
|
||||
});
|
||||
|
||||
test("the list carries each person's groups", async () => {
|
||||
reset();
|
||||
const body = (await (await list()).json()) as { users: { username: string; groups: string[] | null }[] };
|
||||
assert.deepEqual(body.users.map((u) => [u.username, u.groups]), [["akadmin", [G_ADMIN]], ["bob", [G_ADMIN]], ["carol", [G_FAMILY]], ["dave", []]]);
|
||||
});
|
||||
|
||||
test("an Authentik with no token for managing users is not asked anything", async () => {
|
||||
reset();
|
||||
const res = await fetch(`${base}/${readOnly}/users`, { headers: as("admin") });
|
||||
|
||||
Reference in new issue
Block a user