import { Router, type Response } from "express"; import { eq } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; import { authentikState, integrationCredentials, integrations } from "../db/schema.js"; 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 { recordAudit } from "../services/audit.js"; import { authentikProblems, authentikSyncStatuses, certificatesOf, daysUntil, isAuthentikFresh, outpostsOf, tokensOf } from "../services/authentikSync.js"; import { asyncHandler } from "../utils/asyncHandler.js"; export const authentikRouter = Router(); authentikRouter.use(requireAuth); const hasWriteToken = (config: Record) => typeof config.writeToken === "string" && config.writeToken.trim() !== ""; /** Whether this Authentik was given a token to make users with. Never says more than that; a credential that cannot be opened counts as none. */ async function canCreateUsers(id: number): Promise { try { const loaded = await loadIntegrationConfig(id); return !!loaded && hasWriteToken(loaded.config); } catch { return false; } } /** The adapter that makes users for one Authentik, or the answer to send when there is not one to use. Only an enabled Authentik with a token for it. */ async function usersAdapterFor(rawId: string, res: Response): Promise<{ adapter: AuthentikUsersAdapter; id: number; name: string } | null> { const id = /^\d+$/.test(rawId) ? Number(rawId) : NaN; if (!Number.isInteger(id)) { res.status(400).json({ error: "invalid_id" }); return null; } const loaded = await loadIntegrationConfig(id); if (!loaded) { res.status(404).json({ error: "not_found" }); return null; } if (loaded.integration.type !== "authentik") { res.status(400).json({ error: "wrong_type" }); return null; } if (!loaded.integration.enabled) { res.status(400).json({ error: "integration_disabled", message: "This Authentik is switched off." }); return null; } if (!hasWriteToken(loaded.config)) { res.status(400).json({ error: "no_write_token", message: "This Authentik has no token for making users. Add one under Integrations → edit." }); return null; } return { adapter: createAuthentikUsersAdapter(loaded.config as never), id, name: loaded.integration.name }; } /** 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 : 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); type UserAction = "disable" | "enable" | "delete" | "edit"; /** Whether this may be done to this user, asked of Authentik itself — not taken from the page, which may be minutes old. For an edit, `newGroups` is what their groups would be. */ async function judge(adapter: AuthentikUsersAdapter, user: AuthentikUser, action: UserAction, newGroups?: string[]): Promise { if (action === "enable" || isServiceAccount(user)) return refusalFor(user, action, null, []); const self = await adapter.whoAmI(); const admins = user.admin && user.active ? await adapter.activeAdmins() : []; let losesAdmin = false; if (action === "edit" && newGroups && user.admin && user.active) { const adminGroups = new Set((await adapter.listGroups()).filter((g) => g.admin).map((g) => g.id)); losesAdmin = !newGroups.some((g) => adminGroups.has(g)); } return refusalFor(user, action, self, admins, losesAdmin); } /** The user as Authentik has them now, and whether this may be done to them. */ async function guard(adapter: AuthentikUsersAdapter, pk: number, action: Exclude): Promise<{ user: AuthentikUser; refusal: string | null }> { const user = await adapter.getUser(pk); return { user, refusal: await judge(adapter, user, action) }; } 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), email: z.union([z.literal(""), z.string().trim().email("That is not an email address.").max(254)]).optional(), groups: z.array(z.string().uuid()).max(50).default([]), }); /** Every Authentik, how it is, from what the last read stored: its outposts, certificates and tokens that run out, and what is wrong. Everyone signed in can see it, like the other pages made of stored readings. */ authentikRouter.get("/", asyncHandler(async (_req, res) => { const [rows, states, statuses] = await Promise.all([ db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "authentik")).orderBy(integrations.name), db.select().from(authentikState), authentikSyncStatuses(), ]); const byId = new Map(states.map((s) => [s.integrationId, s])); const writable = new Map(await Promise.all(rows.map(async (r) => [r.id, await canCreateUsers(r.id)] as const))); const now = new Date(); res.json({ authentiks: rows.map((r) => { const state = byId.get(r.id) ?? null; const status = statuses[r.id] ?? null; const fresh = isAuthentikFresh(status ?? undefined, now.getTime()); return { id: r.id, name: r.name, enabled: r.enabled, canCreateUsers: r.enabled && writable.get(r.id) === true, status, fresh, state: state ? { version: state.version, latestVersion: state.latestVersion, outdated: state.outdated, workers: state.workers, outposts: outpostsOf(state), certificates: certificatesOf(state).map((c) => ({ ...c, days: daysUntil(c.expires, now) })).sort((a, b) => a.days - b.days), tokens: tokensOf(state).map((t) => ({ ...t, days: daysUntil(t.expires, now) })).sort((a, b) => a.days - b.days), failedLogins24h: state.failedLogins24h, configErrors24h: state.configErrors24h, lastConfigError: state.lastConfigError, updatedAt: state.updatedAt, } : null, problems: state && fresh ? authentikProblems(r.id, r.name, state, now) : [], }; }), }); })); /** The groups a new user can be put in, as the Authentik being asked has them. Only an administrator, and only where a token for making users was given. */ authentikRouter.get("/:id/groups", requireRole("admin"), asyncHandler(async (req, res) => { const target = await usersAdapterFor(req.params.id, res); if (!target) return; try { res.json({ groups: await target.adapter.listGroups() }); } catch (err) { sendFailure(res, err); } })); /** * Makes a user and a one-time recovery link for them, which is how they choose their own password: no password passes through here. The link is in this answer and nowhere else — not stored, * not in the audit log. When the user is made and the link is not, the answer says so and the link is made in Authentik (the user's page → Create recovery link). */ authentikRouter.post("/:id/users", requireRole("admin"), asyncHandler(async (req, res) => { const parsed = newUserSchema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a user.", details: parsed.error.flatten() }); const target = await usersAdapterFor(req.params.id, res); if (!target) return; let user; try { user = await target.adapter.createUser({ username: parsed.data.username, name: parsed.data.name, email: parsed.data.email || undefined, groups: parsed.data.groups }); } catch (err) { return sendFailure(res, err); } await recordAudit({ actor: req.currentUser!, category: "integration", action: "create_authentik_user", targetType: "authentik_user", targetId: user.pk, detail: { integrationId: target.id, integration: target.name, username: user.username, groups: parsed.data.groups.length }, }); let link: string | null = null; let linkError: string | null = null; try { link = await target.adapter.recoveryLink(user.pk); await recordAudit({ actor: req.currentUser!, category: "integration", action: "make_authentik_recovery_link", targetType: "authentik_user", targetId: user.pk, detail: { integrationId: target.id, username: user.username } }); } catch (err) { linkError = err instanceof Error ? err.message : String(err); } res.set("Cache-Control", "no-store"); res.status(201).json({ user, link, linkError }); })); /** Takes the token for making users away again, leaving the one that reads. */ authentikRouter.delete("/:id/write-token", requireRole("admin"), asyncHandler(async (req, res) => { const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : NaN; if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" }); const [row] = await db.select().from(integrations).where(eq(integrations.id, id)).limit(1); if (!row) return res.status(404).json({ error: "not_found" }); if (row.type !== "authentik") return res.status(400).json({ error: "wrong_type" }); if (row.credentialId) { const [cred] = await db.select().from(integrationCredentials).where(eq(integrationCredentials.id, row.credentialId)).limit(1); if (cred) { const secrets = JSON.parse(decryptSecret(cred.encryptedSecret)) as Record; if ("writeToken" in secrets) { delete secrets.writeToken; await db.update(integrationCredentials).set({ encryptedSecret: encryptSecret(JSON.stringify(secrets)) }).where(eq(integrationCredentials.id, cred.id)); await recordAudit({ actor: req.currentUser!, category: "integration", action: "remove_authentik_write_token", targetType: "integration", targetId: id, detail: { name: row.name } }); } } } 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); } })); const editSchema = z .object({ name: z.string().trim().min(1, "A name is needed.").max(200).optional(), // An empty email clears it. email: z.union([z.literal(""), z.string().trim().email("That is not an email address.").max(254)]).optional(), // Groups are changed by what to put in and what to take out, never by a whole list: a membership somebody gave them meanwhile is kept. groupsAdd: z.array(z.string().uuid()).max(50).default([]), groupsRemove: z.array(z.string().uuid()).max(50).default([]), }) .refine((d) => !d.groupsAdd.some((g) => d.groupsRemove.includes(g)), { message: "A group can't be both put in and taken out." }); /** * Changes a user's name, email and groups — what they are called and where they belong; not the user name, which is how a person is known elsewhere. Authentik is sent only what differs * from the user as it has them now (nothing at all when nothing does), and the groups as that user's current ones with the changes made. */ authentikRouter.patch("/:id/users/:pk", requireRole("admin"), asyncHandler(async (req, res) => { const parsed = editSchema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a change.", details: parsed.error.flatten() }); const pk = pkOf(req.params.pk); if (!Number.isInteger(pk) || pk <= 0) return res.status(400).json({ error: "invalid_user" }); const target = await usersAdapterFor(req.params.id, res); if (!target) return; const { name, email, groupsAdd, groupsRemove } = parsed.data; try { const user = await target.adapter.getUser(pk); const changes: { name?: string; email?: string; groups?: string[] } = {}; if (name !== undefined && name !== user.name) changes.name = name; if (email !== undefined && email !== (user.email ?? "")) changes.email = email; let newGroups: string[] | undefined; if (groupsAdd.length > 0 || groupsRemove.length > 0) { if (user.groups === null) return res.status(409).json({ error: "refused", message: "Authentik did not say which groups this user is in, so they are not changed from here." }); const next = applyGroupChange(user.groups, groupsAdd, groupsRemove); if (next.length !== user.groups.length || next.some((g) => !user.groups!.includes(g))) { changes.groups = next; newGroups = next; } } const changed = Object.keys(changes); if (changed.length === 0) return res.json({ user, changed }); const refusal = await judge(target.adapter, user, "edit", newGroups); if (refusal) return res.status(409).json({ error: "refused", message: refusal }); const updated = await target.adapter.updateUser(pk, changes); await recordAudit({ actor: req.currentUser!, category: "integration", action: "update_authentik_user", targetType: "authentik_user", targetId: pk, detail: { integrationId: target.id, integration: target.name, username: user.username, changed } }); res.json({ user: updated, changed }); } catch (err) { sendFailure(res, err); } }));