Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+102
-107
@@ -1,75 +1,63 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import {
|
||||
AdminIdentityNotPreparedError,
|
||||
bindPreparedAuthentikAdminIdentity,
|
||||
} from "@hivegrid/db/admin-sso.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import { absoluteAdminPath } from "~/utils/app/CrossHostUrls";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { createUserSession, getUserInfo } from "~/utils/session.server";
|
||||
import {
|
||||
AdminSsoConfigError,
|
||||
consumeAdminSsoChallenge,
|
||||
extractAdminSsoClaims,
|
||||
getAdminSsoClient,
|
||||
jitProvisionAdmin,
|
||||
readAdminSsoEnv,
|
||||
type AdminSsoClaims,
|
||||
type JitProvisioningDbClient,
|
||||
} from "~/modules/admin-sso";
|
||||
import { serializeIdTokenCookie } from "~/modules/admin-sso/logout.server";
|
||||
import { hasAllowedAdminGroup } from "~/modules/admin-sso/claims.server";
|
||||
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
|
||||
import { createUserSession, getUserInfo, setLoggedUser } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { ensureAdminUserRoleByName } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAdminPath } from "~/utils/app/CrossHostUrls";
|
||||
|
||||
/**
|
||||
* Phase 09 Task #82 — GET /auth/admin/callback
|
||||
*
|
||||
* Verifies state + nonce + PKCE via openid-client, exchanges the code
|
||||
* for tokens, runs JIT provisioning, and rotates the App-Session cookie
|
||||
* to the freshly-provisioned admin. Failures always redirect to
|
||||
* /login with a typed error query param.
|
||||
*/
|
||||
import { serializeIdTokenCookie } from "~/modules/admin-sso/logout.server";
|
||||
|
||||
function failRedirect(reason: string): never {
|
||||
const path = `/login?error=${encodeURIComponent(reason)}`;
|
||||
throw redirect(path);
|
||||
}
|
||||
|
||||
function buildJitDbClient(): JitProvisioningDbClient {
|
||||
// The real Prisma client matches the structural type used by the helper.
|
||||
// We do the cast at the boundary so the module stays Prisma-free.
|
||||
return db as unknown as JitProvisioningDbClient;
|
||||
throw redirect(`/login?error=${encodeURIComponent(reason)}`);
|
||||
}
|
||||
|
||||
function sanitizeReturnTo(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
if (!value.startsWith("/") || value.startsWith("//")) return undefined;
|
||||
// Reject backslash variants (browsers treat `/\evil.com` as protocol-relative)
|
||||
// and percent-encoded slash/backslash/CR-LF.
|
||||
if (value.includes("\\")) return undefined;
|
||||
if (/%(?:2f|5c|00|0a|0d)/i.test(value)) return undefined;
|
||||
if (/[\x00-\x1f\x7f]/.test(value)) return undefined;
|
||||
if (!value || !value.startsWith("/") || value.startsWith("//") || value.includes("\\")) return undefined;
|
||||
if (/%(?:2f|5c|00|0a|0d)/i.test(value) || /[\x00-\x1f\x7f]/u.test(value)) return undefined;
|
||||
return value;
|
||||
}
|
||||
|
||||
function isAdminIdentityNotPrepared(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof AdminIdentityNotPreparedError ||
|
||||
(typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error.code === "ADMIN_IDENTITY_NOT_PREPARED")
|
||||
);
|
||||
}
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
|
||||
// --- 1. Env + client init ------------------------------------------------
|
||||
let env;
|
||||
let client;
|
||||
try {
|
||||
env = readAdminSsoEnv();
|
||||
client = await getAdminSsoClient(env);
|
||||
} catch (err) {
|
||||
const reason = err instanceof AdminSsoConfigError ? err.code : "unknown";
|
||||
} catch (error) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.failure",
|
||||
request,
|
||||
meta: { stage: "init", reason },
|
||||
meta: { stage: "init", reason: error instanceof AdminSsoConfigError ? error.code : "unknown" },
|
||||
});
|
||||
return failRedirect("sso_unavailable");
|
||||
}
|
||||
|
||||
// --- 2. Pop the challenge cookie ---------------------------------------
|
||||
const consumed = consumeAdminSsoChallenge(request);
|
||||
if (!consumed.ok) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
@@ -79,28 +67,24 @@ export async function loader({ request }: LoaderFunctionArgs): Promise<Response>
|
||||
});
|
||||
return failRedirect("sso_state_invalid");
|
||||
}
|
||||
const challenge = consumed.payload;
|
||||
|
||||
// --- 3. Token exchange + ID-token verification --------------------------
|
||||
const params = client.callbackParams(url.toString());
|
||||
let tokenSet;
|
||||
try {
|
||||
tokenSet = await client.callback(env.redirectUri, params, {
|
||||
state: challenge.state,
|
||||
nonce: challenge.nonce,
|
||||
code_verifier: challenge.codeVerifier,
|
||||
tokenSet = await client.callback(env.redirectUri, client.callbackParams(url.toString()), {
|
||||
state: consumed.payload.state,
|
||||
nonce: consumed.payload.nonce,
|
||||
code_verifier: consumed.payload.codeVerifier,
|
||||
});
|
||||
} catch (err) {
|
||||
} catch (error) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.failure",
|
||||
request,
|
||||
meta: { stage: "token-exchange", error: (err as Error).message },
|
||||
meta: { stage: "token-exchange", error: error instanceof Error ? error.name : "Error" },
|
||||
});
|
||||
return failRedirect("sso_token_exchange_failed");
|
||||
}
|
||||
|
||||
const rawClaims = tokenSet.claims();
|
||||
const claimResult = extractAdminSsoClaims(rawClaims as Record<string, unknown>);
|
||||
const claimResult = extractAdminSsoClaims(tokenSet.claims() as Record<string, unknown>);
|
||||
if (!claimResult.ok) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.failure",
|
||||
@@ -109,86 +93,97 @@ export async function loader({ request }: LoaderFunctionArgs): Promise<Response>
|
||||
});
|
||||
return failRedirect(`sso_${claimResult.reason.replace(/-/g, "_")}`);
|
||||
}
|
||||
const claims: AdminSsoClaims = claimResult.claims;
|
||||
|
||||
// --- 4. JIT-provision the admin ----------------------------------------
|
||||
const jitResult = await jitProvisionAdmin({ claims }, buildJitDbClient());
|
||||
if (!jitResult.ok) {
|
||||
const claims = claimResult.claims;
|
||||
if (!hasAllowedAdminGroup(claims.groups)) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.failure",
|
||||
request,
|
||||
ssoSubjectId: claims.subject,
|
||||
meta: { stage: "jit", reason: jitResult.reason, groups: claims.groups },
|
||||
meta: { stage: "authorization", reason: "forbidden-group", groups: claims.groups },
|
||||
});
|
||||
return failRedirect("sso_forbidden_group");
|
||||
}
|
||||
const admin = jitResult.admin;
|
||||
|
||||
// --- 4b. Wire the admin-SSO identity to its RBAC permissions -------------
|
||||
// JIT creates the User + AdminUser but not the permission-bearing UserRole.
|
||||
// Map super_admin -> the "SuperAdmin" RBAC role so a freshly-provisioned
|
||||
// colleague has the full admin surface on their FIRST page load. The grant is
|
||||
// idempotent and invalidates the userRoles cache, so the 24h cache TTL never
|
||||
// causes a "logged in but no permissions" state. Never block login on failure.
|
||||
if (admin.role === "super_admin") {
|
||||
try {
|
||||
await ensureAdminUserRoleByName(admin.userId, "SuperAdmin");
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("[admin-sso] failed to grant SuperAdmin RBAC role", error);
|
||||
}
|
||||
}
|
||||
|
||||
// --- 5. Session rotation ------------------------------------------------
|
||||
const userRecord = await getUser(admin.userId);
|
||||
if (!userRecord) {
|
||||
if (!claims.authenticationMethods.includes("mfa")) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.failure",
|
||||
request,
|
||||
ssoSubjectId: claims.subject,
|
||||
meta: { stage: "post-jit-user-missing" },
|
||||
meta: { stage: "mfa-assurance", reason: "authentik-mfa-required" },
|
||||
});
|
||||
return failRedirect("sso_session_failed");
|
||||
return failRedirect("sso_mfa_required");
|
||||
}
|
||||
|
||||
let boundIdentity: Awaited<ReturnType<typeof bindPreparedAuthentikAdminIdentity>>;
|
||||
try {
|
||||
boundIdentity = await bindPreparedAuthentikAdminIdentity({
|
||||
subject: claims.subject,
|
||||
email: claims.email,
|
||||
emailVerified: claims.emailVerified,
|
||||
groups: claims.groups,
|
||||
firstName: claims.name.trim().split(/\s+/u)[0] ?? claims.email,
|
||||
lastName: claims.name.trim().split(/\s+/u).slice(1).join(" "),
|
||||
loginAt: new Date(),
|
||||
});
|
||||
} catch (error) {
|
||||
const identityNotPrepared = isAdminIdentityNotPrepared(error);
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.failure",
|
||||
request,
|
||||
ssoSubjectId: claims.subject,
|
||||
meta: {
|
||||
stage: "identity-binding",
|
||||
reason: identityNotPrepared ? "admin-not-prepared" : "binding-failed",
|
||||
error: error instanceof Error ? error.name : "Error",
|
||||
},
|
||||
});
|
||||
return failRedirect(identityNotPrepared ? "sso_admin_not_prepared" : "sso_binding_failed");
|
||||
}
|
||||
|
||||
const adminUser = await runWithRlsContext({ userId: boundIdentity.adminUserId }, () =>
|
||||
db.adminUser.findUnique({
|
||||
where: { id: boundIdentity.adminUserId },
|
||||
select: { id: true, email: true, locale: true },
|
||||
})
|
||||
);
|
||||
if (!adminUser) return failRedirect("sso_session_failed");
|
||||
|
||||
const routing = loadRequiredWebConfig().routing;
|
||||
const redirectTarget = sanitizeReturnTo(consumed.payload.returnTo) ?? absoluteAdminPath(routing, "dashboard");
|
||||
const userInfo = await getUserInfo(request);
|
||||
const loggedUser = await setLoggedUser({
|
||||
id: userRecord.id,
|
||||
email: userRecord.email,
|
||||
defaultTenantId: userRecord.defaultTenantId,
|
||||
});
|
||||
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.success",
|
||||
actorAdminUserId: admin.userId,
|
||||
ssoSubjectId: claims.subject,
|
||||
request,
|
||||
meta: { groups: claims.groups, role: admin.role, created: admin.created, linkedExisting: admin.linkedExisting },
|
||||
});
|
||||
|
||||
const returnTo = sanitizeReturnTo(challenge.returnTo);
|
||||
const fallbackTarget = absoluteAdminPath(loadRequiredWebConfig().routing, "dashboard");
|
||||
const redirectTarget = returnTo ?? fallbackTarget;
|
||||
|
||||
const mfaAssuredAt = new Date();
|
||||
const sessionResponse = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
userId: loggedUser.userId,
|
||||
lng: userRecord.locale ?? userInfo.lng,
|
||||
userId: adminUser.id,
|
||||
lng: adminUser.locale ?? userInfo.lng,
|
||||
},
|
||||
redirectTarget,
|
||||
{
|
||||
request,
|
||||
rotate: true,
|
||||
adminAuthenticationMethods: claims.authenticationMethods,
|
||||
adminMfaAssuredAt: mfaAssuredAt,
|
||||
}
|
||||
);
|
||||
|
||||
await runWithRlsContext({ userId: adminUser.id }, () =>
|
||||
writeAdminSsoAuditEvent({
|
||||
action: "admin.login.sso.success",
|
||||
actorAdminUserId: adminUser.id,
|
||||
ssoSubjectId: claims.subject,
|
||||
request,
|
||||
meta: {
|
||||
groups: claims.groups,
|
||||
newSubjectBinding: boundIdentity.newSubjectBinding,
|
||||
authentikMfaVerified: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
// Append both the clear-challenge cookie and the id-token cookie to
|
||||
// whatever Set-Cookie createUserSession already set.
|
||||
const headers = new Headers(sessionResponse.headers);
|
||||
headers.append("Set-Cookie", consumed.clearCookie);
|
||||
if (tokenSet.id_token) {
|
||||
headers.append("Set-Cookie", serializeIdTokenCookie(tokenSet.id_token));
|
||||
}
|
||||
return new Response(sessionResponse.body, {
|
||||
status: sessionResponse.status,
|
||||
headers,
|
||||
});
|
||||
if (tokenSet.id_token) headers.append("Set-Cookie", serializeIdTokenCookie(tokenSet.id_token));
|
||||
return new Response(sessionResponse.body, { status: sessionResponse.status, headers });
|
||||
}
|
||||
|
||||
export default function AuthAdminCallback() {
|
||||
|
||||
Reference in new issue
Block a user