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:
1 parent
aa95d6b314
commit
0cd11268ee
12 files changed
+733
-21
No files matched your search
@@ -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 });
|
||||
}
|
||||
@@ -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: [
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}));
|
||||
Reference in new issue
Block a user