List, switch off/on and delete Authentik users

Apps → Authentik gets a Users section for administrators: a searchable list
of people (service accounts left out) with status, administrator and last
sign-in, and Switch off / Switch on / Delete. Switching off sends only
is_active; deleting needs the user name typed and re-checked by the server.
The server refuses service accounts, the account the token belongs to and
the last active administrator. Each action is audited. The token field is
now "Token for making and managing users".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 00:31:14 +01:00
1 parent aa95d6b314
commit 0cd11268ee
12 files changed
+733 -21

No files matched your search

+112 -9
View File
@@ -1,10 +1,14 @@
/**
* Making a user in Authentik: the one thing this app does there that is not reading. It is kept apart from the adapter that reads (./adapter.ts, which sends nothing but GET requests with
* the integration's own token) and it has a token of its own — `writeToken`, optional, from an account that may add users — so an Authentik that is only watched is never written to.
* Making and looking after users in Authentik: what this app does there that is not reading. It is kept apart from the adapter that reads (./adapter.ts, which sends nothing but GET requests with
* the integration's own token) and it has a token of its own — `writeToken`, optional, from an account that may add, change and delete users — so an Authentik that is only watched is never written to.
*
* 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
* 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
* 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
* the address it was asked at, so it is only as good as the address in the integration.
*/
@@ -39,9 +43,9 @@ export interface CreatedAuthentikUser {
name: string;
}
/** How a call failed: `invalid` — Authentik looked at it and said no (a name taken, a bad address); `denied` — the token is not accepted or may not; `failed` — no answer, or one that makes no sense. */
/** How a call failed: `invalid` — Authentik looked at it and said no (a name taken, a bad address); `denied` — the token is not accepted or may not; `missing` — there is no such thing there (a user that is gone); `failed` — no answer, or one that makes no sense. */
export class AuthentikUserError extends Error {
constructor(message: string, readonly kind: "invalid" | "denied" | "failed") {
constructor(message: string, readonly kind: "invalid" | "denied" | "missing" | "failed") {
super(message);
}
}
@@ -51,6 +55,10 @@ const PAGE = 200;
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
const iso = (v: unknown): string | null => {
const s = str(v);
return s && Number.isFinite(Date.parse(s)) ? new Date(s).toISOString() : null;
};
/** Pure: the groups of a `/core/groups/` page, by name. */
export function parseGroups(raw: unknown): AuthentikGroup[] {
@@ -87,6 +95,57 @@ export function parseRecoveryLink(raw: unknown): string | null {
}
}
/** A user as the list shows them. */
export interface AuthentikUser {
pk: number;
username: string;
name: string;
email: string | null;
active: boolean;
/** A member of a superuser group, or a superuser themselves: may do everything in Authentik. */
admin: boolean;
lastLogin: string | null;
/** internal, external, service_account, internal_service_account. */
type: string;
}
/** What an outpost or an integration signs in with: not a person, and not this app's to switch off or delete. */
export const isServiceAccount = (u: Pick<AuthentikUser, "type">): boolean => u.type === "service_account" || u.type === "internal_service_account";
/** Pure: one user; null when the answer is not a user. A version that does not say what type a user is has only people. */
export function parseUser(raw: unknown): AuthentikUser | null {
const u = obj(raw);
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" };
}
/** Pure: the people of a `/core/users/` page (service accounts left out), and whether there are more pages than this one. */
export function parseUsers(raw: unknown): { users: AuthentikUser[]; more: boolean } {
const list = Array.isArray(raw) ? raw : Array.isArray(obj(raw).results) ? (obj(raw).results as unknown[]) : [];
const users = list.map(parseUser).filter((u): u is AuthentikUser => u !== null && !isServiceAccount(u));
return { users, more: Number(obj(obj(raw).pagination).total_pages) > 1 };
}
/** Pure: which user the token is, out of `/core/users/me/`; null when it does not say. */
export function parseMe(raw: unknown): number | null {
const pk = obj(obj(raw).user).pk;
return typeof pk === "number" && Number.isInteger(pk) && pk > 0 ? pk : null;
}
/**
* 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).
*/
export function refusalFor(user: AuthentikUser, action: "disable" | "enable" | "delete", self: number | null, activeAdmins: number[]): 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.";
return null;
}
/** Pure: what Authentik's complaint says, in words. It answers `{"username": ["…"]}`, `{"detail": "…"}` or `{"non_field_errors": ["…"]}`; the longest it is allowed to be is a sentence or two. */
export function describeComplaint(raw: unknown): string | null {
const o = obj(raw);
@@ -100,6 +159,14 @@ export function describeComplaint(raw: unknown): string | null {
}
export interface AuthentikUsersAdapter {
listUsers(search?: string): Promise<{ users: AuthentikUser[]; more: boolean }>;
getUser(pk: number): Promise<AuthentikUser>;
/** The user the token belongs to. */
whoAmI(): Promise<number | null>;
/** 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>;
deleteUser(pk: number): Promise<void>;
listGroups(): Promise<AuthentikGroup[]>;
createUser(input: NewAuthentikUser): Promise<CreatedAuthentikUser>;
recoveryLink(pk: number): Promise<string>;
@@ -110,7 +177,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", path: string, body?: unknown): Promise<unknown> {
async function call(method: "GET" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown): Promise<unknown> {
let res;
try {
res = await requestJson(`${base}/api/v3${path}`, { method, headers, body, insecure });
@@ -118,13 +185,49 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
throw new AuthentikUserError(`Authentik could not be reached: ${err instanceof Error ? err.message : String(err)}`, "failed");
}
if (res.status === 401 || res.status === 403) throw new AuthentikUserError(`Authentik did not accept the token for making users (HTTP ${res.status}) — it must be an API token of an account that may add users`, "denied");
if (res.status === 404) throw new AuthentikUserError("Authentik has no API at this address, or no such thing there — check the address", "failed");
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");
if (res.json === null) throw new AuthentikUserError("Authentik answered with something that isn't JSON — is the address its own?", "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");
return res.json;
}
const wholeNumber = (pk: number) => {
if (!Number.isInteger(pk) || pk <= 0) throw new AuthentikUserError("That is not a user id", "invalid");
return pk;
};
async function listUsers(search?: string) {
const q = search?.trim() ? `&search=${encodeURIComponent(search.trim())}` : "";
return parseUsers(await call("GET", `/core/users/?page_size=${PAGE}&ordering=username${q}`));
}
async function getUser(pk: number): Promise<AuthentikUser> {
const user = parseUser(await call("GET", `/core/users/${wholeNumber(pk)}/`));
if (!user) throw new AuthentikUserError("Authentik answered, but not with a user", "failed");
return user;
}
async function whoAmI(): Promise<number | null> {
return parseMe(await call("GET", "/core/users/me/"));
}
async function activeAdmins(): Promise<number[]> {
return parseUsers(await call("GET", "/core/users/?is_superuser=true&is_active=true&page_size=3")).users.map((u) => u.pk);
}
async function setActive(pk: number, active: boolean): Promise<AuthentikUser> {
// Only that one field: nothing else about the user is sent, so nothing else can change.
const user = parseUser(await call("PATCH", `/core/users/${wholeNumber(pk)}/`, { is_active: active }));
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)}/`);
}
async function listGroups(): Promise<AuthentikGroup[]> {
return parseGroups(await call("GET", `/core/groups/?page_size=${PAGE}&ordering=name`));
}
@@ -145,5 +248,5 @@ export function createAuthentikUsersAdapter(config: AuthentikUsersConfig): Authe
return link;
}
return withDiagLogging("authentik", { listGroups, createUser, recoveryLink });
return withDiagLogging("authentik", { listUsers, getUser, whoAmI, activeAdmins, setActive, deleteUser, listGroups, createUser, recoveryLink });
}
+1 -1
View File
@@ -187,7 +187,7 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
authentik: [
{ key: "url", label: "Authentik URL", secret: false, placeholder: "https://auth.example.lan" },
{ key: "token", label: "API token", secret: true, type: "password", placeholder: "Directory → Tokens and App passwords, intent API Token" },
{ key: "writeToken", label: "Token for making users (optional)", secret: true, optional: true, type: "password", placeholder: "only to make users from here; an account that may add users. Leave blank to only watch" },
{ key: "writeToken", label: "Token for making and managing users (optional)", secret: true, optional: true, type: "password", placeholder: "only to make, switch off and delete users from here; an account that may. Leave blank to only watch" },
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
],
jellyfin: [
+1 -1
View File
@@ -15,7 +15,7 @@ export interface JsonResponse {
const TIMEOUT_MS = 15_000;
export function requestJson(url: string, opts: { method?: "GET" | "POST"; headers?: Record<string, string>; body?: unknown; insecure?: boolean; timeoutMs?: number } = {}): Promise<JsonResponse> {
export function requestJson(url: string, opts: { method?: "GET" | "POST" | "PATCH" | "DELETE"; headers?: Record<string, string>; body?: unknown; insecure?: boolean; timeoutMs?: number } = {}): Promise<JsonResponse> {
return new Promise((resolve, reject) => {
let parsed: URL;
try {
+73 -2
View File
@@ -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, type AuthentikUsersAdapter } from "../integrations/authentik/users.js";
import { 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";
@@ -55,10 +55,21 @@ async function usersAdapterFor(rawId: string, res: Response): Promise<{ adapter:
/** What a failed call to Authentik is answered with: what it said when it looked and refused, a bad gateway otherwise. */
function sendFailure(res: Response, err: unknown) {
if (err instanceof AuthentikUserError) return res.status(err.kind === "invalid" ? 400 : 502).json({ error: `authentik_${err.kind}`, message: err.message });
if (err instanceof AuthentikUserError) return res.status(err.kind === "invalid" ? 400 : err.kind === "missing" ? 404 : 502).json({ error: `authentik_${err.kind}`, message: err.message });
return res.status(502).json({ error: "authentik_failed", message: err instanceof Error ? err.message : String(err) });
}
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, []) };
const self = await adapter.whoAmI();
const admins = user.admin && user.active ? await adapter.activeAdmins() : [];
return { user, refusal: refusalFor(user, action, self, admins) };
}
const newUserSchema = z.object({
username: z.string().trim().min(1, "A user name is needed.").max(150).regex(/^[^\x00-\x1f\x7f]+$/, "A user name can't hold control characters."),
name: z.string().trim().min(1, "A name is needed.").max(200),
@@ -177,3 +188,63 @@ authentikRouter.delete("/:id/write-token", requireRole("admin"), asyncHandler(as
}
res.status(204).end();
}));
/** The people in that Authentik, for the page that looks after them: not the service accounts, and which one the token belongs to (that one is not touched). Only an administrator. */
authentikRouter.get("/:id/users", requireRole("admin"), asyncHandler(async (req, res) => {
const target = await usersAdapterFor(req.params.id, res);
if (!target) return;
const search = typeof req.query.search === "string" ? req.query.search.trim().slice(0, 100) : "";
try {
const [list, self] = await Promise.all([target.adapter.listUsers(search), target.adapter.whoAmI()]);
res.json({ users: list.users, more: list.more, self });
} catch (err) {
sendFailure(res, err);
}
}));
const activeSchema = z.object({ active: z.boolean() });
/** Switches a user off or on again. Off means they can no longer sign in at Authentik; nothing of theirs is lost, and on brings it all back. */
authentikRouter.post("/:id/users/:pk/active", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = activeSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say whether the user is to be on or off." });
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 action = parsed.data.active ? "enable" : "disable";
try {
const { user, refusal } = await guard(target.adapter, pk, action);
if (refusal) return res.status(409).json({ error: "refused", message: refusal });
const updated = await target.adapter.setActive(pk, parsed.data.active);
await recordAudit({ actor: req.currentUser!, category: "integration", action: `${action}_authentik_user`, targetType: "authentik_user", targetId: pk, detail: { integrationId: target.id, integration: target.name, username: user.username } });
res.json({ user: updated });
} catch (err) {
sendFailure(res, err);
}
}));
const deleteSchema = z.object({ username: z.string().min(1).max(150) });
/**
* Deletes a user for good. The user name has to be sent along and has to be the one the user has now: a page that is minutes old, or a wrong id, cannot delete somebody else. Switching off
* is the way that can be undone; this is not.
*/
authentikRouter.delete("/:id/users/:pk", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = deleteSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "The user name has to be sent along to delete a user." });
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;
try {
const { user, refusal } = await guard(target.adapter, pk, "delete");
if (user.username !== parsed.data.username) return res.status(400).json({ error: "username_mismatch", message: "That is not the user name of that user." });
if (refusal) return res.status(409).json({ error: "refused", message: refusal });
await target.adapter.deleteUser(pk);
await recordAudit({ actor: req.currentUser!, category: "integration", action: "delete_authentik_user", targetType: "authentik_user", targetId: pk, detail: { integrationId: target.id, integration: target.name, username: user.username } });
res.status(204).end();
} catch (err) {
sendFailure(res, err);
}
}));
+358
View File
@@ -0,0 +1,358 @@
/**
* 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
* administrator, a user name that does not match), who may, and what is written in the audit log.
*
* 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-useradmin-"));
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 { authentikRouter } = await import("../src/routes/authentik.js");
await runMigrations();
interface FakeUser {
pk: number;
username: string;
name: string;
email: string;
is_active: boolean;
is_superuser: boolean;
last_login: string | null;
type: 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 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(4, "dave", { is_active: false }),
person(5, "ak-outpost-front", { type: "internal_service_account", email: "" }),
];
describe("what Authentik's answers are read as", () => {
test("the list: people only, with whether they are on, administrators and when they last signed in; and whether there are more pages", () => {
const { users: list, more } = usersApi.parseUsers({ pagination: { total_pages: 2 }, results: fresh() });
assert.deepEqual(list.map((u) => u.username), ["akadmin", "bob", "carol", "dave"], "the outpost's account is not a person");
assert.deepEqual([list[0].admin, list[0].lastLogin, list[3].active, list[2].email], [true, "2026-10-30T08:00:00.000Z", false, "carol@example.com"]);
assert.equal(more, true);
assert.equal(usersApi.parseUsers({ pagination: { total_pages: 1 }, results: [] }).more, false);
assert.deepEqual(usersApi.parseUsers("nonsense"), { users: [], more: false });
});
test("a user needs a whole-number id and a user name; a version that does not say the type has only people", () => {
assert.equal(usersApi.parseUser({ pk: "3", username: "x" }), null);
assert.equal(usersApi.parseUser({ pk: 3 }), null);
const u = usersApi.parseUser({ pk: 3, username: "x" })!;
assert.deepEqual([u.type, u.active, u.admin, u.email, u.name], ["internal", true, false, null, "x"]);
assert.equal(usersApi.isServiceAccount({ type: "service_account" }), true);
assert.equal(usersApi.isServiceAccount({ type: "internal_service_account" }), true);
assert.equal(usersApi.isServiceAccount({ type: "external" }), false);
});
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);
assert.equal(usersApi.parseMe({}), null);
});
test("what is refused: a service account always; the token's own account and the last active administrator when switching off or deleting; switching on, never", () => {
const [akadmin, bob, carol, dave, outpost] = fresh().map((f) => usersApi.parseUser(f)!);
assert.match(usersApi.refusalFor(outpost, "disable", 1, [1, 2]) ?? "", /service account/);
assert.match(usersApi.refusalFor(outpost, "enable", 1, [1, 2]) ?? "", /service account/);
assert.match(usersApi.refusalFor(akadmin, "disable", 1, [1, 2]) ?? "", /token/);
assert.match(usersApi.refusalFor(akadmin, "delete", 1, [1, 2]) ?? "", /token/);
assert.equal(usersApi.refusalFor(akadmin, "enable", 1, [1, 2]), null);
assert.equal(usersApi.refusalFor(bob, "disable", 1, [1, 2]), null, "there is another administrator");
assert.match(usersApi.refusalFor(bob, "delete", 1, [2]) ?? "", /only active administrator/);
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);
});
});
/** An Authentik with a few users that remembers what it was asked. */
interface Seen {
method: string;
path: string;
auth: string;
body: string;
}
const seen: Seen[] = [];
let table = fresh();
let meId = 1;
let patchStatus = 200;
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/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;
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);
const q = url.searchParams.get("search");
if (q) list = list.filter((u) => u.username.includes(q) || u.name.toLowerCase().includes(q.toLowerCase()));
return send(200, { pagination: { total_pages: 1 }, results: list });
}
const one = /^\/api\/v3\/core\/users\/(\d+)\/$/.exec(url.pathname);
if (one) {
const user = table.find((u) => u.pk === Number(one[1]));
if (!user) return send(404, { detail: "Not found." });
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;
return send(200, user);
}
if (req.method === "DELETE") {
table = table.filter((u) => u.pk !== user.pk);
return send(204);
}
}
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();
});
describe("the calls", () => {
const adapter = () => usersApi.createAuthentikUsersAdapter({ url: fakeUrl, writeToken: "write-tok" });
const reset = () => {
table = fresh();
meId = 1;
patchStatus = 200;
seen.length = 0;
};
test("the list is asked for by name, with what was searched for, using the token for managing users", async () => {
reset();
const all = await adapter().listUsers();
assert.deepEqual(all.users.map((u) => u.username), ["akadmin", "bob", "carol", "dave"]);
const found = await adapter().listUsers(" car ol&x ");
assert.deepEqual(found.users, [], "nothing is called that");
assert.match(seen[1].path, /search=car%20ol%26x$/);
assert.deepEqual([...new Set(seen.map((s) => s.auth))], ["Bearer write-tok"]);
assert.equal(await adapter().whoAmI(), 1);
});
test("switching off is a PATCH of that one field and nothing else; deleting is a DELETE of that user", async () => {
reset();
const off = await adapter().setActive(3, false);
assert.equal(off.active, false);
assert.deepEqual([seen[0].method, seen[0].path, seen[0].body], ["PATCH", "/api/v3/core/users/3/", JSON.stringify({ is_active: false })]);
await adapter().deleteUser(4);
assert.deepEqual([seen[1].method, seen[1].path], ["DELETE", "/api/v3/core/users/4/"]);
assert.equal(table.some((u) => u.pk === 4), false);
});
test("a user id that is not a whole number is never put in the address; a user that is gone is said so", async () => {
reset();
for (const bad of [0, -1, 1.5, Number.NaN]) {
await assert.rejects(() => adapter().setActive(bad, false), /not a user id/);
await assert.rejects(() => adapter().deleteUser(bad), /not a user id/);
await assert.rejects(() => adapter().getUser(bad), /not a user id/);
}
assert.deepEqual(seen, []);
await assert.rejects(
() => adapter().getUser(99),
(err: Error & { kind?: string }) => err.kind === "missing",
);
});
test("the active administrators are asked for as such", async () => {
reset();
assert.deepEqual(await adapter().activeAdmins(), [1, 2]);
assert.match(seen[0].path, /is_superuser=true/);
assert.match(seen[0].path, /is_active=true/);
});
});
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 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 writes = () => seen.filter((s) => s.method !== "GET");
const reset = () => {
table = fresh();
meId = 1;
patchStatus = 200;
seen.length = 0;
};
const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action);
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;
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 users or changes them; nothing reaches Authentik for anyone else", async () => {
reset();
for (const sub of ["viewer", "operator"]) {
assert.equal((await list(sub)).status, 403, sub);
assert.equal((await active(3, false, sub)).status, 403, sub);
assert.equal((await del(3, "carol", sub)).status, 403, sub);
}
assert.deepEqual(seen, []);
});
test("the list: the people, whether each is on, which one the token is, and what was searched for", async () => {
reset();
const res = await list();
assert.equal(res.status, 200);
const body = (await res.json()) as { users: { pk: number; username: string; active: boolean; admin: boolean; lastLogin: string | null }[]; more: boolean; self: number };
assert.deepEqual(body.users.map((u) => [u.pk, u.username, u.active, u.admin]), [[1, "akadmin", true, true], [2, "bob", true, true], [3, "carol", true, false], [4, "dave", false, false]]);
assert.deepEqual([body.self, body.more], [1, false]);
const found = (await (await list("admin", "?search=carol")).json()) as { users: { username: string }[] };
assert.deepEqual(found.users.map((u) => u.username), ["carol"]);
assert.equal(/write-tok|read-tok/.test(JSON.stringify(body)), false);
});
test("switching a user off and on: Authentik is asked for exactly that, and the audit log says who did it to whom", async () => {
reset();
const off = await active(3, false);
assert.equal(off.status, 200);
assert.equal(((await off.json()) as { user: { active: boolean } }).user.active, false);
assert.deepEqual(writes().map((s) => [s.method, s.path, s.body]), [["PATCH", "/api/v3/core/users/3/", JSON.stringify({ is_active: false })]]);
assert.equal(table.find((u) => u.pk === 3)!.is_active, false);
const on = await active(3, true);
assert.equal(on.status, 200);
assert.equal(table.find((u) => u.pk === 3)!.is_active, true);
const [d] = await audit("disable_authentik_user");
const [e] = await audit("enable_authentik_user");
for (const entry of [d, e]) {
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "3"]);
assert.match(entry.detail ?? "", /carol/);
}
});
test("a service account, the account the token belongs to, and the last active administrator are refused — and not touched", 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 active(5, false), /service account/);
await refused(await del(5, "ak-outpost-front"), /service account/);
await refused(await active(1, false), /token/);
await refused(await del(1, "akadmin"), /token/);
assert.deepEqual(writes(), []);
// The token is somebody else's now, and bob is the only other administrator: with bob off, akadmin is the last one holding the door.
meId = 3;
assert.equal((await active(2, false)).status, 200, "there is still akadmin");
await refused(await active(1, false), /only active administrator/);
await refused(await del(1, "akadmin"), /only active administrator/);
assert.deepEqual(writes().map((s) => s.path), ["/api/v3/core/users/2/"]);
assert.equal((await active(5, true)).status, 409, "not even to switch one on");
});
test("deleting: the user name has to match the user now; then they are gone, and it is written down", async () => {
reset();
assert.equal((await del(4, undefined)).status, 400);
assert.equal((await del(4, "")).status, 400);
const wrong = await del(4, "carol");
assert.equal(wrong.status, 400);
assert.equal(((await wrong.json()) as { error: string }).error, "username_mismatch");
assert.deepEqual(writes(), []);
assert.equal(table.some((u) => u.pk === 4), true);
assert.equal((await del(4, "dave")).status, 204);
assert.equal(table.some((u) => u.pk === 4), false);
assert.deepEqual(writes().map((s) => [s.method, s.path]), [["DELETE", "/api/v3/core/users/4/"]]);
const [entry] = await audit("delete_authentik_user");
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "authentik_user", "4"]);
assert.match(entry.detail ?? "", /dave/);
});
test("a user that is gone, an id that is no id, and a refusal from Authentik itself are told as such", async () => {
reset();
assert.equal((await active(99, false)).status, 404);
assert.equal((await del(99, "x")).status, 404);
assert.equal((await active(Number.NaN, false)).status, 400);
assert.equal((await fetch(`${base}/${id}/users/1e3/active`, { method: "POST", headers: as("admin"), body: JSON.stringify({ active: false }) })).status, 400);
assert.equal((await fetch(`${base}/${id}/users/3/active`, { method: "POST", headers: as("admin"), body: JSON.stringify({ active: "yes" }) })).status, 400);
const before = (await audit("disable_authentik_user")).length;
patchStatus = 403;
const res = await active(3, false);
assert.equal(res.status, 502);
assert.match(((await res.json()) as { message: string }).message, /did not accept the token/);
assert.equal((await audit("disable_authentik_user")).length, before, "nothing was done, so nothing more is written down");
});
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") });
assert.equal(res.status, 400);
assert.equal(((await res.json()) as { error: string }).error, "no_write_token");
assert.equal((await active(3, false, "admin", readOnly)).status, 400);
assert.deepEqual(seen, []);
});
});