268 lines
10 KiB
TypeScript
268 lines
10 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
|
|
import { Prisma } from "../generated/prisma/client/client.js";
|
|
|
|
import { getAuthentikAdminJitDbClient, getDbClient, type DbClient } from "./client.server.js";
|
|
import { buildAuditEventCreateData, buildAuditEventHashPayload, type AuditEventInput } from "./audit-events.server.js";
|
|
import { computeAuditHash } from "./audit-hash.js";
|
|
import { computeAuditChainHeadMac, verifyAuditChainHead, type AuditChainHeadRecord } from "./audit-chain-checkpoint.server.js";
|
|
|
|
export const AUTHENTIK_ADMIN_SSO_PROVIDER = "authentik" as const;
|
|
export const AUTHENTIK_ADMIN_GROUPS = ["hivegrid-admin", "hivegrid-staff"] as const;
|
|
|
|
export type AdminSsoRlsIdentity = {
|
|
resourceId: string;
|
|
userId: string;
|
|
};
|
|
|
|
export type AuthentikAdminBindingInput = {
|
|
subject: string;
|
|
email: string;
|
|
emailVerified: boolean;
|
|
groups: readonly string[];
|
|
firstName: string;
|
|
lastName: string;
|
|
locale?: string | null;
|
|
loginAt: Date;
|
|
};
|
|
|
|
type AdminIdentityBindingRow = {
|
|
admin_user_id: string | null;
|
|
subject_bound: boolean | null;
|
|
};
|
|
|
|
export class AdminIdentityNotPreparedError extends Error {
|
|
readonly code = "ADMIN_IDENTITY_NOT_PREPARED";
|
|
|
|
constructor() {
|
|
super("No active prepared AdminUser matches the verified Authentik email");
|
|
this.name = "AdminIdentityNotPreparedError";
|
|
}
|
|
}
|
|
|
|
export async function resolveAuthentikAdminIdentity(
|
|
subject: string,
|
|
client: AdminSsoRlsClient = getDbClient()
|
|
): Promise<{ adminUserId: string } | null> {
|
|
const normalizedSubject = normalizeIdentifier(subject, 2_048);
|
|
if (!normalizedSubject) return null;
|
|
const rows = await client.$queryRaw<Array<{ admin_user_id: string | null }>>(
|
|
Prisma.sql`SELECT user_id AS admin_user_id FROM public.hivegrid_resolve_admin_sso_identity_v2(${normalizedSubject})`
|
|
);
|
|
if (rows.length === 0) return null;
|
|
if (rows.length !== 1) throw new Error("Admin SSO resolver returned an ambiguous identity");
|
|
const adminUserId = normalizeIdentifier(rows[0]?.admin_user_id ?? "", 191);
|
|
if (!adminUserId) throw new Error("Admin SSO resolver returned an invalid identity");
|
|
return { adminUserId };
|
|
}
|
|
|
|
export async function bindPreparedAuthentikAdminIdentity(
|
|
input: AuthentikAdminBindingInput,
|
|
client: AdminSsoRlsClient = getAuthentikAdminJitDbClient()
|
|
): Promise<{ adminUserId: string; newSubjectBinding: boolean }> {
|
|
const subject = requireIdentifier(input.subject, "subject", 2_048);
|
|
const email = requireEmail(input.email);
|
|
const groups = normalizeGroups(input.groups);
|
|
const firstName = requireIdentifier(input.firstName, "firstName", 200);
|
|
const lastName = normalizeIdentifier(input.lastName, 200) ?? "";
|
|
const locale = input.locale ? normalizeIdentifier(input.locale, 20) : null;
|
|
if (!input.emailVerified) throw new Error("Admin SSO binding requires a verified email");
|
|
if (!groups.some((group) => AUTHENTIK_ADMIN_GROUPS.includes(group as (typeof AUTHENTIK_ADMIN_GROUPS)[number]))) {
|
|
throw new Error("Admin SSO binding requires an allowed operator group");
|
|
}
|
|
if (!(input.loginAt instanceof Date) || Number.isNaN(input.loginAt.getTime())) {
|
|
throw new Error("Admin SSO binding login timestamp is invalid");
|
|
}
|
|
const groupValues = Prisma.join(groups.map((group) => Prisma.sql`${group}`));
|
|
const rows = await client.$queryRaw<AdminIdentityBindingRow[]>(
|
|
Prisma.sql`SELECT admin_user_id, subject_bound
|
|
FROM public.hivegrid_bind_prepared_authentik_admin_v3(
|
|
${subject}, ${email}, ${input.emailVerified}, ARRAY[${groupValues}]::text[],
|
|
${firstName}, ${lastName}, ${locale}, ${input.loginAt}
|
|
)`
|
|
);
|
|
if (rows.length === 0) throw new AdminIdentityNotPreparedError();
|
|
if (rows.length !== 1) throw new Error("Admin SSO binding capability returned an invalid result");
|
|
const adminUserId = normalizeIdentifier(rows[0]?.admin_user_id ?? "", 191);
|
|
if (!adminUserId || typeof rows[0]?.subject_bound !== "boolean") {
|
|
throw new Error("Admin SSO binding capability returned an invalid identity");
|
|
}
|
|
return { adminUserId, newSubjectBinding: rows[0].subject_bound };
|
|
}
|
|
|
|
type AdminSsoRlsClient = Pick<DbClient, "$queryRaw">;
|
|
|
|
type AdminSsoAuditHeadRow = {
|
|
event_id: string | null;
|
|
event_hash: string | null;
|
|
event_created_at: Date | string | null;
|
|
head_mac: string | null;
|
|
};
|
|
|
|
type AdminSsoAuditAppendRow = {
|
|
event_id: string | null;
|
|
};
|
|
|
|
type AdminSsoAuditRawClient = Pick<DbClient, "$queryRaw">;
|
|
|
|
type AdminSsoAuditClient = AdminSsoAuditRawClient & {
|
|
$transaction<T>(runner: (transaction: AdminSsoAuditRawClient) => Promise<T>, options?: { timeout?: number }): Promise<T>;
|
|
};
|
|
|
|
const ADMIN_SSO_AUDIT_ACTIONS = new Set([
|
|
"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",
|
|
]);
|
|
|
|
/**
|
|
* Compatibility wrapper for callers not yet renamed to the v2 API. It resolves
|
|
* only the tenant-less AdminUser id and never touches a tenant User.
|
|
*/
|
|
export async function resolveAuthentikAdminSsoIdentity(
|
|
provider: string,
|
|
subject: string,
|
|
client: AdminSsoRlsClient = getDbClient()
|
|
): Promise<AdminSsoRlsIdentity | null> {
|
|
if (provider !== AUTHENTIK_ADMIN_SSO_PROVIDER) return null;
|
|
const identity = await resolveAuthentikAdminIdentity(subject, client);
|
|
return identity ? { resourceId: identity.adminUserId, userId: identity.adminUserId } : null;
|
|
}
|
|
|
|
/**
|
|
* Appends a platform Admin-SSO audit event before an operator identity exists.
|
|
* A first capability acquires the platform-chain transaction lock and exposes
|
|
* only its authenticated head. A second capability validates the fixed action
|
|
* vocabulary and atomically advances AuditEvent plus AuditChainHead.
|
|
*/
|
|
export async function appendPreauthAdminSsoAuditEvent(
|
|
input: AuditEventInput,
|
|
client: AdminSsoAuditClient = getDbClient() as unknown as AdminSsoAuditClient
|
|
): Promise<void> {
|
|
if (!ADMIN_SSO_AUDIT_ACTIONS.has(input.action)) {
|
|
throw new Error("Admin SSO audit action is not allowed");
|
|
}
|
|
const data = buildAuditEventCreateData({
|
|
...input,
|
|
tenantId: null,
|
|
actorType: "admin",
|
|
sourceModule: "admin-sso",
|
|
});
|
|
|
|
await client.$transaction(
|
|
async (transaction) => {
|
|
const heads = await transaction.$queryRaw<AdminSsoAuditHeadRow[]>(
|
|
Prisma.sql`SELECT event_id, event_hash, event_created_at, head_mac FROM public.hivegrid_lock_admin_sso_audit_head()`
|
|
);
|
|
if (heads.length > 1) {
|
|
throw new Error("Admin SSO audit head capability returned an ambiguous chain");
|
|
}
|
|
|
|
const head = heads[0] ?? null;
|
|
const previousHash = normalizeOptionalHash(head?.event_hash);
|
|
const previousCreatedAt = normalizeOptionalDate(head?.event_created_at);
|
|
if (head?.head_mac) {
|
|
const eventId = normalizeIdentifier(head.event_id ?? "", 191);
|
|
if (!eventId || !previousHash || !previousCreatedAt) {
|
|
throw new Error("Admin SSO audit head capability returned an invalid chain");
|
|
}
|
|
const persistedHead: AuditChainHeadRecord = {
|
|
chainKey: "platform",
|
|
tenantId: null,
|
|
eventId,
|
|
eventHash: previousHash,
|
|
eventCreatedAt: previousCreatedAt,
|
|
headMac: head.head_mac,
|
|
};
|
|
if (!verifyAuditChainHead(persistedHead)) {
|
|
throw new Error("Admin SSO audit chain-head authentication failed");
|
|
}
|
|
}
|
|
|
|
const id = randomUUID();
|
|
const now = new Date();
|
|
const createdAt = previousCreatedAt && now.getTime() <= previousCreatedAt.getTime() ? new Date(previousCreatedAt.getTime() + 1) : now;
|
|
const eventHash = computeAuditHash({
|
|
previousHash,
|
|
payload: buildAuditEventHashPayload(data, id, createdAt),
|
|
version: "hmac-v2",
|
|
});
|
|
const headWithoutMac: Omit<AuditChainHeadRecord, "headMac"> = {
|
|
chainKey: "platform",
|
|
tenantId: null,
|
|
eventId: id,
|
|
eventHash,
|
|
eventCreatedAt: createdAt,
|
|
};
|
|
const headMac = computeAuditChainHeadMac(headWithoutMac);
|
|
const payload = JSON.stringify({
|
|
...data,
|
|
id,
|
|
createdAt: createdAt.toISOString(),
|
|
});
|
|
const inserted = await transaction.$queryRaw<AdminSsoAuditAppendRow[]>(
|
|
Prisma.sql`SELECT event_id FROM public.hivegrid_append_admin_sso_audit(
|
|
${payload}::jsonb, ${previousHash}, ${eventHash}, ${headMac}
|
|
)`
|
|
);
|
|
if (inserted.length !== 1 || inserted[0]?.event_id !== id) {
|
|
throw new Error("Admin SSO audit append capability returned an invalid event");
|
|
}
|
|
},
|
|
{ timeout: 10_000 }
|
|
);
|
|
}
|
|
|
|
function normalizeGroups(groups: readonly string[]): string[] {
|
|
if (!Array.isArray(groups) || groups.length > 64) {
|
|
throw new Error("Admin SSO groups are invalid");
|
|
}
|
|
const normalized = [...new Set(groups.map((group) => normalizeIdentifier(group, 256)).filter((group): group is string => Boolean(group)))];
|
|
if (normalized.length !== groups.length) {
|
|
throw new Error("Admin SSO groups are invalid");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function requireEmail(value: string): string {
|
|
const normalized = value.trim().toLowerCase();
|
|
if (normalized.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized) || normalized.includes("\u0000")) {
|
|
throw new Error("Admin SSO email is invalid");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function requireIdentifier(value: string, name: string, maxLength: number): string {
|
|
const normalized = normalizeIdentifier(value, maxLength);
|
|
if (!normalized) throw new Error(`Admin SSO ${name} is invalid`);
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeIdentifier(value: string, maxLength: number): string | null {
|
|
const normalized = value.trim();
|
|
if (!normalized || normalized.length > maxLength || normalized.includes("\u0000")) return null;
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeOptionalHash(value: string | null | undefined): string | null {
|
|
if (value === null || value === undefined) return null;
|
|
const normalized = value.trim();
|
|
if (!/^(?:v2:)?[0-9a-f]{64}$/.test(normalized)) {
|
|
throw new Error("Admin SSO audit head capability returned an invalid hash");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeOptionalDate(value: Date | string | null | undefined): Date | null {
|
|
if (value === null || value === undefined) return null;
|
|
const parsed = value instanceof Date ? value : new Date(value);
|
|
if (Number.isNaN(parsed.getTime())) {
|
|
throw new Error("Admin SSO audit head capability returned an invalid timestamp");
|
|
}
|
|
return parsed;
|
|
}
|