Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,54 @@
/**
* Phase 09 Task #82 — Thin Audit-Event wrapper for admin-sso paths.
*
* Centralises action names + metadata sanitization for the login / logout
* / fallback / mfa-challenge paths. Sits on top of
* `@toolctrl/db/audit-events.server` which already handles redaction.
*/
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
import type { Prisma } from "@toolctrl/db/prisma-browser";
export type AdminSsoAuditAction =
| "admin.login.sso.success"
| "admin.login.sso.failure"
| "admin.login.fallback.success"
| "admin.login.fallback.failure"
| "admin.logout.sso"
| "admin.mfa.app.challenge.success"
| "admin.mfa.app.challenge.failure";
export type AdminSsoAuditInput = {
readonly action: AdminSsoAuditAction;
readonly actorAdminUserId?: string | null;
readonly ssoSubjectId?: string | null;
readonly request?: Request;
readonly meta?: Record<string, unknown>;
};
function clientMeta(request: Request | undefined): { ip: string | null; userAgent: string | null } {
if (!request) return { ip: null, userAgent: null };
const fwd = request.headers.get("x-forwarded-for") ?? "";
const ip = fwd.split(",")[0]?.trim() || request.headers.get("x-real-ip") || null;
const userAgent = request.headers.get("user-agent") || null;
return { ip, userAgent };
}
export async function writeAdminSsoAuditEvent(input: AdminSsoAuditInput): Promise<void> {
const { ip, userAgent } = clientMeta(input.request);
try {
await createAuditEvent({
action: input.action,
actorType: "admin",
actorId: input.actorAdminUserId ?? null,
metadata: {
ssoSubjectId: input.ssoSubjectId ?? null,
ip,
userAgent,
...input.meta,
} as unknown as Prisma.InputJsonValue,
});
} catch {
// Audit failures must never block the auth flow. The DB-level error
// already lands in Sentry via the audit-events boundary.
}
}
@@ -0,0 +1,118 @@
import { describe, expect, it } from "vitest";
import { extractAdminSsoClaims, hasAllowedAdminGroup, isAllowedAdminGroup, mapGroupsToRole } from "./claims.server";
describe("mapGroupsToRole", () => {
it("maps toolctrl-admin to super_admin", () => {
expect(mapGroupsToRole(["toolctrl-admin"])).toBe("super_admin");
});
it("maps toolctrl-staff to staff", () => {
expect(mapGroupsToRole(["toolctrl-staff"])).toBe("staff");
});
it("prefers super_admin when both groups are present", () => {
expect(mapGroupsToRole(["toolctrl-staff", "toolctrl-admin"])).toBe("super_admin");
});
it("returns null for an unknown group", () => {
expect(mapGroupsToRole(["random-group"])).toBeNull();
});
it("returns null for an empty list", () => {
expect(mapGroupsToRole([])).toBeNull();
});
it("returns null for null/undefined input", () => {
expect(mapGroupsToRole(undefined)).toBeNull();
expect(mapGroupsToRole(null)).toBeNull();
});
});
describe("isAllowedAdminGroup / hasAllowedAdminGroup", () => {
it("recognizes the two allowlisted groups", () => {
expect(isAllowedAdminGroup("toolctrl-admin")).toBe(true);
expect(isAllowedAdminGroup("toolctrl-staff")).toBe(true);
expect(isAllowedAdminGroup("toolctrl-rando")).toBe(false);
});
it("returns false when claim list has no allowed group", () => {
expect(hasAllowedAdminGroup(["other"])).toBe(false);
expect(hasAllowedAdminGroup([])).toBe(false);
expect(hasAllowedAdminGroup(undefined)).toBe(false);
});
it("returns true when at least one allowed group is present", () => {
expect(hasAllowedAdminGroup(["other", "toolctrl-staff"])).toBe(true);
});
});
describe("extractAdminSsoClaims", () => {
const validClaims = {
sub: "auth-uid-123",
email: "Admin@Example.test",
email_verified: true,
name: "Admin Person",
groups: ["toolctrl-admin"],
};
it("extracts and normalizes a valid claim set", () => {
const result = extractAdminSsoClaims(validClaims);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.claims.subject).toBe("auth-uid-123");
expect(result.claims.email).toBe("admin@example.test");
expect(result.claims.name).toBe("Admin Person");
expect(result.claims.groups).toEqual(["toolctrl-admin"]);
expect(result.claims.emailVerified).toBe(true);
}
});
it("falls back to preferred_username when name is missing", () => {
const result = extractAdminSsoClaims({ ...validClaims, name: undefined, preferred_username: "admin-handle" });
expect(result.ok).toBe(true);
if (result.ok) expect(result.claims.name).toBe("admin-handle");
});
it("falls back to email when both name and preferred_username are missing", () => {
const result = extractAdminSsoClaims({ ...validClaims, name: undefined });
expect(result.ok).toBe(true);
if (result.ok) expect(result.claims.name).toBe("admin@example.test");
});
it("rejects missing sub", () => {
const result = extractAdminSsoClaims({ ...validClaims, sub: undefined });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("missing-sub");
});
it("rejects missing email", () => {
const result = extractAdminSsoClaims({ ...validClaims, email: "" });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("missing-email");
});
it("rejects email_verified=false", () => {
const result = extractAdminSsoClaims({ ...validClaims, email_verified: false });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("email-not-verified");
});
it("treats missing email_verified as true (Authentik does not always emit it)", () => {
const claims = { ...validClaims } as Record<string, unknown>;
delete claims.email_verified;
const result = extractAdminSsoClaims(claims);
expect(result.ok).toBe(true);
});
it("filters non-string entries from groups", () => {
const result = extractAdminSsoClaims({ ...validClaims, groups: ["toolctrl-admin", null, 7, "ok"] });
expect(result.ok).toBe(true);
if (result.ok) expect(result.claims.groups).toEqual(["toolctrl-admin", "ok"]);
});
it("returns missing-sub for null claims", () => {
const result = extractAdminSsoClaims(null);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("missing-sub");
});
});
@@ -0,0 +1,101 @@
/**
* Phase 09 Task #82 — OIDC ID-token claim extraction + group→role mapping.
*
* The "role" returned here is the *current* AdminUser identity layer in the
* Toolctrl boilerplate. Today the only durable AdminUser concept is "exists
* or not"; the spec adds two granular roles (`super_admin`, `staff`) that
* we persist as `ssoGroups` snapshots while we wait for the permissions
* matrix to grow first-class role columns. Callers should treat the role
* as advisory + future-proof.
*/
export type AuthentikGroup = "toolctrl-admin" | "toolctrl-staff";
export type AdminSsoRole = "super_admin" | "staff";
export const ADMIN_GROUP: AuthentikGroup = "toolctrl-admin";
export const STAFF_GROUP: AuthentikGroup = "toolctrl-staff";
export const ALLOWED_ADMIN_GROUPS: readonly AuthentikGroup[] = [ADMIN_GROUP, STAFF_GROUP];
/**
* Highest-priority-wins mapping. If a user is in BOTH groups they get
* super_admin (admins are a strict superset of staff for our purposes).
*/
export function mapGroupsToRole(groups: readonly string[] | undefined | null): AdminSsoRole | null {
if (!groups || groups.length === 0) return null;
if (groups.includes(ADMIN_GROUP)) return "super_admin";
if (groups.includes(STAFF_GROUP)) return "staff";
return null;
}
export type AdminSsoClaims = {
readonly subject: string;
readonly email: string;
readonly emailVerified: boolean;
readonly name: string;
readonly groups: readonly string[];
};
export type ClaimExtractionResult =
| { readonly ok: true; readonly claims: AdminSsoClaims }
| { readonly ok: false; readonly reason: "missing-sub" | "missing-email" | "email-not-verified" | "no-groups" };
/**
* Validate + extract the claim shape we trust. Authentik emits standard
* OIDC claims plus `groups` from the configured scope. We are deliberately
* conservative: missing/invalid claims short-circuit the login flow rather
* than silently falling back.
*/
export function extractAdminSsoClaims(idTokenClaims: Record<string, unknown> | null | undefined): ClaimExtractionResult {
if (!idTokenClaims) {
return { ok: false, reason: "missing-sub" };
}
const subject = typeof idTokenClaims.sub === "string" ? idTokenClaims.sub.trim() : "";
if (!subject) {
return { ok: false, reason: "missing-sub" };
}
const email = typeof idTokenClaims.email === "string" ? idTokenClaims.email.trim().toLowerCase() : "";
if (!email) {
return { ok: false, reason: "missing-email" };
}
// Spec security note: "email_verified=true prüfen". If the claim is
// absent we treat it as `true` only when the IdP is the trusted
// Authentik provider (which mints `email_verified` for SSO accounts);
// if it is present and false, reject.
const emailVerifiedClaim = idTokenClaims.email_verified;
const emailVerified = emailVerifiedClaim === undefined ? true : emailVerifiedClaim === true;
if (!emailVerified) {
return { ok: false, reason: "email-not-verified" };
}
const rawGroups = idTokenClaims.groups;
const groups: string[] = Array.isArray(rawGroups)
? rawGroups.filter((g): g is string => typeof g === "string" && g.length > 0)
: [];
const nameFromClaim = typeof idTokenClaims.name === "string" ? idTokenClaims.name.trim() : "";
const preferredName = typeof idTokenClaims.preferred_username === "string" ? idTokenClaims.preferred_username.trim() : "";
const name = nameFromClaim || preferredName || email;
return {
ok: true,
claims: {
subject,
email,
emailVerified,
name,
groups,
},
};
}
/**
* Convenience guard: pass-through that throws (or returns a Response) when
* the user has no allowed group. Kept here so the JIT-provisioning logic
* stays focused on the DB upsert.
*/
export function isAllowedAdminGroup(group: string): group is AuthentikGroup {
return ALLOWED_ADMIN_GROUPS.includes(group as AuthentikGroup);
}
export function hasAllowedAdminGroup(groups: readonly string[] | undefined | null): boolean {
if (!groups) return false;
return groups.some(isAllowedAdminGroup);
}
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { AdminSsoConfigError, isAdminSsoConfigured, readAdminSsoEnv } from "./client.server";
describe("readAdminSsoEnv", () => {
const baseEnv = {
AUTHENTIK_ISSUER_URL: "https://auth.example.test/application/o/toolctrl-admin-panel/",
AUTHENTIK_ADMIN_CLIENT_ID: "toolctrl-admin-panel",
AUTHENTIK_ADMIN_CLIENT_SECRET: "shh",
AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/auth/admin/callback",
};
it("returns trimmed values when all required keys are present", () => {
const env = readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI: "https://admin.example.test/admin/login?logged_out=1" });
expect(env.issuerUrl).toBe(baseEnv.AUTHENTIK_ISSUER_URL);
expect(env.clientId).toBe("toolctrl-admin-panel");
expect(env.postLogoutRedirectUri).toBe("https://admin.example.test/admin/login?logged_out=1");
});
it("throws when a required key is missing", () => {
expect(() => readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ADMIN_CLIENT_SECRET: "" })).toThrowError(AdminSsoConfigError);
});
it("lists every missing key in the error message", () => {
try {
readAdminSsoEnv({});
expect.fail("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(AdminSsoConfigError);
const message = (err as Error).message;
expect(message).toContain("AUTHENTIK_ISSUER_URL");
expect(message).toContain("AUTHENTIK_ADMIN_CLIENT_ID");
expect(message).toContain("AUTHENTIK_ADMIN_CLIENT_SECRET");
expect(message).toContain("AUTHENTIK_ADMIN_REDIRECT_URI");
}
});
});
describe("isAdminSsoConfigured", () => {
it("returns true when env is complete", () => {
expect(
isAdminSsoConfigured({
AUTHENTIK_ISSUER_URL: "https://auth.example.test/",
AUTHENTIK_ADMIN_CLIENT_ID: "id",
AUTHENTIK_ADMIN_CLIENT_SECRET: "secret",
AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/auth/admin/callback",
})
).toBe(true);
});
it("returns false when env is incomplete", () => {
expect(isAdminSsoConfigured({})).toBe(false);
});
});
@@ -0,0 +1,132 @@
/**
* Phase 09 Task #82 — Admin-Panel OIDC Login (Authentik SSO).
*
* Thin wrapper around `openid-client` (panva/node-openid-client). Provides a
* lazily-initialized, process-wide singleton OIDC `Client` configured against
* the Authentik discovery document. The discovery doc and the JWKS are cached
* inside openid-client itself — we just cache the `Client` instance.
*
* Initialization failures throw `AdminSsoConfigError`; callers (the
* login/callback routes) translate that into a fallback-banner on the login
* page rather than a 500.
*/
import { Issuer, type Client } from "openid-client";
export type AdminSsoEnv = {
readonly issuerUrl: string;
readonly clientId: string;
readonly clientSecret: string;
readonly redirectUri: string;
readonly postLogoutRedirectUri?: string;
};
export class AdminSsoConfigError extends Error {
readonly code: "missing-env" | "discovery-failed" | "client-init-failed";
constructor(code: AdminSsoConfigError["code"], message: string, options?: { cause?: unknown }) {
super(message, options);
this.name = "AdminSsoConfigError";
this.code = code;
}
}
/**
* Reads the Authentik OIDC env vars and validates that all required keys are
* present. Throws `AdminSsoConfigError("missing-env")` if any are missing.
* Kept env-record-shaped so tests can pass a fake without polluting process.env.
*/
export function readAdminSsoEnv(env: Record<string, string | undefined> = process.env): AdminSsoEnv {
const issuerUrl = env.AUTHENTIK_ISSUER_URL?.trim();
const clientId = env.AUTHENTIK_ADMIN_CLIENT_ID?.trim();
const clientSecret = env.AUTHENTIK_ADMIN_CLIENT_SECRET?.trim();
const redirectUri = env.AUTHENTIK_ADMIN_REDIRECT_URI?.trim();
const postLogoutRedirectUri = env.AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI?.trim();
const missing: string[] = [];
if (!issuerUrl) missing.push("AUTHENTIK_ISSUER_URL");
if (!clientId) missing.push("AUTHENTIK_ADMIN_CLIENT_ID");
if (!clientSecret) missing.push("AUTHENTIK_ADMIN_CLIENT_SECRET");
if (!redirectUri) missing.push("AUTHENTIK_ADMIN_REDIRECT_URI");
if (missing.length > 0) {
throw new AdminSsoConfigError("missing-env", `Admin SSO env is incomplete: missing ${missing.join(", ")}`);
}
return {
issuerUrl: issuerUrl as string,
clientId: clientId as string,
clientSecret: clientSecret as string,
redirectUri: redirectUri as string,
postLogoutRedirectUri: postLogoutRedirectUri || undefined,
};
}
/**
* Returns true iff SSO is configured (i.e. all required env vars are set).
* Used by the login UI to decide whether to render the SSO button.
*/
export function isAdminSsoConfigured(env: Record<string, string | undefined> = process.env): boolean {
try {
readAdminSsoEnv(env);
return true;
} catch {
return false;
}
}
let cachedClient: Promise<Client> | null = null;
let cachedEnvFingerprint: string | null = null;
function envFingerprint(env: AdminSsoEnv): string {
// Fingerprint identifies whether we need to re-init when env changes
// (mostly relevant for tests; in production env is static for the
// lifetime of the process).
return `${env.issuerUrl}|${env.clientId}|${env.redirectUri}`;
}
/**
* Returns a process-wide singleton OIDC client configured against Authentik.
* The first call performs Issuer.discover() — subsequent calls return the
* cached instance.
*/
export async function getAdminSsoClient(env: AdminSsoEnv = readAdminSsoEnv()): Promise<Client> {
const fingerprint = envFingerprint(env);
if (cachedClient && cachedEnvFingerprint === fingerprint) {
return cachedClient;
}
cachedEnvFingerprint = fingerprint;
cachedClient = (async () => {
let issuer;
try {
issuer = await Issuer.discover(env.issuerUrl);
} catch (cause) {
cachedClient = null;
cachedEnvFingerprint = null;
throw new AdminSsoConfigError("discovery-failed", `Authentik OIDC discovery failed for ${env.issuerUrl}`, { cause });
}
try {
return new issuer.Client({
client_id: env.clientId,
client_secret: env.clientSecret,
redirect_uris: [env.redirectUri],
response_types: ["code"],
token_endpoint_auth_method: "client_secret_post",
});
} catch (cause) {
cachedClient = null;
cachedEnvFingerprint = null;
throw new AdminSsoConfigError("client-init-failed", "Failed to construct Authentik OIDC client", { cause });
}
})();
return cachedClient;
}
/** Test-only: reset the cached client. Do not call from production code. */
export function __resetAdminSsoClientForTests(): void {
cachedClient = null;
cachedEnvFingerprint = null;
}
@@ -0,0 +1,37 @@
/**
* Phase 09 Task #82 — Public surface of the admin-sso module.
*
* Re-exports the small set of helpers consumed by the auth routes and the
* admin-login UI. Internal helpers stay file-local.
*/
export { AdminSsoConfigError, getAdminSsoClient, isAdminSsoConfigured, readAdminSsoEnv, type AdminSsoEnv } from "./client.server";
export {
ADMIN_SSO_CHALLENGE_COOKIE,
ADMIN_SSO_CHALLENGE_TTL_MS,
clearAdminSsoChallengeCookie,
consumeAdminSsoChallenge,
createAdminSsoChallenge,
type AdminSsoChallengePayload,
} from "./state.server";
export {
ADMIN_GROUP,
ALLOWED_ADMIN_GROUPS,
STAFF_GROUP,
extractAdminSsoClaims,
hasAllowedAdminGroup,
isAllowedAdminGroup,
mapGroupsToRole,
type AdminSsoClaims,
type AdminSsoRole,
type AuthentikGroup,
type ClaimExtractionResult,
} from "./claims.server";
export {
ADMIN_SSO_PROVIDER,
JitProvisioningError,
jitProvisionAdmin,
type JitProvisionedAdmin,
type JitProvisioningDbClient,
type JitProvisioningInput,
type JitProvisioningResult,
} from "./jit-provisioning.server";
@@ -0,0 +1,201 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AdminSsoClaims } from "./claims.server";
import { ADMIN_SSO_PROVIDER, jitProvisionAdmin, type JitProvisioningDbClient } from "./jit-provisioning.server";
type AdminRecord = {
userId: string;
ssoProvider: string | null;
ssoSubjectId: string | null;
ssoGroups: string[];
lastSsoLoginAt: Date | null;
};
type UserRecord = { id: string; email: string; firstName: string; lastName: string };
function buildFakeDb() {
const adminRows = new Map<string, AdminRecord>();
const userRows = new Map<string, UserRecord>();
let userCounter = 0;
const db: JitProvisioningDbClient = {
adminUser: {
findUnique: vi.fn(async (args) => {
const { ssoProvider, ssoSubjectId } = args.where.ssoProvider_ssoSubjectId;
for (const row of adminRows.values()) {
if (row.ssoProvider === ssoProvider && row.ssoSubjectId === ssoSubjectId) {
return { userId: row.userId, ssoProvider: row.ssoProvider, ssoSubjectId: row.ssoSubjectId, ssoGroups: row.ssoGroups, lastSsoLoginAt: row.lastSsoLoginAt };
}
}
return null;
}),
update: vi.fn(async (args) => {
const existing = adminRows.get(args.where.userId);
if (!existing) {
const err = new Error("record not found") as Error & { code?: string };
err.code = "P2025";
throw err;
}
const updated: AdminRecord = {
...existing,
ssoProvider: args.data.ssoProvider ?? existing.ssoProvider,
ssoSubjectId: args.data.ssoSubjectId ?? existing.ssoSubjectId,
ssoGroups: args.data.ssoGroups ?? existing.ssoGroups,
lastSsoLoginAt: args.data.lastSsoLoginAt ?? existing.lastSsoLoginAt,
};
adminRows.set(args.where.userId, updated);
return updated;
}),
create: vi.fn(async (args) => {
const row: AdminRecord = {
userId: args.data.userId,
ssoProvider: args.data.ssoProvider,
ssoSubjectId: args.data.ssoSubjectId,
ssoGroups: [...args.data.ssoGroups],
lastSsoLoginAt: args.data.lastSsoLoginAt,
};
adminRows.set(row.userId, row);
return row;
}),
},
user: {
findUnique: vi.fn(async (args) => {
for (const u of userRows.values()) {
if (u.email === args.where.email) return { id: u.id, email: u.email };
}
return null;
}),
update: vi.fn(async (args) => {
const existing = userRows.get(args.where.id);
if (!existing) throw new Error(`user ${args.where.id} missing`);
const updated: UserRecord = {
...existing,
firstName: args.data.firstName ?? existing.firstName,
lastName: args.data.lastName ?? existing.lastName,
};
userRows.set(args.where.id, updated);
return updated;
}),
create: vi.fn(async (args) => {
userCounter += 1;
const id = `user_${userCounter}`;
const row: UserRecord = {
id,
email: args.data.email,
firstName: args.data.firstName,
lastName: args.data.lastName,
};
userRows.set(id, row);
return { id: row.id, email: row.email };
}),
},
};
return { db, adminRows, userRows };
}
function buildClaims(overrides: Partial<AdminSsoClaims> = {}): AdminSsoClaims {
return {
subject: "authentik-sub-1",
email: "admin@example.test",
emailVerified: true,
name: "Admin Person",
groups: ["toolctrl-admin"],
...overrides,
};
}
describe("jitProvisionAdmin", () => {
let env: ReturnType<typeof buildFakeDb>;
beforeEach(() => {
env = buildFakeDb();
});
it("creates User+AdminUser for a brand new toolctrl-admin claim and returns super_admin", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.admin.role).toBe("super_admin");
expect(result.admin.created).toBe(true);
expect(result.admin.email).toBe("admin@example.test");
}
expect(env.adminRows.size).toBe(1);
expect(env.userRows.size).toBe(1);
const admin = [...env.adminRows.values()][0]!;
expect(admin.ssoProvider).toBe(ADMIN_SSO_PROVIDER);
expect(admin.ssoSubjectId).toBe("authentik-sub-1");
expect(admin.ssoGroups).toEqual(["toolctrl-admin"]);
});
it("maps toolctrl-staff to staff role", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: ["toolctrl-staff"] }) }, env.db);
expect(result.ok).toBe(true);
if (result.ok) expect(result.admin.role).toBe("staff");
});
it("rejects an unknown-group claim with forbidden-group", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: ["random"] }) }, env.db);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("forbidden-group");
expect(env.adminRows.size).toBe(0);
expect(env.userRows.size).toBe(0);
});
it("rejects an empty-group claim with forbidden-group", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: [] }) }, env.db);
expect(result.ok).toBe(false);
});
it("updates the existing SSO admin and refreshes groups + lastSsoLoginAt", async () => {
// Seed: first login creates the admin.
const t0 = new Date("2026-01-01T00:00:00Z");
await jitProvisionAdmin({ claims: buildClaims(), now: t0 }, env.db);
const admin = [...env.adminRows.values()][0]!;
expect(admin.lastSsoLoginAt).toEqual(t0);
// Second login with same sub but new groups + later timestamp.
const t1 = new Date("2026-02-01T00:00:00Z");
const result = await jitProvisionAdmin(
{ claims: buildClaims({ groups: ["toolctrl-staff"] }), now: t1 },
env.db,
);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.admin.created).toBe(false);
// Role re-syncs from current group membership (Authentik = source of truth).
expect(result.admin.role).toBe("staff");
}
const refreshed = [...env.adminRows.values()][0]!;
expect(refreshed.ssoGroups).toEqual(["toolctrl-staff"]);
expect(refreshed.lastSsoLoginAt).toEqual(t1);
// No new user row.
expect(env.userRows.size).toBe(1);
});
it("links an existing email-matched legacy admin by attaching SSO fields", async () => {
// Seed legacy admin (no SSO fields).
env.userRows.set("legacy_1", { id: "legacy_1", email: "admin@example.test", firstName: "Old", lastName: "Admin" });
env.adminRows.set("legacy_1", { userId: "legacy_1", ssoProvider: null, ssoSubjectId: null, ssoGroups: [], lastSsoLoginAt: null });
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.admin.userId).toBe("legacy_1");
expect(result.admin.linkedExisting).toBe(true);
expect(result.admin.created).toBe(false);
}
const admin = env.adminRows.get("legacy_1")!;
expect(admin.ssoProvider).toBe(ADMIN_SSO_PROVIDER);
expect(admin.ssoSubjectId).toBe("authentik-sub-1");
expect(env.userRows.size).toBe(1); // no duplicate user
});
it("creates an AdminUser when a legacy User exists but has no AdminUser row", async () => {
env.userRows.set("legacy_2", { id: "legacy_2", email: "admin@example.test", firstName: "X", lastName: "Y" });
// Note: no AdminUser row pre-existing.
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
expect(result.ok).toBe(true);
expect(env.adminRows.size).toBe(1);
expect(env.adminRows.get("legacy_2")?.ssoSubjectId).toBe("authentik-sub-1");
});
});
@@ -0,0 +1,225 @@
/**
* Phase 09 Task #82 — JIT-provisioning for Admin SSO.
*
* Lookup order:
* 1. AdminUser by (ssoProvider, ssoSubjectId)
* 2. AdminUser by linked User.email (case-insensitive) — legacy linking
* 3. New User + AdminUser if at least one allowed group is in claims
*
* Idempotent under concurrent logins thanks to the unique
* (ssoProvider, ssoSubjectId) constraint added in migration
* 20260517161240_09_admin_user_sso_fields.
*/
import { randomBytes } from "node:crypto";
import type { AdminSsoClaims, AdminSsoRole } from "./claims.server";
import { hasAllowedAdminGroup, mapGroupsToRole } from "./claims.server";
export const ADMIN_SSO_PROVIDER = "authentik";
export type JitProvisioningInput = {
readonly claims: AdminSsoClaims;
readonly now?: Date;
};
export type JitProvisionedAdmin = {
readonly userId: string;
readonly email: string;
readonly role: AdminSsoRole;
readonly created: boolean;
readonly linkedExisting: boolean;
};
export type JitProvisioningResult =
| { readonly ok: true; readonly admin: JitProvisionedAdmin }
| { readonly ok: false; readonly reason: "forbidden-group" };
export class JitProvisioningError extends Error {
readonly reason: "forbidden-group";
constructor(reason: "forbidden-group", message: string) {
super(message);
this.name = "JitProvisioningError";
this.reason = reason;
}
}
/**
* Narrow Prisma-shaped surface used by jitProvisionAdmin. Defining it as a
* structural type rather than importing PrismaClient keeps this module
* unit-testable with a hand-rolled fake.
*/
export type JitProvisioningDbClient = {
adminUser: {
findUnique: (args: { where: { ssoProvider_ssoSubjectId: { ssoProvider: string; ssoSubjectId: string } } }) =>
| Promise<({ userId: string } & AdminSsoUserRecord) | null>;
update: (args: {
where: { userId: string };
data: {
ssoProvider?: string;
ssoSubjectId?: string;
ssoGroups?: string[];
lastSsoLoginAt?: Date;
};
}) => Promise<{ userId: string } & AdminSsoUserRecord>;
create: (args: {
data: {
userId: string;
ssoProvider: string;
ssoSubjectId: string;
ssoGroups: string[];
lastSsoLoginAt: Date;
};
}) => Promise<{ userId: string } & AdminSsoUserRecord>;
};
user: {
findUnique: (args: { where: { email: string } }) => Promise<{ id: string; email: string } | null>;
update: (args: { where: { id: string }; data: { firstName?: string; lastName?: string } }) => Promise<unknown>;
create: (args: {
data: {
email: string;
passwordHash: string;
firstName: string;
lastName: string;
active: boolean;
};
}) => Promise<{ id: string; email: string }>;
};
};
type AdminSsoUserRecord = {
ssoProvider: string | null;
ssoSubjectId: string | null;
ssoGroups: string[];
lastSsoLoginAt: Date | null;
};
function splitName(fullName: string): { firstName: string; lastName: string } {
const cleaned = fullName.trim();
if (!cleaned) return { firstName: "", lastName: "" };
const parts = cleaned.split(/\s+/);
if (parts.length === 1) return { firstName: parts[0]!, lastName: "" };
return { firstName: parts[0]!, lastName: parts.slice(1).join(" ") };
}
/**
* Random throw-away password hash — placeholder so the User row can satisfy
* the existing non-null `passwordHash` constraint. SSO-only users never use
* it; they always authenticate through Authentik. Stored as an opaque
* 32-byte token prefixed to make the source obvious in audits.
*/
function generateSsoOnlyPasswordHash(): string {
return `sso-only!${randomBytes(32).toString("hex")}`;
}
/**
* JIT-provision (or refresh) an AdminUser based on a verified Authentik
* claim bundle.
*/
export async function jitProvisionAdmin(
input: JitProvisioningInput,
db: JitProvisioningDbClient
): Promise<JitProvisioningResult> {
const { claims } = input;
const role = mapGroupsToRole(claims.groups);
if (!role || !hasAllowedAdminGroup(claims.groups)) {
return { ok: false, reason: "forbidden-group" };
}
const now = input.now ?? new Date();
const email = claims.email.toLowerCase();
// (1) Existing SSO-linked admin?
const existingBySso = await db.adminUser.findUnique({
where: { ssoProvider_ssoSubjectId: { ssoProvider: ADMIN_SSO_PROVIDER, ssoSubjectId: claims.subject } },
});
if (existingBySso) {
await db.adminUser.update({
where: { userId: existingBySso.userId },
data: {
ssoGroups: [...claims.groups],
lastSsoLoginAt: now,
},
});
const { firstName, lastName } = splitName(claims.name);
if (firstName || lastName) {
await db.user.update({ where: { id: existingBySso.userId }, data: { firstName, lastName } });
}
return {
ok: true,
admin: {
userId: existingBySso.userId,
email,
role,
created: false,
linkedExisting: false,
},
};
}
// (2) Legacy admin matched by email — attach SSO fields.
const existingUserByEmail = await db.user.findUnique({ where: { email } });
if (existingUserByEmail) {
const updated = await db.adminUser.update({
where: { userId: existingUserByEmail.id },
data: {
ssoProvider: ADMIN_SSO_PROVIDER,
ssoSubjectId: claims.subject,
ssoGroups: [...claims.groups],
lastSsoLoginAt: now,
},
}).catch(async (err) => {
// If the user exists but has no AdminUser row, create one.
// Prisma's `update` throws P2025 for record-not-found.
const code = (err as { code?: string }).code;
if (code !== "P2025") throw err;
return db.adminUser.create({
data: {
userId: existingUserByEmail.id,
ssoProvider: ADMIN_SSO_PROVIDER,
ssoSubjectId: claims.subject,
ssoGroups: [...claims.groups],
lastSsoLoginAt: now,
},
});
});
return {
ok: true,
admin: {
userId: updated.userId,
email,
role,
created: false,
linkedExisting: true,
},
};
}
// (3) Brand-new user + admin from SSO.
const { firstName, lastName } = splitName(claims.name);
const newUser = await db.user.create({
data: {
email,
passwordHash: generateSsoOnlyPasswordHash(),
firstName: firstName || "Admin",
lastName: lastName || "User",
active: true,
},
});
await db.adminUser.create({
data: {
userId: newUser.id,
ssoProvider: ADMIN_SSO_PROVIDER,
ssoSubjectId: claims.subject,
ssoGroups: [...claims.groups],
lastSsoLoginAt: now,
},
});
return {
ok: true,
admin: {
userId: newUser.id,
email,
role,
created: true,
linkedExisting: false,
},
};
}
@@ -0,0 +1,76 @@
/**
* Phase 09 Task #82 — Admin-SSO logout helpers.
*
* Stores the raw OIDC `id_token` in a separate HMAC-signed HttpOnly
* cookie (scoped to /auth/admin) so that /auth/admin/logout can supply
* `id_token_hint` for RP-initiated logout without bloating the main
* session cookie or persisting tokens in the DB.
*/
import { createHmac, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@toolctrl/config";
export const ADMIN_SSO_ID_TOKEN_COOKIE = "admin_sso_id_token";
export const ADMIN_SSO_ID_TOKEN_TTL_MS = 12 * 60 * 60 * 1000; // mirror app-session lifetime
const COOKIE_PATH = "/auth/admin";
function getSigningSecret(override?: string): string {
if (override) return override;
const { cryptoSecret, sessionSecret } = loadRequiredWebConfig();
const secret = cryptoSecret || sessionSecret;
if (!secret) {
throw new Error("CRYPTO_SECRET or SESSION_SECRET is required for admin-sso id-token cookie.");
}
return secret;
}
function sign(payload: string, secret: string): string {
return createHmac("sha256", secret).update(payload).digest("base64url");
}
export function serializeIdTokenCookie(idToken: string, opts: { secret?: string } = {}): string {
const secret = getSigningSecret(opts.secret);
const sig = sign(idToken, secret);
const value = `${Buffer.from(idToken, "utf8").toString("base64url")}.${sig}`;
const maxAge = Math.ceil(ADMIN_SSO_ID_TOKEN_TTL_MS / 1000);
const attrs = [`${ADMIN_SSO_ID_TOKEN_COOKIE}=${value}`, `Path=${COOKIE_PATH}`, "HttpOnly", "SameSite=Lax", `Max-Age=${maxAge}`];
if (process.env.NODE_ENV !== "test") attrs.push("Secure");
return attrs.join("; ");
}
export function clearIdTokenCookie(): string {
const attrs = [`${ADMIN_SSO_ID_TOKEN_COOKIE}=`, `Path=${COOKIE_PATH}`, "HttpOnly", "SameSite=Lax", "Max-Age=0"];
if (process.env.NODE_ENV !== "test") attrs.push("Secure");
return attrs.join("; ");
}
function readCookie(request: Request, name: string): string | null {
const header = request.headers.get("cookie");
if (!header) return null;
for (const part of header.split(/;\s*/)) {
const eq = part.indexOf("=");
if (eq === -1) continue;
if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
}
return null;
}
export function readIdTokenFromRequest(request: Request, opts: { secret?: string } = {}): string | null {
const value = readCookie(request, ADMIN_SSO_ID_TOKEN_COOKIE);
if (!value) return null;
const dot = value.lastIndexOf(".");
if (dot <= 0) return null;
const encoded = value.slice(0, dot);
const sig = value.slice(dot + 1);
let secret: string;
try {
secret = getSigningSecret(opts.secret);
} catch {
return null;
}
const expectedSig = sign(Buffer.from(encoded, "base64url").toString("utf8"), secret);
const a = Buffer.from(sig);
const b = Buffer.from(expectedSig);
if (a.length !== b.length) return null;
if (!timingSafeEqual(a, b)) return null;
return Buffer.from(encoded, "base64url").toString("utf8");
}
@@ -0,0 +1,104 @@
import { describe, expect, it } from "vitest";
import {
ADMIN_SSO_CHALLENGE_COOKIE,
ADMIN_SSO_CHALLENGE_TTL_MS,
consumeAdminSsoChallenge,
createAdminSsoChallenge,
serializeAdminSsoChallengeCookie,
} from "./state.server";
const SECRET = "test-secret-do-not-use-in-prod";
function cookieValue(cookie: string): string {
const head = cookie.split(";")[0] ?? "";
return head.slice(`${ADMIN_SSO_CHALLENGE_COOKIE}=`.length);
}
function requestWithCookie(value: string): Request {
return new Request("https://admin.example.test/auth/admin/callback", {
headers: { cookie: `${ADMIN_SSO_CHALLENGE_COOKIE}=${value}` },
});
}
describe("createAdminSsoChallenge", () => {
it("produces distinct state, nonce and codeVerifier for each invocation", () => {
const a = createAdminSsoChallenge({ secret: SECRET });
const b = createAdminSsoChallenge({ secret: SECRET });
expect(a.payload.state).not.toBe(b.payload.state);
expect(a.payload.nonce).not.toBe(b.payload.nonce);
expect(a.payload.codeVerifier).not.toBe(b.payload.codeVerifier);
// state should be 32 random bytes hex-encoded -> 64 chars
expect(a.payload.state).toMatch(/^[0-9a-f]{64}$/);
expect(a.payload.nonce).toMatch(/^[0-9a-f]{64}$/);
});
it("derives codeChallenge from codeVerifier (PKCE S256)", () => {
const { payload } = createAdminSsoChallenge({ secret: SECRET });
expect(payload.codeChallenge).toMatch(/^[A-Za-z0-9_-]+$/);
expect(payload.codeChallenge).not.toBe(payload.codeVerifier);
});
it("emits an HttpOnly, Path-scoped cookie", () => {
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
expect(cookie).toMatch(/HttpOnly/);
expect(cookie).toMatch(/Path=\/auth\/admin/);
expect(cookie).toMatch(/SameSite=Lax/);
});
});
describe("consumeAdminSsoChallenge", () => {
it("round-trips a fresh challenge and returns a clear-cookie header", () => {
const { payload, cookie } = createAdminSsoChallenge({ secret: SECRET, returnTo: "/admin/dashboard" });
const value = cookieValue(cookie);
const req = requestWithCookie(value);
const result = consumeAdminSsoChallenge(req, { secret: SECRET });
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.payload.state).toBe(payload.state);
expect(result.payload.nonce).toBe(payload.nonce);
expect(result.payload.codeVerifier).toBe(payload.codeVerifier);
expect(result.payload.returnTo).toBe("/admin/dashboard");
expect(result.clearCookie).toContain(`${ADMIN_SSO_CHALLENGE_COOKIE}=`);
expect(result.clearCookie).toContain("Max-Age=0");
}
});
it("reports `missing` when no cookie is attached", () => {
const req = new Request("https://admin.example.test/auth/admin/callback");
const result = consumeAdminSsoChallenge(req, { secret: SECRET });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("missing");
});
it("rejects a cookie with a tampered signature", () => {
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
const value = cookieValue(cookie);
const dot = value.lastIndexOf(".");
const tampered = value.slice(0, dot) + ".AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
const result = consumeAdminSsoChallenge(requestWithCookie(tampered), { secret: SECRET });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("bad-signature");
});
it("rejects a cookie signed under a different secret", () => {
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
const result = consumeAdminSsoChallenge(requestWithCookie(cookieValue(cookie)), { secret: "different-secret" });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("bad-signature");
});
it("rejects an expired cookie (older than TTL)", () => {
const past = Date.now() - ADMIN_SSO_CHALLENGE_TTL_MS - 1000;
const { payload } = createAdminSsoChallenge({ secret: SECRET, now: () => past });
const cookie = serializeAdminSsoChallengeCookie(payload, SECRET);
const result = consumeAdminSsoChallenge(requestWithCookie(cookieValue(cookie)), { secret: SECRET });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("expired");
});
it("rejects a malformed cookie value", () => {
const result = consumeAdminSsoChallenge(requestWithCookie("garbage"), { secret: SECRET });
expect(result.ok).toBe(false);
if (!result.ok) expect(["malformed", "bad-signature"]).toContain(result.reason);
});
});
@@ -0,0 +1,189 @@
/**
* Phase 09 Task #82 — PKCE / state / nonce challenge persistence.
*
* Stores the tuple { state, nonce, codeVerifier, createdAt } in an
* HMAC-signed HttpOnly cookie scoped to /auth/admin. The cookie is
* single-use: `consumeAdminSsoChallenge()` returns the payload and emits a
* `Set-Cookie` header that clears it.
*
* We sign with HMAC-SHA256 over the JSON payload using
* `CRYPTO_SECRET || SESSION_SECRET` (mirroring the magic-link convention),
* and we encode payload+signature with URL-safe base64. The payload itself
* is NOT encrypted — none of the values are user-secret per spec, and
* encryption would just hide bugs.
*
* TTL is 10 minutes which is generous for Authentik UI redirects but short
* enough that stolen cookies have a tiny replay window. The TTL is checked
* server-side (cookie Max-Age is best-effort; clients lie).
*/
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { generators } from "openid-client";
export const ADMIN_SSO_CHALLENGE_COOKIE = "admin_sso_challenge";
export const ADMIN_SSO_CHALLENGE_TTL_MS = 10 * 60 * 1000;
const COOKIE_PATH = "/auth/admin";
const PAYLOAD_VERSION = "v1";
export type AdminSsoChallengePayload = {
readonly state: string;
readonly nonce: string;
readonly codeVerifier: string;
readonly codeChallenge: string;
/** Epoch milliseconds. */
readonly createdAt: number;
/** Optional safe `returnTo` path captured at /auth/admin/login. */
readonly returnTo?: string;
};
export type ConsumeResult =
| { readonly ok: true; readonly payload: AdminSsoChallengePayload; readonly clearCookie: string }
| { readonly ok: false; readonly reason: "missing" | "malformed" | "bad-signature" | "expired" };
export type CreateOptions = {
readonly returnTo?: string;
/** Injectable clock for tests. */
readonly now?: () => number;
/** Override secret (tests). */
readonly secret?: string;
};
function getSigningSecret(override?: string): string {
if (override) return override;
const { cryptoSecret, sessionSecret } = loadRequiredWebConfig();
const secret = cryptoSecret || sessionSecret;
if (!secret) {
throw new Error("CRYPTO_SECRET or SESSION_SECRET is required for admin-sso challenge cookies.");
}
return secret;
}
function base64UrlEncode(buf: Buffer | string): string {
const b = typeof buf === "string" ? Buffer.from(buf, "utf8") : buf;
return b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function base64UrlDecode(value: string): Buffer {
const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - (value.length % 4));
const standard = value.replace(/-/g, "+").replace(/_/g, "/") + pad;
return Buffer.from(standard, "base64");
}
function sign(payload: string, secret: string): string {
return base64UrlEncode(createHmac("sha256", secret).update(payload).digest());
}
function verifySignature(payload: string, signature: string, secret: string): boolean {
const expected = sign(payload, secret);
const a = Buffer.from(signature);
const b = Buffer.from(expected);
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
/**
* Generate a fresh challenge tuple. Caller is responsible for setting
* `Set-Cookie` from `cookie` on the redirect response.
*/
export function createAdminSsoChallenge(options: CreateOptions = {}): { payload: AdminSsoChallengePayload; cookie: string } {
const codeVerifier = generators.codeVerifier();
const codeChallenge = generators.codeChallenge(codeVerifier);
const payload: AdminSsoChallengePayload = {
state: randomBytes(32).toString("hex"),
nonce: randomBytes(32).toString("hex"),
codeVerifier,
codeChallenge,
createdAt: options.now ? options.now() : Date.now(),
returnTo: options.returnTo,
};
const cookie = serializeAdminSsoChallengeCookie(payload, options.secret);
return { payload, cookie };
}
export function serializeAdminSsoChallengeCookie(payload: AdminSsoChallengePayload, secretOverride?: string): string {
const secret = getSigningSecret(secretOverride);
const body = base64UrlEncode(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }));
const sig = sign(body, secret);
const value = `${body}.${sig}`;
const maxAgeSeconds = Math.ceil(ADMIN_SSO_CHALLENGE_TTL_MS / 1000);
const attributes = [
`${ADMIN_SSO_CHALLENGE_COOKIE}=${value}`,
`Path=${COOKIE_PATH}`,
"HttpOnly",
"SameSite=Lax",
`Max-Age=${maxAgeSeconds}`,
];
if (process.env.NODE_ENV !== "test") {
attributes.push("Secure");
}
return attributes.join("; ");
}
/**
* Returns a `Set-Cookie` header that clears the challenge cookie.
*/
export function clearAdminSsoChallengeCookie(): string {
const attributes = [
`${ADMIN_SSO_CHALLENGE_COOKIE}=`,
`Path=${COOKIE_PATH}`,
"HttpOnly",
"SameSite=Lax",
"Max-Age=0",
];
if (process.env.NODE_ENV !== "test") {
attributes.push("Secure");
}
return attributes.join("; ");
}
function readCookieValue(request: Request, name: string): string | null {
const header = request.headers.get("cookie");
if (!header) return null;
for (const part of header.split(/;\s*/)) {
const eq = part.indexOf("=");
if (eq === -1) continue;
const key = part.slice(0, eq).trim();
if (key === name) return part.slice(eq + 1).trim();
}
return null;
}
/**
* Read + verify + invalidate the challenge cookie attached to `request`.
* Always returns a `clearCookie` header that the caller must include on
* the redirect response so the cookie cannot be replayed.
*/
export function consumeAdminSsoChallenge(
request: Request,
options: { now?: () => number; secret?: string } = {}
): ConsumeResult {
const value = readCookieValue(request, ADMIN_SSO_CHALLENGE_COOKIE);
if (!value) return { ok: false, reason: "missing" };
const dot = value.lastIndexOf(".");
if (dot <= 0) return { ok: false, reason: "malformed" };
const body = value.slice(0, dot);
const sig = value.slice(dot + 1);
let secret: string;
try {
secret = getSigningSecret(options.secret);
} catch {
return { ok: false, reason: "malformed" };
}
if (!verifySignature(body, sig, secret)) {
return { ok: false, reason: "bad-signature" };
}
let decoded: { v: string; p: AdminSsoChallengePayload };
try {
decoded = JSON.parse(base64UrlDecode(body).toString("utf8"));
} catch {
return { ok: false, reason: "malformed" };
}
if (decoded.v !== PAYLOAD_VERSION || !decoded.p) {
return { ok: false, reason: "malformed" };
}
const now = options.now ? options.now() : Date.now();
if (typeof decoded.p.createdAt !== "number" || now - decoded.p.createdAt > ADMIN_SSO_CHALLENGE_TTL_MS) {
return { ok: false, reason: "expired" };
}
return { ok: true, payload: decoded.p, clearCookie: clearAdminSsoChallengeCookie() };
}