/** * Roles from sign-in groups: reading the claim, the rules, what happens to people at sign-in, and the Users routes around it. * * Run with: npm test --workspace server */ import { test, describe, before, after } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { AddressInfo } from "node:net"; import type { Server } from "node:http"; const dir = mkdtempSync(join(tmpdir(), "hm-groups-")); process.env.DATABASE_PATH = join(dir, "test.sqlite"); process.env.SESSION_DIR = join(dir, "sessions"); process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); const express = (await import("express")).default; const { db } = await import("../src/db/client.js"); const { users } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { extractGroups, roleFromGroups } = await import("../src/auth/groups.js"); const { upsertUserFromLogin } = await import("../src/auth/users.js"); const { usersRouter } = await import("../src/routes/users.js"); const { updateSettings } = await import("../src/services/settingsStore.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); const rules = { roleFromGroups: true, groupsClaim: "groups", adminGroups: ["homelab-admins"], operatorGroups: ["homelab-ops"], otherwise: "viewer" as const }; describe("reading the groups out of a sign-in", () => { test("from any place the provider put them, as a list or a single name", () => { assert.deepEqual(extractGroups([{ groups: ["a", "b"] }], "groups"), ["a", "b"]); assert.deepEqual(extractGroups([{ groups: "solo" }], "groups"), ["solo"]); assert.deepEqual(extractGroups([{ sub: "x" }, { groups: ["u"] }], "groups"), ["u"], "the user-info answer counts too"); assert.deepEqual(extractGroups([{ groups: ["a", "b"] }, { groups: ["b", "c"] }], "groups"), ["a", "b", "c"], "joined, without repeats"); assert.deepEqual(extractGroups([{ roles: ["x"] }], "roles"), ["x"], "a claim of another name"); assert.deepEqual(extractGroups([{ groups: [" padded ", "", 5, null, "ok"] }], "groups"), ["padded", "ok"], "only real names"); }); test("not being told is not the same as being in no groups", () => { assert.equal(extractGroups([{ sub: "x" }], "groups"), null); assert.equal(extractGroups([{ groups: null }], "groups"), null); assert.deepEqual(extractGroups([{ groups: [] }], "groups"), [], "an empty list is an answer"); assert.equal(extractGroups([], "groups"), null); }); }); describe("the rules", () => { test("admin beats operator, names ignore case and spaces, and the rest get what 'otherwise' says", () => { assert.equal(roleFromGroups(rules, ["homelab-ops", "homelab-admins"], "viewer"), "admin"); assert.equal(roleFromGroups(rules, ["HomeLab-Ops "], "viewer"), "operator"); assert.equal(roleFromGroups(rules, ["cooks"], "operator"), "viewer"); assert.equal(roleFromGroups(rules, [], "admin"), "viewer"); assert.equal(roleFromGroups({ ...rules, otherwise: "keep" }, ["cooks"], "operator"), "operator"); assert.equal(roleFromGroups({ ...rules, adminGroups: [], operatorGroups: [] }, ["homelab-admins"], "viewer"), "viewer", "no groups named, no role from them"); }); }); describe("at sign-in", () => { const login = (sub: string, groups: string[] | null | undefined) => upsertUserFromLogin({ sub, email: `${sub}@lab`, name: sub, groups }); const roleOf = async (sub: string) => (await db.select().from(users).where(eq(users.oidcSub, sub)))[0].role; test("with the rules off, groups are remembered but roles stay as they are", async () => { const first = await login("founder", ["homelab-ops"]); assert.equal(first.user.role, "admin", "the first person ever is the administrator"); assert.deepEqual(JSON.parse(first.user.groups!), ["homelab-ops"]); const second = await login("sam", ["homelab-admins"]); assert.equal(second.user.role, "viewer"); assert.equal(second.roleChange, undefined); assert.equal((await login("sam", ["homelab-admins"])).user.role, "viewer", "and again on the next sign-in"); }); test("with the rules on, a new person's groups decide, and the first person is still the administrator", async () => { await updateSettings({ signIn: rules }); assert.equal((await login("olga", ["homelab-ops"])).user.role, "operator"); assert.equal((await login("nobody", ["cooks"])).user.role, "viewer"); assert.equal((await login("quiet", [])).user.role, "viewer"); assert.equal((await login("unknown", null)).user.role, "viewer", "no groups reported: viewer, as before"); }); test("an existing person's role follows their groups, and says what changed", async () => { const up = await login("sam", ["homelab-ops"]); assert.equal(up.user.role, "operator"); assert.deepEqual(up.roleChange, { from: "viewer", to: "operator", groups: ["homelab-ops"] }); const again = await login("sam", ["homelab-ops"]); assert.equal(again.roleChange, undefined, "nothing to say when nothing changed"); const down = await login("sam", ["cooks"]); assert.equal(down.user.role, "viewer"); assert.equal(down.roleChange?.from, "operator"); }); test("a sign-in that carries no groups leaves roles alone, so a wrong claim name can't demote anyone", async () => { await login("sam", ["homelab-admins"]); assert.equal(await roleOf("sam"), "admin"); const blind = await login("sam", null); assert.equal(blind.roleChange, undefined); assert.equal(await roleOf("sam"), "admin"); assert.equal(await roleOf("founder"), "admin"); await login("founder", undefined); assert.equal(await roleOf("founder"), "admin"); }); test("the last administrator is never demoted by a group rule", async () => { // sam and founder are both admins now; demoting one is allowed… const d1 = await login("sam", ["cooks"]); assert.equal(d1.user.role, "viewer"); // …but not the other, who is the last. const d2 = await login("founder", ["cooks"]); assert.equal(d2.user.role, "admin"); assert.equal(d2.roleChange?.blocked, true); assert.equal(await roleOf("founder"), "admin"); }); test("'keep' leaves people in no named group as they are", async () => { await updateSettings({ signIn: { ...rules, otherwise: "keep" } }); await login("olga", ["cooks"]); assert.equal(await roleOf("olga"), "operator"); await updateSettings({ signIn: { ...rules, otherwise: "viewer" } }); }); }); describe("the Users routes", () => { let app: Server; let base = ""; before(async () => { await db.update(users).set({ role: "admin" }).where(eq(users.oidcSub, "founder")); const a = express(); a.use(express.json()); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub: "founder" } }; next(); }); a.use("/api/users", usersRouter); app = await new Promise((resolve) => { const s = a.listen(0, "127.0.0.1", () => resolve(s)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/users`; }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); const send = (method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }); test("the list carries each person's groups and says whether roles follow them; nothing else leaks", async () => { const body = await (await send("GET", "/")).json(); assert.equal(body.rolesFollowGroups, true); const olga = body.users.find((u: { name: string }) => u.name === "olga"); assert.deepEqual(olga.groups, ["cooks"]); assert.deepEqual(Object.keys(olga).sort(), ["avatarUrl", "createdAt", "email", "groups", "id", "lastLoginAt", "name", "oidcSub", "role"]); assert.equal(olga.avatarUrl, null, "no picture source is on, so none to look for"); }); test("a role can't be set by hand while groups decide it", async () => { const olga = (await db.select().from(users).where(eq(users.oidcSub, "olga")))[0]; const res = await send("PATCH", `/${olga.id}/role`, { role: "viewer" }); assert.equal(res.status, 409); assert.equal((await res.json()).error, "managed_by_groups"); await updateSettings({ signIn: { roleFromGroups: false } }); assert.equal((await send("PATCH", `/${olga.id}/role`, { role: "viewer" })).status, 200, "and it can again once they don't"); }); test("the preview says what each person would be, and warns when nobody would be an administrator", async () => { await db.update(users).set({ groups: JSON.stringify(["homelab-admins"]) }).where(eq(users.oidcSub, "founder")); const ok = await (await send("POST", "/preview-group-roles", { adminGroups: ["homelab-admins"] })).json(); assert.equal(ok.people.find((p: { name: string }) => p.name === "founder").wouldBe, "admin"); assert.equal(ok.adminsAfter, 1); const locked = await (await send("POST", "/preview-group-roles", { adminGroups: ["a-group-nobody-is-in"] })).json(); assert.equal(locked.adminsAfter, 0, "that rule would leave no administrator"); assert.equal(locked.people.find((p: { name: string }) => p.name === "founder").wouldBe, "viewer"); const never = locked.people.find((p: { name: string }) => p.name === "unknown"); assert.equal(never.groups, null); assert.equal(never.wouldBe, null, "someone who has never signed in with groups can't be told"); assert.equal((await send("POST", "/preview-group-roles", { adminGroups: "nope" })).status, 400); }); });