mirror of
https://github.com/fosrl/pangolin.git
synced 2026-02-23 13:26:41 +00:00
testing oidc callback
This commit is contained in:
@@ -10,6 +10,7 @@ import * as auth from "./auth";
|
||||
import * as role from "./role";
|
||||
import * as supporterKey from "./supporterKey";
|
||||
import * as accessToken from "./accessToken";
|
||||
import * as idp from "./idp";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import {
|
||||
verifyAccessTokenAccess,
|
||||
@@ -493,6 +494,13 @@ authenticated.delete(
|
||||
// createNewt
|
||||
// );
|
||||
|
||||
authenticated.put(
|
||||
"/org/:orgId/idp/oidc",
|
||||
verifyOrgAccess,
|
||||
verifyUserHasAction(ActionsEnum.createIdp),
|
||||
idp.createOidcIdp
|
||||
)
|
||||
|
||||
// Auth routes
|
||||
export const authRouter = Router();
|
||||
unauthenticated.use("/auth", authRouter);
|
||||
@@ -581,4 +589,17 @@ authRouter.post(
|
||||
resource.authWithAccessToken
|
||||
);
|
||||
|
||||
authRouter.post("/access-token", resource.authWithAccessToken);
|
||||
authRouter.post(
|
||||
"/access-token",
|
||||
resource.authWithAccessToken
|
||||
);
|
||||
|
||||
authRouter.post(
|
||||
"/org/:orgId/idp/:idpId/oidc/generate-url",
|
||||
idp.generateOidcUrl
|
||||
)
|
||||
|
||||
authRouter.post(
|
||||
"/org/:orgId/idp/:idpId/oidc/validate-callback",
|
||||
idp.validateOidcCallback
|
||||
)
|
||||
|
||||
158
server/routers/idp/createOidcIdp.ts
Normal file
158
server/routers/idp/createOidcIdp.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { idp, idpOidcConfig, idpOrg, orgs } from "@server/db/schemas";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { generateOidcUrl } from "./generateOidcUrl";
|
||||
import { generateOidcRedirectUrl } from "@server/lib/idp/generateRedirectUrl";
|
||||
|
||||
const paramsSchema = z
|
||||
.object({
|
||||
orgId: z.string()
|
||||
})
|
||||
.strict();
|
||||
|
||||
const bodySchema = z
|
||||
.object({
|
||||
clientId: z.string().nonempty(),
|
||||
clientSecret: z.string().nonempty(),
|
||||
authUrl: z.string().url(),
|
||||
tokenUrl: z.string().url(),
|
||||
autoProvision: z.boolean(),
|
||||
identifierPath: z.string().nonempty(),
|
||||
emailPath: z.string().optional(),
|
||||
namePath: z.string().optional(),
|
||||
roleMapping: z.string().optional(),
|
||||
scopes: z.array(z.string().nonempty())
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type CreateIdpResponse = {
|
||||
idpId: number;
|
||||
redirectUrl: string;
|
||||
};
|
||||
|
||||
registry.registerPath({
|
||||
method: "put",
|
||||
path: "/org/{orgId}/idp/oidc",
|
||||
description: "Create an OIDC IdP for an organization.",
|
||||
tags: [OpenAPITags.Org, OpenAPITags.Idp],
|
||||
request: {
|
||||
params: paramsSchema,
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: bodySchema
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function createOidcIdp(
|
||||
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()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedBody = bodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId } = parsedParams.data;
|
||||
|
||||
const {
|
||||
clientId,
|
||||
clientSecret,
|
||||
authUrl,
|
||||
tokenUrl,
|
||||
scopes,
|
||||
identifierPath,
|
||||
emailPath,
|
||||
namePath,
|
||||
roleMapping,
|
||||
autoProvision
|
||||
} = parsedBody.data;
|
||||
|
||||
// Check if the org exists
|
||||
const [org] = await db.select().from(orgs).where(eq(orgs.orgId, orgId));
|
||||
|
||||
if (!org) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Organization not found")
|
||||
);
|
||||
}
|
||||
|
||||
let idpId: number | undefined;
|
||||
await db.transaction(async (trx) => {
|
||||
const [idpRes] = await trx
|
||||
.insert(idp)
|
||||
.values({
|
||||
type: "oidc"
|
||||
})
|
||||
.returning();
|
||||
|
||||
idpId = idpRes.idpId;
|
||||
|
||||
await trx.insert(idpOidcConfig).values({
|
||||
idpId: idpRes.idpId,
|
||||
clientId,
|
||||
clientSecret,
|
||||
authUrl,
|
||||
tokenUrl,
|
||||
autoProvision,
|
||||
scopes: JSON.stringify(scopes),
|
||||
identifierPath,
|
||||
emailPath,
|
||||
namePath,
|
||||
roleMapping
|
||||
});
|
||||
|
||||
await trx.insert(idpOrg).values({
|
||||
idpId: idpRes.idpId,
|
||||
orgId
|
||||
});
|
||||
});
|
||||
|
||||
const redirectUrl = generateOidcRedirectUrl(orgId, idpId as number);
|
||||
|
||||
return response<CreateIdpResponse>(res, {
|
||||
data: {
|
||||
idpId: idpId as number,
|
||||
redirectUrl
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Idp created successfully",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
116
server/routers/idp/generateOidcUrl.ts
Normal file
116
server/routers/idp/generateOidcUrl.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
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, idpOrg } from "@server/db/schemas";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import * as arctic from "arctic";
|
||||
import { generateOidcRedirectUrl } from "@server/lib/idp/generateRedirectUrl";
|
||||
import cookie from "cookie";
|
||||
|
||||
const paramsSchema = z
|
||||
.object({
|
||||
orgId: z.string(),
|
||||
idpId: z.coerce.number()
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type GenerateOidcUrlResponse = {
|
||||
redirectUrl: string;
|
||||
};
|
||||
|
||||
export async function generateOidcUrl(
|
||||
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()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId, idpId } = parsedParams.data;
|
||||
|
||||
const [existingIdp] = await db
|
||||
.select()
|
||||
.from(idp)
|
||||
.innerJoin(idpOrg, eq(idp.idpId, idpOrg.idpId))
|
||||
.innerJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId))
|
||||
.where(
|
||||
and(
|
||||
eq(idpOrg.orgId, orgId),
|
||||
eq(idp.type, "oidc"),
|
||||
eq(idp.idpId, idpId)
|
||||
)
|
||||
);
|
||||
|
||||
if (!existingIdp) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"IdP not found for the organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedScopes = JSON.parse(existingIdp.idpOidcConfig.scopes);
|
||||
|
||||
const redirectUrl = generateOidcRedirectUrl(orgId, idpId);
|
||||
const client = new arctic.OAuth2Client(
|
||||
existingIdp.idpOidcConfig.clientId,
|
||||
existingIdp.idpOidcConfig.clientSecret,
|
||||
redirectUrl
|
||||
);
|
||||
|
||||
const codeVerifier = arctic.generateCodeVerifier();
|
||||
const state = arctic.generateState();
|
||||
const url = client.createAuthorizationURLWithPKCE(
|
||||
existingIdp.idpOidcConfig.authUrl,
|
||||
state,
|
||||
arctic.CodeChallengeMethod.S256,
|
||||
codeVerifier,
|
||||
parsedScopes
|
||||
);
|
||||
|
||||
res.cookie("oidc_state", state, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: req.protocol === "https",
|
||||
expires: new Date(Date.now() + 60 * 10 * 1000),
|
||||
sameSite: "lax"
|
||||
});
|
||||
|
||||
res.cookie(`oidc_code_verifier`, codeVerifier, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: req.protocol === "https",
|
||||
expires: new Date(Date.now() + 60 * 10 * 1000),
|
||||
sameSite: "lax"
|
||||
});
|
||||
|
||||
return response<GenerateOidcUrlResponse>(res, {
|
||||
data: {
|
||||
redirectUrl: url.toString()
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Idp auth url generated",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
3
server/routers/idp/index.ts
Normal file
3
server/routers/idp/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from "./createOidcIdp";
|
||||
export * from "./generateOidcUrl";
|
||||
export * from "./validateOidcCallback";
|
||||
250
server/routers/idp/validateOidcCallback.ts
Normal file
250
server/routers/idp/validateOidcCallback.ts
Normal file
@@ -0,0 +1,250 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
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,
|
||||
idpOrg,
|
||||
idpUser,
|
||||
idpUserOrg,
|
||||
Role,
|
||||
roles
|
||||
} from "@server/db/schemas";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import * as arctic from "arctic";
|
||||
import { generateOidcRedirectUrl } from "@server/lib/idp/generateRedirectUrl";
|
||||
import jmespath from "jmespath";
|
||||
import { generateId, generateSessionToken } from "@server/auth/sessions/app";
|
||||
import {
|
||||
createIdpSession,
|
||||
serializeIdpSessionCookie
|
||||
} from "@server/auth/sessions/orgIdp";
|
||||
|
||||
const paramsSchema = z
|
||||
.object({
|
||||
orgId: z.string(),
|
||||
idpId: z.coerce.number()
|
||||
})
|
||||
.strict();
|
||||
|
||||
const bodySchema = z.object({
|
||||
code: z.string().nonempty(),
|
||||
codeVerifier: z.string().nonempty()
|
||||
});
|
||||
|
||||
export type ValidateOidcUrlCallbackResponse = {};
|
||||
|
||||
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()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { orgId, idpId } = parsedParams.data;
|
||||
|
||||
const parsedBody = bodySchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { code, codeVerifier } = parsedBody.data;
|
||||
|
||||
const [existingIdp] = await db
|
||||
.select()
|
||||
.from(idp)
|
||||
.innerJoin(idpOrg, eq(idp.idpId, idpOrg.idpId))
|
||||
.innerJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId))
|
||||
.where(
|
||||
and(
|
||||
eq(idpOrg.orgId, orgId),
|
||||
eq(idp.type, "oidc"),
|
||||
eq(idp.idpId, idpId)
|
||||
)
|
||||
);
|
||||
|
||||
if (!existingIdp) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"IdP not found for the organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const redirectUrl = generateOidcRedirectUrl(
|
||||
orgId,
|
||||
existingIdp.idp.idpId
|
||||
);
|
||||
const client = new arctic.OAuth2Client(
|
||||
existingIdp.idpOidcConfig.clientId,
|
||||
existingIdp.idpOidcConfig.clientSecret,
|
||||
redirectUrl
|
||||
);
|
||||
|
||||
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 });
|
||||
|
||||
const email = jmespath.search(
|
||||
claims,
|
||||
existingIdp.idpOidcConfig.emailPath || "email"
|
||||
);
|
||||
const name = jmespath.search(
|
||||
claims,
|
||||
existingIdp.idpOidcConfig.namePath || "name"
|
||||
);
|
||||
|
||||
logger.debug("User email", { email });
|
||||
logger.debug("User name", { name });
|
||||
|
||||
const [existingIdpUser] = await db
|
||||
.select()
|
||||
.from(idpUser)
|
||||
.innerJoin(idpUserOrg, eq(idpUserOrg.idpUserId, idpUser.idpUserId))
|
||||
.where(
|
||||
and(
|
||||
eq(idpUserOrg.orgId, orgId),
|
||||
eq(idpUser.idpId, existingIdp.idp.idpId)
|
||||
)
|
||||
);
|
||||
|
||||
let userRole: Role | undefined;
|
||||
if (existingIdp.idpOidcConfig.roleMapping) {
|
||||
const roleName = jmespath.search(
|
||||
claims,
|
||||
existingIdp.idpOidcConfig.roleMapping
|
||||
);
|
||||
|
||||
if (!roleName) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Role mapping not found in the ID token"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const [roleRes] = await db
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.orgId, orgId), eq(roles.name, roleName)));
|
||||
|
||||
userRole = roleRes;
|
||||
} else {
|
||||
// TODO: Get the default role for this IDP?
|
||||
}
|
||||
|
||||
logger.debug("User role", { userRole });
|
||||
|
||||
if (!userRole) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Role not found for the user"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
let userId: string | undefined = existingIdpUser?.idpUser.idpUserId;
|
||||
if (!existingIdpUser) {
|
||||
if (existingIdp.idpOidcConfig.autoProvision) {
|
||||
// TODO: Create the user and automatically assign roles
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
const idpUserId = generateId(15);
|
||||
|
||||
const [idpUserRes] = await trx
|
||||
.insert(idpUser)
|
||||
.values({
|
||||
idpUserId,
|
||||
idpId: existingIdp.idp.idpId,
|
||||
identifier: userIdentifier,
|
||||
email,
|
||||
name
|
||||
})
|
||||
.returning();
|
||||
|
||||
await trx.insert(idpUserOrg).values({
|
||||
idpUserId: idpUserRes.idpUserId,
|
||||
orgId,
|
||||
roleId: userRole.roleId
|
||||
});
|
||||
|
||||
userId = idpUserRes.idpUserId;
|
||||
});
|
||||
} else {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"User not found and auto-provisioning is disabled"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const token = generateSessionToken();
|
||||
const sess = await createIdpSession(token, userId);
|
||||
const cookie = serializeIdpSessionCookie(
|
||||
`p_idp_${orgId}.${idpId}`,
|
||||
sess.idpSessionId,
|
||||
req.protocol === "https",
|
||||
new Date(sess.expiresAt)
|
||||
);
|
||||
|
||||
res.setHeader("Set-Cookie", cookie);
|
||||
|
||||
return response<ValidateOidcUrlCallbackResponse>(res, {
|
||||
data: {},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "OIDC callback validated successfully",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user