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);
}
}));
+389
View File
@@ -0,0 +1,389 @@
/**
* Looking after Authentik groups: reading them with who is in them, renaming one, putting users in and taking them out — and what is refused (service accounts, the account the token belongs
* to, the last active administrator losing that, a user whose groups Authentik did not say), that nothing is changed unless all of it may be, how far a failure got, who may, what is in the
* audit log, and which groups decide roles in this app.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer as createHttpServer, type Server } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
const dir = mkdtempSync(join(tmpdir(), "hm-authentik-groups-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, integrations, integrationCredentials, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { encryptSecret } = await import("../src/crypto.js");
const usersApi = await import("../src/integrations/authentik/users.js");
const { roleForGroupName } = await import("../src/auth/groups.js");
const { updateSettings } = await import("../src/services/settingsStore.js");
const { authentikRouter } = await import("../src/routes/authentik.js");
await runMigrations();
const G_ADMIN = "22222222-2222-4222-8222-222222222222";
const G_FAMILY = "11111111-1111-4111-8111-111111111111";
const G_OTHER = "44444444-4444-4444-8444-444444444444";
interface FakeGroup {
pk: string;
name: string;
is_superuser: boolean;
users: number[];
}
interface FakeUser {
pk: number;
username: string;
name: string;
email: string;
is_active: boolean;
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", groups: [], ...extra });
describe("what Authentik's answers are read as", () => {
test("a group with who is in it: the ids of the users; none given is not the same as none", () => {
assert.deepEqual(usersApi.parseGroupDetail({ pk: G_FAMILY, name: "Family", is_superuser: false, users: [3, 4, "x", 0, 1.5] }), { id: G_FAMILY, name: "Family", admin: false, members: [3, 4] });
assert.deepEqual(usersApi.parseGroupDetail({ pk: G_ADMIN, name: "admins", is_superuser: true, users: [] }), { id: G_ADMIN, name: "admins", admin: true, members: [] });
assert.equal(usersApi.parseGroupDetail({ pk: G_FAMILY, name: "Family" })!.members, null);
assert.equal(usersApi.parseGroupDetail({ pk: "nope", name: "x" }), null);
assert.equal(usersApi.parseGroupDetail({ pk: G_FAMILY, name: " " }), null);
});
test("the list is by name", () => {
const list = usersApi.parseGroupDetails({ results: [{ pk: G_OTHER, name: "other", users: [] }, { pk: G_FAMILY, name: "Family", users: [] }, { pk: "x", name: "junk" }] });
assert.deepEqual(list.map((g) => g.name), ["Family", "other"]);
assert.deepEqual(usersApi.parseGroupDetails("nonsense"), []);
});
test("a group decides a role here when roles follow the groups and its name is one of the named ones — compared the way sign-in compares", () => {
const rules = { roleFromGroups: true, adminGroups: ["Homelab-Admins"], operatorGroups: [" ops "] };
assert.equal(roleForGroupName(rules, "homelab-admins"), "admin");
assert.equal(roleForGroupName(rules, "OPS"), "operator");
assert.equal(roleForGroupName(rules, "Family"), null);
assert.equal(roleForGroupName({ ...rules, roleFromGroups: false }, "homelab-admins"), null);
});
});
/** An Authentik with groups and users that remembers what it was asked. */
interface Seen {
method: string;
path: string;
auth: string;
body: string;
}
const seen: Seen[] = [];
const freshGroups = (): FakeGroup[] => [
{ pk: G_ADMIN, name: "admins", is_superuser: true, users: [1, 2] },
{ pk: G_FAMILY, name: "Family", is_superuser: false, users: [3] },
{ pk: G_OTHER, name: "Other", is_superuser: false, users: [] },
];
const freshUsers = (): FakeUser[] => [
person(1, "akadmin", { is_superuser: true, groups: [G_ADMIN] }),
person(2, "bob", { is_superuser: true, groups: [G_ADMIN] }),
person(3, "carol", { groups: [G_FAMILY] }),
person(4, "dave"),
person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }),
];
let groupTable = freshGroups();
let userTable = freshUsers();
let meId = 1;
/** A user id whose put-in or take-out Authentik answers with an error. */
let failMemberPk = 0;
let fake: Server;
let fakeUrl = "";
before(async () => {
fake = createHttpServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
const path = req.url ?? "";
seen.push({ method: req.method ?? "", path, auth: String(req.headers.authorization ?? ""), body });
const send = (status: number, json?: unknown) => {
if (json === undefined) {
res.writeHead(status);
return res.end();
}
res.writeHead(status, { "content-type": "application/json" });
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: groupTable });
const grp = /^\/api\/v3\/core\/groups\/([0-9a-f-]{36})\/(add_user\/|remove_user\/)?$/.exec(url.pathname);
if (grp) {
const group = groupTable.find((g) => g.pk === grp[1]);
if (!group) return send(404, { detail: "Not found." });
if (!grp[2] && req.method === "GET") return send(200, group);
if (!grp[2] && req.method === "PATCH") {
Object.assign(group, JSON.parse(body));
return send(200, group);
}
if (grp[2] && req.method === "POST") {
const pk = (JSON.parse(body) as { pk: number }).pk;
if (pk === failMemberPk) return send(500, { detail: "boom" });
const user = userTable.find((u) => u.pk === pk);
if (!user) return send(404, { detail: "Not found." });
if (grp[2] === "add_user/") {
if (!group.users.includes(pk)) group.users.push(pk);
if (user.groups && !user.groups.includes(group.pk)) user.groups.push(group.pk);
} else {
group.users = group.users.filter((u) => u !== pk);
if (user.groups) user.groups = user.groups.filter((g) => g !== group.pk);
}
user.is_superuser = (user.groups ?? []).some((g) => groupTable.find((x) => x.pk === g)?.is_superuser);
return send(204);
}
}
if (req.method === "GET" && url.pathname === "/api/v3/core/users/me/") return send(200, { user: userTable.find((u) => u.pk === meId) });
if (req.method === "GET" && url.pathname === "/api/v3/core/users/") {
let list = userTable;
if (url.searchParams.get("is_superuser") === "true") list = list.filter((u) => u.is_superuser);
if (url.searchParams.get("is_active") === "true") list = list.filter((u) => u.is_active);
return send(200, { pagination: { total_pages: 1 }, results: list });
}
const one = /^\/api\/v3\/core\/users\/(\d+)\/$/.exec(url.pathname);
if (one && req.method === "GET") {
const user = userTable.find((u) => u.pk === Number(one[1]));
return user ? send(200, user) : send(404, { detail: "Not found." });
}
return send(200, { results: [] });
});
});
await new Promise<void>((resolve) => fake.listen(0, "127.0.0.1", resolve));
fakeUrl = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`;
});
after(() => {
fake.close();
});
const reset = () => {
groupTable = freshGroups();
userTable = freshUsers();
meId = 1;
failMemberPk = 0;
seen.length = 0;
};
describe("the calls", () => {
const adapter = () => usersApi.createAuthentikUsersAdapter({ url: fakeUrl, writeToken: "write-tok" });
test("the groups are listed with their members, without the heavy user objects", async () => {
reset();
const list = await adapter().listGroupDetails();
assert.deepEqual(list.map((g) => [g.name, g.admin, g.members]), [["admins", true, [1, 2]], ["Family", false, [3]], ["Other", false, []]]);
assert.match(seen[0].path, /include_users=false/);
assert.equal(seen[0].auth, "Bearer write-tok");
});
test("renaming is a PATCH of the name and nothing else; a member goes in or out with a POST of that one user", async () => {
reset();
const renamed = await adapter().renameGroup(G_FAMILY, "Household");
assert.equal(renamed.name, "Household");
assert.deepEqual([seen[0].method, seen[0].path, seen[0].body], ["PATCH", `/api/v3/core/groups/${G_FAMILY}/`, JSON.stringify({ name: "Household" })]);
await adapter().addMember(G_FAMILY, 4);
await adapter().removeMember(G_FAMILY, 3);
assert.deepEqual(seen.slice(1).map((s) => [s.method, s.path, s.body]), [["POST", `/api/v3/core/groups/${G_FAMILY}/add_user/`, '{"pk":4}'], ["POST", `/api/v3/core/groups/${G_FAMILY}/remove_user/`, '{"pk":3}']]);
assert.deepEqual(groupTable.find((g) => g.pk === G_FAMILY)!.users, [4]);
});
test("a group id that is not an id and a user id that is not a whole number are never put in the address", async () => {
reset();
for (const bad of ["../../x", "", "not-a-uuid", `${G_FAMILY}/../x`]) {
await assert.rejects(() => adapter().getGroup(bad), /not a group id/);
await assert.rejects(() => adapter().renameGroup(bad, "x"), /not a group id/);
await assert.rejects(() => adapter().addMember(bad, 1), /not a group id/);
}
for (const pk of [0, -2, 1.5, Number.NaN]) await assert.rejects(() => adapter().removeMember(G_FAMILY, pk), /not a user id/);
assert.deepEqual(seen, []);
});
});
describe("the routes", () => {
let app: Server;
let base = "";
let id = 0;
let readOnly = 0;
const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub });
const details = (sub = "admin") => fetch(`${base}/${id}/group-details`, { headers: as(sub) });
const change = (gid: string, body: unknown, sub = "admin") => fetch(`${base}/${id}/groups/${gid}`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) });
const writes = () => seen.filter((s) => s.method !== "GET");
const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action);
const refused = async (res: Response, pattern: RegExp) => {
assert.equal(res.status, 409);
assert.match(((await res.json()) as { message: string }).message, pattern);
};
before(async () => {
await db.insert(users).values([
{ oidcSub: "admin", name: "Alma", role: "admin" },
{ oidcSub: "operator", name: "Olle", role: "operator" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
const cred = (await db.insert(integrationCredentials).values({ name: "authentik:Front door", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok", writeToken: "write-tok" })) }).returning({ id: integrationCredentials.id }))[0];
const credRead = (await db.insert(integrationCredentials).values({ name: "authentik:Watched", encryptedSecret: encryptSecret(JSON.stringify({ token: "read-tok" })) }).returning({ id: integrationCredentials.id }))[0];
const config = JSON.stringify({ url: fakeUrl });
id = (await db.insert(integrations).values({ type: "authentik", name: "Front door", baseUrl: fakeUrl, config, credentialId: cred.id }).returning({ id: integrations.id }))[0].id;
readOnly = (await db.insert(integrations).values({ type: "authentik", name: "Watched", baseUrl: fakeUrl, config, credentialId: credRead.id }).returning({ id: integrations.id }))[0].id;
await updateSettings({ signIn: { roleFromGroups: true, groupsClaim: "groups", adminGroups: ["admins"], operatorGroups: ["family"], otherwise: "viewer" } });
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } };
next();
});
a.use("/api/authentik", authentikRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/authentik`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("only an administrator sees the groups or changes them; nothing reaches Authentik for anyone else", async () => {
reset();
for (const sub of ["viewer", "operator"]) {
assert.equal((await details(sub)).status, 403, sub);
assert.equal((await change(G_FAMILY, { name: "x" }, sub)).status, 403, sub);
}
assert.deepEqual(seen, []);
});
test("the groups with their members and the people to name them by (not service accounts), which group decides a role here, and which user the token is", async () => {
reset();
const res = await details();
assert.equal(res.status, 200);
const text = await res.text();
assert.equal(/write-tok|read-tok/.test(text), false);
const body = JSON.parse(text) as { groups: { name: string; admin: boolean; members: number[]; decidesRole: string | null }[]; people: { username: string }[]; self: number; more: boolean };
assert.deepEqual(body.groups.map((g) => [g.name, g.admin, g.members, g.decidesRole]), [["admins", true, [1, 2], "admin"], ["Family", false, [3], "operator"], ["Other", false, [], null]]);
assert.deepEqual(body.people.map((p) => p.username), ["akadmin", "bob", "carol", "dave"]);
assert.deepEqual([body.self, body.more], [1, false]);
});
test("renaming and changing members: the name first, then each user, and the audit log says who was put in and taken out", async () => {
reset();
const res = await change(G_FAMILY, { name: "Household", membersAdd: [4], membersRemove: [3] });
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), { changed: ["name", "members"], added: 1, removed: 1 });
assert.deepEqual(writes().map((s) => `${s.method} ${s.path.replace(G_FAMILY, "G")} ${s.body}`), ["PATCH /api/v3/core/groups/G/ {\"name\":\"Household\"}", "POST /api/v3/core/groups/G/add_user/ {\"pk\":4}", "POST /api/v3/core/groups/G/remove_user/ {\"pk\":3}"]);
const [entry] = await audit("update_authentik_group");
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_group", G_FAMILY]);
assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: id, integration: "Front door", group: "Family", renamedTo: "Household", added: ["dave"], removed: ["carol"] });
});
test("members already in are not put in again, those not in are not taken out, and a change that changes nothing sends nothing and writes nothing", async () => {
reset();
const before = (await audit("update_authentik_group")).length;
const res = await change(G_FAMILY, { name: "Family", membersAdd: [3], membersRemove: [4] });
assert.deepEqual(await res.json(), { changed: [], added: 0, removed: 0 });
assert.deepEqual(writes(), []);
assert.equal((await audit("update_authentik_group")).length, before);
});
test("somebody who joined meanwhile is not dropped: members are put in and out one by one, never replaced", async () => {
reset();
groupTable.find((g) => g.pk === G_OTHER)!.users = [4]; // dave joined after the page was read
const res = await change(G_OTHER, { membersAdd: [3] });
assert.equal(res.status, 200);
assert.deepEqual(groupTable.find((g) => g.pk === G_OTHER)!.users, [4, 3]);
assert.deepEqual(writes().map((s) => s.path.split("/").slice(-2, -1)[0]), ["add_user"]);
});
test("what is wrong with the change is said before Authentik is asked", async () => {
reset();
for (const bad of [{ name: "" }, { membersAdd: ["x"] }, { membersAdd: [1.5] }, { membersAdd: [0] }, { membersAdd: [4], membersRemove: [4] }, { membersAdd: Array.from({ length: 26 }, (_, i) => i + 1) }]) {
const res = await change(G_FAMILY, bad);
assert.equal(res.status, 400, JSON.stringify(bad));
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
}
assert.equal((await change("not-a-uuid", { name: "x" })).status, 400);
assert.deepEqual(seen, []);
});
test("a service account and the token's own account are refused, and nothing at all is changed — not even the name asked for in the same request", async () => {
reset();
await refused(await change(G_FAMILY, { name: "Renamed", membersAdd: [5] }), /ak-outpost-front: .*service account/);
await refused(await change(G_FAMILY, { name: "Renamed", membersAdd: [4, 1] }), /akadmin: .*token/);
await refused(await change(G_ADMIN, { membersRemove: [1] }), /akadmin: .*token/);
assert.deepEqual(writes(), []);
assert.equal(groupTable.find((g) => g.pk === G_FAMILY)!.name, "Family");
assert.deepEqual(groupTable.find((g) => g.pk === G_FAMILY)!.users, [3], "dave, checked before akadmin, was not put in either");
});
test("the last active administrator can't be taken out of the group that makes them one — unless they are in another such group, or another administrator is active", async () => {
reset();
meId = 3;
userTable.find((u) => u.pk === 2)!.is_active = false; // bob is off: akadmin is the only active administrator
await refused(await change(G_ADMIN, { membersRemove: [1] }), /akadmin: .*only active administrator/);
assert.deepEqual(writes(), []);
assert.equal((await change(G_ADMIN, { membersRemove: [2] })).status, 200, "bob is not an active administrator, so taking him out loses nothing");
// akadmin in a second administrators group: taking him out of the first leaves him an administrator.
groupTable.push({ pk: "55555555-5555-4555-8555-555555555555", name: "root", is_superuser: true, users: [1] });
userTable.find((u) => u.pk === 1)!.groups!.push("55555555-5555-4555-8555-555555555555");
assert.equal((await change(G_ADMIN, { membersRemove: [1] })).status, 200);
// And with another active administrator, one may come out of the only group.
reset();
meId = 3;
assert.equal((await change(G_ADMIN, { membersRemove: [1] })).status, 200);
});
test("a user whose groups Authentik did not say can be put in a group, but not taken out of one that makes administrators", async () => {
reset();
meId = 3;
delete userTable.find((u) => u.pk === 2)!.groups;
await refused(await change(G_ADMIN, { membersRemove: [2] }), /bob: .*did not say which groups/);
assert.equal((await change(G_FAMILY, { membersAdd: [4] })).status, 200);
assert.equal((await change(G_OTHER, { membersAdd: [2] })).status, 200);
});
test("a group whose members Authentik did not say can be renamed but its members are not changed", async () => {
reset();
delete (groupTable.find((g) => g.pk === G_OTHER) as Partial<FakeGroup>).users;
await refused(await change(G_OTHER, { membersAdd: [4] }), /did not say who is in this group/);
assert.equal((await change(G_OTHER, { name: "Others" })).status, 200);
});
test("a failure part-way says how far it got, and the audit log has what was done", async () => {
reset();
failMemberPk = 4;
const res = await change(G_OTHER, { name: "Others", membersAdd: [3, 4] });
assert.equal(res.status, 502);
assert.match(((await res.json()) as { message: string }).message, /boom|Authentik error/);
assert.deepEqual(groupTable.find((g) => g.pk === G_OTHER)!.users, [3], "the name and carol were done; dave was not");
const entry = (await audit("update_authentik_group")).at(-1)!;
const detail = JSON.parse(entry.detail ?? "{}") as { renamedTo?: string; added: string[] };
assert.deepEqual([detail.renamedTo, detail.added], ["Others", ["carol"]]);
assert.match(((await (await change(G_OTHER, { membersAdd: [4] })).json()) as { message: string }).message, /0 of 1 changes had been made/);
});
test("a group that is gone is not found; an Authentik with no token for managing users is not asked anything", async () => {
reset();
assert.equal((await change("99999999-9999-4999-8999-999999999999", { name: "x" })).status, 404);
seen.length = 0;
assert.equal((await fetch(`${base}/${readOnly}/group-details`, { headers: as("admin") })).status, 400);
assert.equal((await fetch(`${base}/${readOnly}/groups/${G_FAMILY}`, { method: "PATCH", headers: as("admin"), body: JSON.stringify({ name: "x" }) })).status, 400);
assert.deepEqual(seen, []);
});
});