import { describe, expect, it, vi } from "vitest"; import { AdminIdentityNotPreparedError, appendPreauthAdminSsoAuditEvent, bindPreparedAuthentikAdminIdentity, resolveAuthentikAdminSsoIdentity, } from "./admin-sso.server.js"; function queryClient(rows: unknown[]) { return { $queryRaw: vi.fn().mockResolvedValue(rows) }; } describe("Admin SSO RLS boundary", () => { it("resolves an existing Authentik link to identifiers only", async () => { const client = queryClient([{ admin_user_id: "admin_1" }]); await expect(resolveAuthentikAdminSsoIdentity("authentik", " subject_1 ", client as never)).resolves.toEqual({ resourceId: "admin_1", userId: "admin_1", }); const query = client.$queryRaw.mock.calls[0]?.[0] as { strings: readonly string[]; values: readonly unknown[] }; expect(query.strings.join("?")).toContain("hivegrid_resolve_admin_sso_identity_v2"); expect(query.values).toEqual(["subject_1"]); }); it("rejects unsupported providers and invalid resolver output without exposing a row", async () => { const unsupported = queryClient([]); const mismatched = queryClient([{ admin_user_id: "" }]); await expect(resolveAuthentikAdminSsoIdentity("other", "subject", unsupported as never)).resolves.toBeNull(); expect(unsupported.$queryRaw).not.toHaveBeenCalled(); await expect(resolveAuthentikAdminSsoIdentity("authentik", "subject", mismatched as never)).rejects.toThrow("invalid identity"); }); it("invokes the narrow prepared-identity binding capability with normalized scalar parameters", async () => { const client = queryClient([{ admin_user_id: "admin_1", subject_bound: true }]); await expect( bindPreparedAuthentikAdminIdentity( { subject: " subject_1 ", email: " ADMIN@Example.TEST ", emailVerified: true, groups: ["hivegrid-admin", "other-group"], firstName: " Ada ", lastName: " Admin ", loginAt: new Date("2026-07-14T08:00:00.000Z"), }, client as never ) ).resolves.toEqual({ adminUserId: "admin_1", newSubjectBinding: true }); const query = client.$queryRaw.mock.calls[0]?.[0] as { strings: readonly string[]; values: readonly unknown[] }; expect(query.strings.join("?")).toContain("hivegrid_bind_prepared_authentik_admin_v3"); expect(query.values.slice(0, 9)).toEqual([ "subject_1", "admin@example.test", true, "hivegrid-admin", "other-group", "Ada", "Admin", null, new Date("2026-07-14T08:00:00.000Z"), ]); }); it("fails before PostgreSQL for unverified email, missing allowed groups, or non-canonical duplicates", async () => { const client = queryClient([]); const base = { subject: "subject_1", email: "admin@example.test", emailVerified: true, groups: ["hivegrid-admin"], firstName: "Ada", lastName: "Admin", loginAt: new Date(), } as const; await expect(bindPreparedAuthentikAdminIdentity({ ...base, emailVerified: false }, client as never)).rejects.toThrow("verified email"); await expect(bindPreparedAuthentikAdminIdentity({ ...base, groups: ["untrusted"] }, client as never)).rejects.toThrow("allowed operator group"); await expect(bindPreparedAuthentikAdminIdentity({ ...base, groups: ["hivegrid-admin", "hivegrid-admin"] }, client as never)).rejects.toThrow( "groups are invalid" ); expect(client.$queryRaw).not.toHaveBeenCalled(); }); it("fails closed with a typed error when no prepared active AdminUser matches", async () => { const client = queryClient([]); await expect( bindPreparedAuthentikAdminIdentity( { subject: "subject_1", email: "admin@example.test", emailVerified: true, groups: ["hivegrid-staff"], firstName: "Ada", lastName: "Admin", loginAt: new Date(), }, client as never ) ).rejects.toBeInstanceOf(AdminIdentityNotPreparedError); }); it("locks and atomically appends a pre-auth Admin-SSO event to the platform audit chain", async () => { let calls = 0; const queryRaw = vi.fn(async (query: { strings: readonly string[]; values: readonly unknown[] }) => { calls += 1; if (calls === 1) return []; const payload = JSON.parse(String(query.values[0])) as { id: string }; return [{ event_id: payload.id }]; }); const client = { $transaction: vi.fn(async (runner: (transaction: { $queryRaw: typeof queryRaw }) => Promise) => runner({ $queryRaw: queryRaw })), }; await expect( appendPreauthAdminSsoAuditEvent( { action: "admin.login.sso.failure", actorType: "admin", outcome: "failure", metadata: { stage: "claims" }, }, client as never ) ).resolves.toBeUndefined(); expect(client.$transaction).toHaveBeenCalledTimes(1); expect(queryRaw).toHaveBeenCalledTimes(2); const headQuery = queryRaw.mock.calls[0]?.[0] as { strings: readonly string[] }; const appendQuery = queryRaw.mock.calls[1]?.[0] as { strings: readonly string[]; values: readonly unknown[] }; expect(headQuery.strings.join("?")).toContain("hivegrid_lock_admin_sso_audit_head"); expect(appendQuery.strings.join("?")).toContain("hivegrid_append_admin_sso_audit"); const event = JSON.parse(String(appendQuery.values[0])) as Record; expect(event).toMatchObject({ tenantId: null, actorType: "admin", action: "admin.login.sso.failure", sourceModule: "admin-sso" }); expect(appendQuery.values[2]).toMatch(/^v2:[0-9a-f]{64}$/); expect(appendQuery.values[3]).toMatch(/^ah1:[0-9a-f]{64}$/); }); it("rejects non-SSO actions before acquiring the platform audit lock", async () => { const client = { $transaction: vi.fn() }; await expect(appendPreauthAdminSsoAuditEvent({ action: "admin.permissions.changed" }, client as never)).rejects.toThrow("action is not allowed"); expect(client.$transaction).not.toHaveBeenCalled(); }); });