239 lines
9.2 KiB
TypeScript
239 lines
9.2 KiB
TypeScript
// @vitest-environment node
|
|
import type { LoaderFunctionArgs } from "react-router";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { extractAdminSsoClaims as extractAdminSsoClaimsActual } from "~/modules/admin-sso/claims.server";
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
consumeChallenge: vi.fn(),
|
|
extractClaims: vi.fn(),
|
|
getClient: vi.fn(),
|
|
readEnv: vi.fn(),
|
|
writeAudit: vi.fn(),
|
|
createSession: vi.fn(),
|
|
getUserInfo: vi.fn(),
|
|
bindIdentity: vi.fn(),
|
|
adminFind: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/admin-sso", () => ({
|
|
AdminSsoConfigError: class AdminSsoConfigError extends Error {
|
|
code = "missing-env";
|
|
},
|
|
consumeAdminSsoChallenge: mocks.consumeChallenge,
|
|
extractAdminSsoClaims: mocks.extractClaims,
|
|
getAdminSsoClient: mocks.getClient,
|
|
readAdminSsoEnv: mocks.readEnv,
|
|
}));
|
|
vi.mock("~/modules/admin-sso/audit.server", () => ({ writeAdminSsoAuditEvent: mocks.writeAudit }));
|
|
vi.mock("~/modules/admin-sso/logout.server", () => ({
|
|
serializeIdTokenCookie: (token: string) => `__Host-hivegrid_admin_sso_id_token=${token}; Path=/; HttpOnly; Secure`,
|
|
}));
|
|
vi.mock("~/utils/session.server", () => ({
|
|
createUserSession: mocks.createSession,
|
|
getUserInfo: mocks.getUserInfo,
|
|
}));
|
|
vi.mock("~/utils/db.server", () => ({
|
|
db: { adminUser: { findUnique: mocks.adminFind } },
|
|
}));
|
|
vi.mock("@hivegrid/db/admin-sso.server", () => ({
|
|
AdminIdentityNotPreparedError: class AdminIdentityNotPreparedError extends Error {
|
|
code = "ADMIN_IDENTITY_NOT_PREPARED";
|
|
},
|
|
bindPreparedAuthentikAdminIdentity: mocks.bindIdentity,
|
|
}));
|
|
vi.mock("@hivegrid/db/rls-context.server", () => ({
|
|
runWithRlsContext: async (_context: unknown, operation: () => unknown) => operation(),
|
|
}));
|
|
vi.mock("@hivegrid/config", () => ({
|
|
loadRequiredWebConfig: () => ({
|
|
routing: {
|
|
protocol: "https",
|
|
webAppHost: "app.example.test",
|
|
adminAppHost: "admin.example.test",
|
|
apiHost: "api.example.test",
|
|
appBaseDomain: "example.test",
|
|
},
|
|
}),
|
|
}));
|
|
vi.mock("~/utils/app/CrossHostUrls", () => ({
|
|
absoluteAdminPath: (_routing: unknown, path: string) => `https://admin.example.test/${path.replace(/^\//u, "")}`,
|
|
}));
|
|
|
|
import * as CallbackRoute from "./auth.admin.callback";
|
|
|
|
const claims = {
|
|
subject: "sso-subject-1",
|
|
email: "admin@example.test",
|
|
emailVerified: true,
|
|
name: "Ada Admin",
|
|
groups: ["hivegrid-admin"],
|
|
authenticationMethods: ["pwd", "mfa"],
|
|
};
|
|
|
|
function request() {
|
|
return new Request("https://admin.example.test/auth/admin/callback?code=abc&state=state_1");
|
|
}
|
|
|
|
function callLoader() {
|
|
return CallbackRoute.loader({ request: request(), params: {}, context: {} } as LoaderFunctionArgs);
|
|
}
|
|
|
|
async function expectRedirect(promise: Promise<Response>) {
|
|
try {
|
|
await promise;
|
|
} catch (error) {
|
|
expect(error).toBeInstanceOf(Response);
|
|
return error as Response;
|
|
}
|
|
throw new Error("Expected redirect response");
|
|
}
|
|
|
|
describe("admin Authentik callback", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.readEnv.mockReturnValue({ redirectUri: "https://admin.example.test/auth/admin/callback" });
|
|
mocks.getClient.mockResolvedValue({
|
|
callbackParams: vi.fn(() => ({ code: "abc", state: "state_1" })),
|
|
callback: vi.fn(async () => ({ id_token: "id-token", claims: () => claims })),
|
|
});
|
|
mocks.consumeChallenge.mockReturnValue({
|
|
ok: true,
|
|
payload: { state: "state_1", nonce: "nonce_1", codeVerifier: "verifier_1", returnTo: "/dashboard" },
|
|
clearCookie: "__Host-hivegrid_admin_sso_challenge=; Path=/; Max-Age=0; Secure",
|
|
});
|
|
mocks.extractClaims.mockReturnValue({ ok: true, claims });
|
|
mocks.bindIdentity.mockResolvedValue({ adminUserId: "admin-1", newSubjectBinding: true });
|
|
mocks.adminFind.mockResolvedValue({ id: "admin-1", email: "admin@example.test", locale: "de" });
|
|
mocks.getUserInfo.mockResolvedValue({ userId: undefined, lng: "en" });
|
|
mocks.createSession.mockImplementation(
|
|
async (_session: unknown, redirectTo: string) =>
|
|
new Response(null, { status: 302, headers: { Location: redirectTo, "Set-Cookie": "__Host-hivegrid_admin_session=fresh" } })
|
|
);
|
|
});
|
|
|
|
it("binds a prepared tenant-less AdminUser and creates an assured AdminSession without assigning roles", async () => {
|
|
const response = await callLoader();
|
|
|
|
expect(response.status).toBe(302);
|
|
expect(response.headers.get("Location")).toBe("/dashboard");
|
|
expect(mocks.bindIdentity).toHaveBeenCalledWith(expect.objectContaining({ subject: claims.subject, email: claims.email }));
|
|
expect(mocks.createSession).toHaveBeenCalledWith(
|
|
expect.objectContaining({ userId: "admin-1", lng: "de" }),
|
|
"/dashboard",
|
|
expect.objectContaining({
|
|
rotate: true,
|
|
adminAuthenticationMethods: ["pwd", "mfa"],
|
|
adminMfaAssuredAt: expect.any(Date),
|
|
})
|
|
);
|
|
});
|
|
|
|
it("passes canonicalized groups to subject binding when Authentik scope mappings overlap", async () => {
|
|
const duplicatedGroups = ["authentik Admins", "sogo-users", "hivegrid-admin", "authentik Admins", "sogo-users", "hivegrid-admin"];
|
|
const canonicalGroups = ["authentik Admins", "sogo-users", "hivegrid-admin"];
|
|
const rawClaims = {
|
|
sub: claims.subject,
|
|
email: claims.email,
|
|
email_verified: claims.emailVerified,
|
|
name: claims.name,
|
|
groups: duplicatedGroups,
|
|
amr: claims.authenticationMethods,
|
|
};
|
|
mocks.getClient.mockResolvedValueOnce({
|
|
callbackParams: vi.fn(() => ({ code: "abc", state: "state_1" })),
|
|
callback: vi.fn(async () => ({ id_token: "id-token", claims: () => rawClaims })),
|
|
});
|
|
mocks.extractClaims.mockReturnValueOnce(extractAdminSsoClaimsActual(rawClaims));
|
|
|
|
await callLoader();
|
|
|
|
expect(mocks.extractClaims).toHaveBeenCalledWith(rawClaims);
|
|
expect(mocks.bindIdentity).toHaveBeenCalledWith(expect.objectContaining({ groups: canonicalGroups }));
|
|
});
|
|
|
|
it("accepts both Authentik groups as coarse access gates without mapping either to a HiveGrid role", async () => {
|
|
mocks.extractClaims.mockReturnValueOnce({ ok: true, claims: { ...claims, groups: ["hivegrid-staff"] } });
|
|
|
|
await callLoader();
|
|
|
|
expect(mocks.bindIdentity).toHaveBeenCalledWith(expect.objectContaining({ groups: ["hivegrid-staff"] }));
|
|
});
|
|
|
|
it("keeps existing HiveGrid roles outside the Authentik callback", async () => {
|
|
mocks.extractClaims.mockReturnValueOnce({ ok: true, claims: { ...claims, groups: ["hivegrid-staff"] } });
|
|
mocks.bindIdentity.mockResolvedValueOnce({ adminUserId: "admin-1", newSubjectBinding: false });
|
|
|
|
await callLoader();
|
|
|
|
expect(mocks.bindIdentity).toHaveBeenCalledTimes(1);
|
|
expect(mocks.adminFind).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("rejects an unprepared Authentik user with a clear fail-closed error", async () => {
|
|
mocks.bindIdentity.mockRejectedValueOnce({ code: "ADMIN_IDENTITY_NOT_PREPARED" });
|
|
|
|
const response = await expectRedirect(callLoader());
|
|
|
|
expect(response.headers.get("Location")).toBe("/login?error=sso_admin_not_prepared");
|
|
expect(mocks.createSession).not.toHaveBeenCalled();
|
|
expect(mocks.writeAudit).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
meta: expect.objectContaining({ stage: "identity-binding", reason: "admin-not-prepared" }),
|
|
})
|
|
);
|
|
});
|
|
|
|
it("rejects an allowed group without Authentik MFA assurance before binding", async () => {
|
|
mocks.extractClaims.mockReturnValueOnce({ ok: true, claims: { ...claims, authenticationMethods: ["pwd"] } });
|
|
|
|
const response = await expectRedirect(callLoader());
|
|
|
|
expect(response.headers.get("Location")).toBe("/login?error=sso_mfa_required");
|
|
expect(mocks.bindIdentity).not.toHaveBeenCalled();
|
|
expect(mocks.createSession).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects forbidden Authentik groups before binding", async () => {
|
|
mocks.extractClaims.mockReturnValueOnce({ ok: true, claims: { ...claims, groups: ["unrelated"] } });
|
|
|
|
const response = await expectRedirect(callLoader());
|
|
|
|
expect(response.headers.get("Location")).toBe("/login?error=sso_forbidden_group");
|
|
expect(mocks.bindIdentity).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails closed when the challenge is invalid", async () => {
|
|
mocks.consumeChallenge.mockReturnValueOnce({ ok: false, reason: "missing" });
|
|
|
|
const response = await expectRedirect(callLoader());
|
|
|
|
expect(response.headers.get("Location")).toBe("/login?error=sso_state_invalid");
|
|
expect(mocks.bindIdentity).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("sanitizes external return targets and preserves callback cleanup cookies", async () => {
|
|
mocks.consumeChallenge.mockReturnValueOnce({
|
|
ok: true,
|
|
payload: {
|
|
state: "state_1",
|
|
nonce: "nonce_1",
|
|
codeVerifier: "verifier_1",
|
|
returnTo: "https://evil.example.test/steal",
|
|
},
|
|
clearCookie: "__Host-hivegrid_admin_sso_challenge=; Path=/; Max-Age=0; Secure",
|
|
});
|
|
|
|
const response = await callLoader();
|
|
|
|
expect(response.headers.get("Location")).toBe("https://admin.example.test/dashboard");
|
|
const setCookie = response.headers.get("Set-Cookie") ?? "";
|
|
expect(setCookie).toContain("__Host-hivegrid_admin_session=fresh");
|
|
expect(setCookie).toContain("__Host-hivegrid_admin_sso_challenge=");
|
|
expect(setCookie).toContain("__Host-hivegrid_admin_sso_id_token=id-token");
|
|
});
|
|
|
|
it("has no action export", () => {
|
|
expect("action" in CallbackRoute).toBe(false);
|
|
});
|
|
});
|