fosrl.pangolin/server/routers/idp/validateOidcCallback.ts

259 lines
7.4 KiB
TypeScript
Raw Normal View History

2025-04-12 15:39:15 -04:00
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import {
idp,
idpOidcConfig,
2025-04-13 17:57:27 -04:00
users
2025-04-12 15:39:15 -04:00
} from "@server/db/schemas";
2025-04-22 22:53:52 -04:00
import { and, eq } from "drizzle-orm";
2025-04-12 15:39:15 -04:00
import * as arctic from "arctic";
import { generateOidcRedirectUrl } from "@server/lib/idp/generateRedirectUrl";
import jmespath from "jmespath";
2025-04-13 17:57:27 -04:00
import jsonwebtoken from "jsonwebtoken";
import config from "@server/lib/config";
import { decrypt } from "@server/lib/crypto";
2025-04-12 15:39:15 -04:00
const paramsSchema = z
.object({
idpId: z.coerce.number()
})
.strict();
const bodySchema = z.object({
code: z.string().nonempty(),
2025-04-13 17:57:27 -04:00
state: z.string().nonempty(),
storedState: z.string().nonempty()
2025-04-12 15:39:15 -04:00
});
2025-04-13 17:57:27 -04:00
export type ValidateOidcUrlCallbackResponse = {
redirectUrl: string;
};
2025-04-12 15:39:15 -04:00
export async function validateOidcCallback(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
2025-04-13 17:57:27 -04:00
const { idpId } = parsedParams.data;
2025-04-12 15:39:15 -04:00
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
2025-04-13 17:57:27 -04:00
const { storedState, code, state: expectedState } = parsedBody.data;
2025-04-12 15:39:15 -04:00
const [existingIdp] = await db
.select()
.from(idp)
.innerJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId))
2025-04-13 17:57:27 -04:00
.where(and(eq(idp.type, "oidc"), eq(idp.idpId, idpId)));
2025-04-12 15:39:15 -04:00
if (!existingIdp) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"IdP not found for the organization"
)
);
}
const key = config.getRawConfig().server.secret;
const decryptedClientId = decrypt(
2025-04-12 15:39:15 -04:00
existingIdp.idpOidcConfig.clientId,
key
);
const decryptedClientSecret = decrypt(
2025-04-12 15:39:15 -04:00
existingIdp.idpOidcConfig.clientSecret,
key
);
const redirectUrl = generateOidcRedirectUrl(existingIdp.idp.idpId);
const client = new arctic.OAuth2Client(
decryptedClientId,
decryptedClientSecret,
2025-04-12 15:39:15 -04:00
redirectUrl
);
2025-04-13 17:57:27 -04:00
const statePayload = jsonwebtoken.verify(
storedState,
config.getRawConfig().server.secret,
function (err, decoded) {
if (err) {
logger.error("Error verifying state JWT", { err });
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid state JWT"
)
);
}
return decoded;
}
);
const stateObj = z
.object({
redirectUrl: z.string(),
state: z.string(),
codeVerifier: z.string()
})
.safeParse(statePayload);
if (!stateObj.success) {
logger.error("Error parsing state JWT");
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(stateObj.error).toString()
)
);
}
const {
codeVerifier,
state,
redirectUrl: postAuthRedirectUrl
} = stateObj.data;
if (state !== expectedState) {
logger.error("State mismatch", { expectedState, state });
return next(
createHttpError(HttpCode.BAD_REQUEST, "State mismatch")
);
}
2025-04-12 15:39:15 -04:00
const tokens = await client.validateAuthorizationCode(
existingIdp.idpOidcConfig.tokenUrl,
code,
codeVerifier
);
const idToken = tokens.idToken();
const claims = arctic.decodeIdToken(idToken);
const userIdentifier = jmespath.search(
claims,
existingIdp.idpOidcConfig.identifierPath
);
if (!userIdentifier) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"User identifier not found in the ID token"
)
);
}
logger.debug("User identifier", { userIdentifier });
2025-04-13 17:57:27 -04:00
let email = null;
let name = null;
try {
if (existingIdp.idpOidcConfig.emailPath) {
email = jmespath.search(
claims,
existingIdp.idpOidcConfig.emailPath
);
}
if (existingIdp.idpOidcConfig.namePath) {
name = jmespath.search(
claims,
existingIdp.idpOidcConfig.namePath || ""
);
}
} catch (error) {}
2025-04-12 15:39:15 -04:00
logger.debug("User email", { email });
logger.debug("User name", { name });
2025-04-13 17:57:27 -04:00
const [existingUser] = await db
2025-04-12 15:39:15 -04:00
.select()
2025-04-13 17:57:27 -04:00
.from(users)
2025-04-12 15:39:15 -04:00
.where(
and(
2025-04-13 17:57:27 -04:00
eq(users.username, userIdentifier),
eq(users.idpId, existingIdp.idp.idpId)
2025-04-12 15:39:15 -04:00
)
);
if (existingIdp.idp.autoProvision) {
2025-04-22 22:53:52 -04:00
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Auto provisioning is not supported"
)
2025-04-13 17:57:27 -04:00
);
} else {
if (!existingUser) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"User not found in the IdP"
)
2025-04-13 17:57:27 -04:00
);
}
//
// const token = generateSessionToken();
// const sess = await createSession(token, existingUser.userId);
// const isSecure = req.protocol === "https";
// const cookie = serializeSessionCookie(
// token,
// isSecure,
// new Date(sess.expiresAt)
// );
//
// res.appendHeader("Set-Cookie", cookie);
//
// return response<ValidateOidcUrlCallbackResponse>(res, {
// data: {
// redirectUrl: postAuthRedirectUrl
// },
// success: true,
// error: false,
// message: "OIDC callback validated successfully",
// status: HttpCode.CREATED
// });
}
2025-04-12 15:39:15 -04:00
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}
2025-04-18 17:45:59 -04:00
function hydrateOrgMapping(
orgMapping: string | null,
orgId: string
): string | undefined {
if (!orgMapping) {
return undefined;
}
return orgMapping.split("{{orgId}}").join(orgId);
}