Make Authentik users from Apps → Authentik, with a one-time recovery link

An administrator can make a user (user name, name, optional email, groups)
and gets a recovery link to send them, so they choose their own password;
no password is set or seen here. Uses a separate optional "Token for making
users" on the Authentik integration; reading never uses it, and it can be
removed again from the page. The link is shown once and never stored or
audited; the audit log records who made which user and link.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 00:18:25 +01:00
1 parent 9ca83994fb
commit aa95d6b314
13 files changed
+892 -18

No files matched your search

+372
View File
@@ -0,0 +1,372 @@
/**
* Making a user in Authentik: what its answers are read as, the three calls it takes (groups, the user, a recovery link), that a token of its own is used and the one that reads never is, the
* admin-only routes, what is written in the audit log (never the link), and taking the token away.
*
* 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-users-"));
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 { INTEGRATION_FIELDS } = await import("../src/integrations/fieldSchemas.js");
const { loadIntegrationConfig } = await import("../src/integrations/loadIntegration.js");
const usersApi = await import("../src/integrations/authentik/users.js");
const { createAuthentikAdapter } = await import("../src/integrations/authentik/adapter.js");
const { authentikRouter } = await import("../src/routes/authentik.js");
await runMigrations();
const GROUP_A = "11111111-1111-4111-8111-111111111111";
const GROUP_ADMIN = "22222222-2222-4222-8222-222222222222";
describe("what Authentik's answers are read as", () => {
test("groups: by name, with the ones that make an administrator marked; a row without a real id or a name is left out", () => {
const groups = usersApi.parseGroups({
results: [
{ pk: GROUP_ADMIN, name: "authentik Admins", is_superuser: true },
{ pk: GROUP_A, name: "Family", is_superuser: false },
{ pk: "not-a-uuid", name: "Broken" },
{ pk: "33333333-3333-4333-8333-333333333333", name: " " },
],
});
assert.deepEqual(groups, [{ id: GROUP_ADMIN, name: "authentik Admins", admin: true }, { id: GROUP_A, name: "Family", admin: false }]);
assert.deepEqual(usersApi.parseGroups("nonsense"), []);
});
test("the user it made needs a whole-number id and a name; the display name falls back to the user name", () => {
assert.deepEqual(usersApi.parseCreatedUser({ pk: 7, username: "ada", name: "Ada L" }), { pk: 7, username: "ada", name: "Ada L" });
assert.deepEqual(usersApi.parseCreatedUser({ pk: 7, username: "ada" }), { pk: 7, username: "ada", name: "ada" });
assert.equal(usersApi.parseCreatedUser({ pk: "7", username: "ada" }), null);
assert.equal(usersApi.parseCreatedUser({ pk: 0, username: "ada" }), null);
assert.equal(usersApi.parseCreatedUser({ pk: 3 }), null);
});
test("the link must be a web address", () => {
assert.equal(usersApi.parseRecoveryLink({ link: "https://auth.example.lan/if/flow/recovery/?token=abc" }), "https://auth.example.lan/if/flow/recovery/?token=abc");
assert.equal(usersApi.parseRecoveryLink({ link: "javascript:alert(1)" }), null);
assert.equal(usersApi.parseRecoveryLink({ link: "not a url" }), null);
assert.equal(usersApi.parseRecoveryLink({}), null);
});
test("a complaint is put in words, field by field, and kept short", () => {
assert.equal(usersApi.describeComplaint({ username: ["A user with that username already exists."] }), "username: A user with that username already exists.");
assert.equal(usersApi.describeComplaint({ detail: "Not allowed." }), "Not allowed.");
assert.equal(usersApi.describeComplaint({ non_field_errors: ["No recovery flow set."] }), "No recovery flow set.");
assert.equal(usersApi.describeComplaint({ email: ["x".repeat(900)] })?.length, 300);
assert.equal(usersApi.describeComplaint({}), null);
assert.equal(usersApi.describeComplaint(null), null);
});
});
/** An Authentik that remembers what it was asked. */
interface Seen {
method: string;
path: string;
auth: string;
body: string;
}
const seen: Seen[] = [];
let createStatus = 201;
let createAnswer: unknown = null;
let recoveryStatus = 200;
let recoveryAnswer: unknown = null;
let nextPk = 40;
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) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(json));
};
if (req.method === "GET" && path.startsWith("/api/v3/core/groups/")) {
return send(200, { results: [{ pk: GROUP_A, name: "Family", is_superuser: false }, { pk: GROUP_ADMIN, name: "authentik Admins", is_superuser: true }] });
}
if (req.method === "POST" && path === "/api/v3/core/users/") {
if (createStatus !== 201) return send(createStatus, createAnswer ?? {});
const b = JSON.parse(body) as { username: string; name: string };
return send(201, createAnswer ?? { pk: nextPk++, username: b.username, name: b.name });
}
const rec = /^\/api\/v3\/core\/users\/(\d+)\/recovery\/$/.exec(path);
if (req.method === "POST" && rec) return send(recoveryStatus, recoveryAnswer ?? { link: `${fakeUrl}/if/flow/recovery/?token=secret-${rec[1]}` });
// What the read adapter asks: anything else answers with something that parses as empty.
if (req.method === "GET" && path.startsWith("/api/v3/admin/version/")) return send(200, { version_current: "2025.2.1", version_latest: "2025.2.1", outdated: false });
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 adapterFor = (writeToken = "write-tok") => usersApi.createAuthentikUsersAdapter({ url: fakeUrl, writeToken });
describe("the three calls", () => {
test("the groups are asked for with the token for making users", async () => {
seen.length = 0;
const groups = await adapterFor().listGroups();
assert.deepEqual(groups.map((g) => g.name), ["authentik Admins", "Family"]);
assert.deepEqual(seen.map((s) => [s.method, s.path.split("?")[0], s.auth]), [["GET", "/api/v3/core/groups/", "Bearer write-tok"]]);
});
test("a user is a POST of the name, the user name, the email if there is one and the groups — and no password", async () => {
seen.length = 0;
const user = await adapterFor().createUser({ username: "ada", name: "Ada L", email: "ada@example.com", groups: [GROUP_A, "not-a-uuid"] });
assert.equal(user.username, "ada");
assert.equal(seen.length, 1);
assert.deepEqual([seen[0].method, seen[0].path], ["POST", "/api/v3/core/users/"]);
const body = JSON.parse(seen[0].body);
assert.deepEqual(body, { username: "ada", name: "Ada L", is_active: true, groups: [GROUP_A], email: "ada@example.com" });
assert.equal("password" in body, false);
await adapterFor().createUser({ username: "bo", name: "Bo", groups: [] });
assert.equal("email" in JSON.parse(seen[1].body), false, "no email, no email field");
});
test("the link is a POST to that user's recovery, and a user id that is not a whole number is never put in the address", async () => {
seen.length = 0;
const link = await adapterFor().recoveryLink(41);
assert.match(link, /\/if\/flow\/recovery\/\?token=secret-41$/);
assert.deepEqual(seen.map((s) => [s.method, s.path]), [["POST", "/api/v3/core/users/41/recovery/"]]);
await assert.rejects(() => adapterFor().recoveryLink(1.5), /not a user id/);
await assert.rejects(() => adapterFor().recoveryLink(Number.NaN), /not a user id/);
assert.equal(seen.length, 1);
});
test("what goes wrong is said in kind: refused (the words Authentik used), not accepted, nothing sensible back, nobody there", async () => {
createStatus = 400;
createAnswer = { username: ["A user with that username already exists."] };
await assert.rejects(
() => adapterFor().createUser({ username: "ada", name: "Ada", groups: [] }),
(err: Error & { kind?: string }) => err.kind === "invalid" && /username: A user with that username already exists\./.test(err.message),
);
createStatus = 403;
createAnswer = { detail: "You do not have permission." };
await assert.rejects(
() => adapterFor().createUser({ username: "ada", name: "Ada", groups: [] }),
(err: Error & { kind?: string }) => err.kind === "denied" && /may add users/.test(err.message),
);
createStatus = 201;
createAnswer = { nothing: "useful" };
await assert.rejects(() => adapterFor().createUser({ username: "ada", name: "Ada", groups: [] }), /not with the user it made/);
createAnswer = null;
recoveryAnswer = { link: "" };
await assert.rejects(() => adapterFor().recoveryLink(5), /recovery flow/);
recoveryAnswer = null;
await assert.rejects(() => usersApi.createAuthentikUsersAdapter({ url: "http://127.0.0.1:1", writeToken: "x" }).listGroups(), /could not be reached/);
});
});
describe("the integration form and the reading", () => {
test("the token for making users is an optional secret of the Authentik integration", () => {
const field = INTEGRATION_FIELDS.authentik!.find((f) => f.key === "writeToken");
assert.deepEqual([field?.secret, field?.optional, field?.type], [true, true, "password"]);
});
test("reading Authentik sends nothing but GET requests, with the token that reads — the one for making users is not used", async () => {
seen.length = 0;
await createAuthentikAdapter({ url: fakeUrl, token: "read-tok", writeToken: "write-tok" } as never).read();
assert.ok(seen.length > 0);
assert.deepEqual([...new Set(seen.map((s) => s.method))], ["GET"]);
assert.deepEqual([...new Set(seen.map((s) => s.auth))], ["Bearer read-tok"]);
});
});
describe("the routes", () => {
let app: Server;
let base = "";
let withToken = 0;
let withoutToken = 0;
let otherType = 0;
let off = 0;
const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub });
const post = (id: number, body: unknown, sub = "admin") => fetch(`${base}/${id}/users`, { method: "POST", headers: as(sub), body: JSON.stringify(body) });
const valid = { username: "ada", name: "Ada Lovelace", email: "ada@example.com", groups: [GROUP_A] };
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 credOnlyRead = (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 });
withToken = (await db.insert(integrations).values({ type: "authentik", name: "Front door", baseUrl: fakeUrl, config, credentialId: cred.id }).returning({ id: integrations.id }))[0].id;
withoutToken = (await db.insert(integrations).values({ type: "authentik", name: "Watched", baseUrl: fakeUrl, config, credentialId: credOnlyRead.id }).returning({ id: integrations.id }))[0].id;
off = (await db.insert(integrations).values({ type: "authentik", name: "Switched off", baseUrl: fakeUrl, config, credentialId: cred.id, enabled: false }).returning({ id: integrations.id }))[0].id;
otherType = (await db.insert(integrations).values({ type: "jellyfin", name: "Media", baseUrl: fakeUrl, config, credentialId: cred.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("the page says which Authentik can make users — only a yes or no, never the token — and a switched-off one cannot", async () => {
const res = await fetch(base, { headers: as("viewer") });
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 { authentiks: { id: number; canCreateUsers: boolean }[] };
const can = Object.fromEntries(body.authentiks.map((a) => [a.id, a.canCreateUsers]));
assert.deepEqual([can[withToken], can[withoutToken], can[off]], [true, false, false]);
});
test("only an administrator makes users or sees the groups; nothing reaches Authentik for anyone else", async () => {
seen.length = 0;
for (const sub of ["viewer", "operator"]) {
assert.equal((await post(withToken, valid, sub)).status, 403, sub);
assert.equal((await fetch(`${base}/${withToken}/groups`, { headers: as(sub) })).status, 403, sub);
assert.equal((await fetch(`${base}/${withToken}/write-token`, { method: "DELETE", headers: as(sub) })).status, 403, sub);
}
assert.deepEqual(seen, []);
});
test("the groups come from the Authentik asked", async () => {
seen.length = 0;
const res = await fetch(`${base}/${withToken}/groups`, { headers: as("admin") });
assert.equal(res.status, 200);
const body = (await res.json()) as { groups: { name: string; admin: boolean }[] };
assert.deepEqual(body.groups.map((g) => [g.name, g.admin]), [["authentik Admins", true], ["Family", false]]);
assert.equal(seen[0].auth, "Bearer write-tok");
});
test("a user is made with a link for them; the link is in the answer only, and the audit log says who made whom but not the link", async () => {
seen.length = 0;
const res = await post(withToken, valid);
assert.equal(res.status, 201);
assert.equal(res.headers.get("cache-control"), "no-store");
const body = (await res.json()) as { user: { pk: number; username: string }; link: string | null; linkError: string | null };
assert.equal(body.user.username, "ada");
assert.match(body.link ?? "", /\/if\/flow\/recovery\/\?token=secret-/);
assert.equal(body.linkError, null);
assert.deepEqual(seen.map((s) => `${s.method} ${s.path}`), ["POST /api/v3/core/users/", `POST /api/v3/core/users/${body.user.pk}/recovery/`]);
const entries = (await db.select().from(auditLog)).filter((e) => e.action === "create_authentik_user" || e.action === "make_authentik_recovery_link");
assert.deepEqual(entries.map((e) => e.action).sort(), ["create_authentik_user", "make_authentik_recovery_link"]);
for (const e of entries) {
assert.deepEqual([e.category, e.targetType, e.targetId], ["integration", "authentik_user", String(body.user.pk)]);
assert.match(e.detail ?? "", /ada/);
assert.equal(/secret-|token|write-tok|recovery\/\?/.test(e.detail ?? ""), false, "the link and the tokens are not written down");
}
});
test("what is wrong with the form is said before Authentik is asked", async () => {
seen.length = 0;
for (const bad of [{ ...valid, username: " " }, { ...valid, name: "" }, { ...valid, email: "not-an-email" }, { ...valid, groups: ["not-a-uuid"] }, { ...valid, username: "a\nb" }, { name: "x" }]) {
const res = await post(withToken, bad);
assert.equal(res.status, 400, JSON.stringify(bad));
assert.equal(typeof ((await res.json()) as { message: string }).message, "string");
}
assert.equal((await post(withToken, { ...valid, email: "" })).status, 201, "the email may be left empty");
assert.deepEqual(seen.filter((s) => !s.path.includes("/recovery/")).length, 1, "only the valid one was passed on");
});
test("an Authentik without a token for making users, a switched-off one, another kind of integration and an unknown one are not written to", async () => {
seen.length = 0;
const r1 = await post(withoutToken, valid);
assert.equal(r1.status, 400);
assert.equal(((await r1.json()) as { error: string }).error, "no_write_token");
assert.equal(((await (await post(off, valid)).json()) as { error: string }).error, "integration_disabled");
assert.equal(((await (await post(otherType, valid)).json()) as { error: string }).error, "wrong_type");
assert.equal((await post(999999, valid)).status, 404);
assert.equal((await fetch(`${base}/abc/users`, { method: "POST", headers: as("admin"), body: JSON.stringify(valid) })).status, 400);
assert.equal((await fetch(`${base}/${withoutToken}/groups`, { headers: as("admin") })).status, 400);
assert.deepEqual(seen, []);
});
test("a name that is taken is Authentik's own words; no link is asked for", async () => {
seen.length = 0;
createStatus = 400;
createAnswer = { username: ["A user with that username already exists."] };
const res = await post(withToken, valid);
assert.equal(res.status, 400);
assert.match(((await res.json()) as { message: string }).message, /already exists/);
assert.deepEqual(seen.map((s) => s.path), ["/api/v3/core/users/"]);
createStatus = 201;
createAnswer = null;
});
test("a token that is not accepted is a bad gateway, not a refusal of the form", async () => {
createStatus = 403;
createAnswer = { detail: "nope" };
const res = await post(withToken, valid);
assert.equal(res.status, 502);
assert.match(((await res.json()) as { message: string }).message, /did not accept the token/);
createStatus = 201;
createAnswer = null;
});
test("a user made without a link is said so, and the user is still written down", async () => {
recoveryStatus = 400;
recoveryAnswer = { non_field_errors: ["No recovery flow set."] };
const res = await post(withToken, { ...valid, username: "nolink" });
assert.equal(res.status, 201);
const body = (await res.json()) as { user: { pk: number }; link: string | null; linkError: string | null };
assert.equal(body.link, null);
assert.match(body.linkError ?? "", /No recovery flow set/);
const entries = (await db.select().from(auditLog)).filter((e) => e.targetId === String(body.user.pk));
assert.deepEqual(entries.map((e) => e.action), ["create_authentik_user"], "no link was made, so none is written down");
recoveryStatus = 200;
recoveryAnswer = null;
});
test("the token for making users can be taken away; the one that reads stays, and the page says it can no longer make users", async () => {
const res = await fetch(`${base}/${withToken}/write-token`, { method: "DELETE", headers: as("admin") });
assert.equal(res.status, 204);
const loaded = await loadIntegrationConfig(withToken);
assert.equal(loaded?.config.token, "read-tok");
assert.equal(loaded?.config.writeToken, undefined);
const body = (await (await fetch(base, { headers: as("viewer") })).json()) as { authentiks: { id: number; canCreateUsers: boolean }[] };
assert.equal(body.authentiks.find((a) => a.id === withToken)?.canCreateUsers, false);
seen.length = 0;
assert.equal((await post(withToken, valid)).status, 400);
assert.deepEqual(seen, []);
const entry = (await db.select().from(auditLog)).find((e) => e.action === "remove_authentik_write_token");
assert.deepEqual([entry?.category, entry?.targetType], ["integration", "integration"]);
// Again: nothing to take away, and nothing more is written down.
assert.equal((await fetch(`${base}/${withToken}/write-token`, { method: "DELETE", headers: as("admin") })).status, 204);
assert.equal((await db.select().from(auditLog)).filter((e) => e.action === "remove_authentik_write_token").length, 1);
assert.equal((await fetch(`${base}/${otherType}/write-token`, { method: "DELETE", headers: as("admin") })).status, 400);
assert.equal((await fetch(`${base}/999999/write-token`, { method: "DELETE", headers: as("admin") })).status, 404);
});
});