refactor(api): ♻️ More OpenAPI refactoring work

This commit is contained in:
Jesse Wierzbinski 2024-09-16 15:29:09 +02:00
parent 6d9e385a04
commit 5aa1c4e625
No known key found for this signature in database
35 changed files with 4883 additions and 1815 deletions

View file

@ -1,7 +1,7 @@
import { apiRoute, applyConfig, handleZodError } from "@/api";
import { apiRoute, applyConfig } from "@/api";
import { randomString } from "@/math";
import { setCookie } from "@hono/hono/cookie";
import { zValidator } from "@hono/zod-validator";
import { createRoute } from "@hono/zod-openapi";
import { and, eq, isNull } from "drizzle-orm";
import type { Context } from "hono";
import { SignJWT } from "jose";
@ -40,6 +40,24 @@ export const schemas = {
}),
};
const route = createRoute({
method: "get",
path: "/oauth/sso/{issuer}/callback",
summary: "SSO callback",
description:
"After the user has authenticated to an external OpenID provider, they are redirected here to complete the OAuth flow and get a code",
request: {
query: schemas.query,
params: schemas.param,
},
responses: {
302: {
description:
"Redirect to frontend's consent route, or redirect to login page with error",
},
},
});
const returnError = (
context: Context,
query: object,
@ -63,155 +81,124 @@ const returnError = (
);
};
/**
* OAuth Callback endpoint
* After the user has authenticated to an external OpenID provider,
* they are redirected here to complete the OAuth flow and get a code
*/
export default apiRoute((app) =>
app.on(
meta.allowedMethods,
meta.route,
zValidator("query", schemas.query, handleZodError),
zValidator("param", schemas.param, handleZodError),
async (context) => {
const currentUrl = new URL(context.req.url);
const redirectUrl = new URL(context.req.url);
app.openapi(route, async (context) => {
const currentUrl = new URL(context.req.url);
const redirectUrl = new URL(context.req.url);
// Correct some reverse proxies incorrectly setting the protocol as http, even if the original request was https
// Looking at you, Traefik
if (
new URL(config.http.base_url).protocol === "https:" &&
currentUrl.protocol === "http:"
) {
currentUrl.protocol = "https:";
redirectUrl.protocol = "https:";
}
// Correct some reverse proxies incorrectly setting the protocol as http, even if the original request was https
// Looking at you, Traefik
if (
new URL(config.http.base_url).protocol === "https:" &&
currentUrl.protocol === "http:"
) {
currentUrl.protocol = "https:";
redirectUrl.protocol = "https:";
}
// Remove state query parameter from URL
currentUrl.searchParams.delete("state");
redirectUrl.searchParams.delete("state");
// Remove issuer query parameter from URL (can cause redirect URI mismatches)
redirectUrl.searchParams.delete("iss");
redirectUrl.searchParams.delete("code");
const { issuer: issuerParam } = context.req.valid("param");
const { flow: flowId, user_id, link } = context.req.valid("query");
// Remove state query parameter from URL
currentUrl.searchParams.delete("state");
redirectUrl.searchParams.delete("state");
// Remove issuer query parameter from URL (can cause redirect URI mismatches)
redirectUrl.searchParams.delete("iss");
redirectUrl.searchParams.delete("code");
const { issuer: issuerParam } = context.req.valid("param");
const { flow: flowId, user_id, link } = context.req.valid("query");
const manager = new OAuthManager(issuerParam);
const manager = new OAuthManager(issuerParam);
const userInfo = await manager.automaticOidcFlow(
flowId,
currentUrl,
redirectUrl,
(error, message, app) =>
returnError(
context,
manager.processOAuth2Error(app),
error,
message,
const userInfo = await manager.automaticOidcFlow(
flowId,
currentUrl,
redirectUrl,
(error, message, app) =>
returnError(
context,
manager.processOAuth2Error(app),
error,
message,
),
);
if (userInfo instanceof Response) {
return userInfo;
}
const { sub, email, preferred_username, picture } = userInfo.userInfo;
const flow = userInfo.flow;
// If linking account
if (link && user_id) {
return await manager.linkUser(user_id, context, userInfo);
}
let userId = (
await db.query.OpenIdAccounts.findFirst({
where: (account, { eq, and }) =>
and(
eq(account.serverId, sub),
eq(account.issuerId, manager.issuer.id),
),
);
})
)?.userId;
if (userInfo instanceof Response) {
return userInfo;
}
if (!userId) {
// Register new user
if (config.signups.registration && config.oidc.allow_registration) {
let username =
preferred_username ??
email?.split("@")[0] ??
randomString(8, "hex");
const { sub, email, preferred_username, picture } =
userInfo.userInfo;
const flow = userInfo.flow;
// If linking account
if (link && user_id) {
return await manager.linkUser(user_id, context, userInfo);
}
let userId = (
await db.query.OpenIdAccounts.findFirst({
where: (account, { eq, and }) =>
and(
eq(account.serverId, sub),
eq(account.issuerId, manager.issuer.id),
),
})
)?.userId;
if (!userId) {
// Register new user
if (
config.signups.registration &&
config.oidc.allow_registration
) {
let username =
preferred_username ??
email?.split("@")[0] ??
randomString(8, "hex");
const usernameValidator = z
.string()
.regex(/^[a-z0-9_]+$/)
.min(3)
.max(config.validation.max_username_size)
.refine(
(value) =>
!config.validation.username_blacklist.includes(
value,
),
)
.refine((value) =>
config.filters.username.some((filter) =>
value.match(filter),
const usernameValidator = z
.string()
.regex(/^[a-z0-9_]+$/)
.min(3)
.max(config.validation.max_username_size)
.refine(
(value) =>
!config.validation.username_blacklist.includes(
value,
),
)
.refine(
async (value) =>
!(await User.fromSql(
and(
eq(Users.username, value),
isNull(Users.instanceId),
),
)),
);
try {
await usernameValidator.parseAsync(username);
} catch {
username = randomString(8, "hex");
}
const doesEmailExist = email
? !!(await User.fromSql(eq(Users.email, email)))
: false;
// Create new user
const user = await User.fromDataLocal({
email: doesEmailExist ? undefined : email,
username,
avatar: picture,
password: undefined,
});
// Link account
await manager.linkUserInDatabase(user.id, sub);
userId = user.id;
} else {
return returnError(
context,
{
redirect_uri: flow.application?.redirectUri,
client_id: flow.application?.clientId,
response_type: "code",
scope: flow.application?.scopes,
},
"invalid_request",
"No user found with that account",
)
.refine((value) =>
config.filters.username.some((filter) =>
value.match(filter),
),
)
.refine(
async (value) =>
!(await User.fromSql(
and(
eq(Users.username, value),
isNull(Users.instanceId),
),
)),
);
try {
await usernameValidator.parseAsync(username);
} catch {
username = randomString(8, "hex");
}
}
const user = await User.fromId(userId);
const doesEmailExist = email
? !!(await User.fromSql(eq(Users.email, email)))
: false;
if (!user) {
// Create new user
const user = await User.fromDataLocal({
email: doesEmailExist ? undefined : email,
username,
avatar: picture,
password: undefined,
});
// Link account
await manager.linkUserInDatabase(user.id, sub);
userId = user.id;
} else {
return returnError(
context,
{
@ -224,80 +211,96 @@ export default apiRoute((app) =>
"No user found with that account",
);
}
}
if (!user.hasPermission(RolePermissions.OAuth)) {
return returnError(
context,
{
redirect_uri: flow.application?.redirectUri,
client_id: flow.application?.clientId,
response_type: "code",
scope: flow.application?.scopes,
},
"invalid_request",
`User does not have the '${RolePermissions.OAuth}' permission`,
);
}
const user = await User.fromId(userId);
if (!flow.application) {
return context.json({ error: "Application not found" }, 500);
}
const code = randomString(32, "hex");
await db.insert(Tokens).values({
accessToken: randomString(64, "base64url"),
code: code,
scope: flow.application.scopes,
tokenType: TokenType.Bearer,
userId: user.id,
applicationId: flow.application.id,
});
// Try and import the key
const privateKey = await crypto.subtle.importKey(
"pkcs8",
Buffer.from(config.oidc.keys?.private ?? "", "base64"),
"Ed25519",
false,
["sign"],
if (!user) {
return returnError(
context,
{
redirect_uri: flow.application?.redirectUri,
client_id: flow.application?.clientId,
response_type: "code",
scope: flow.application?.scopes,
},
"invalid_request",
"No user found with that account",
);
}
// Generate JWT
const jwt = await new SignJWT({
sub: user.id,
iss: new URL(config.http.base_url).origin,
aud: flow.application.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(privateKey);
// Redirect back to application
setCookie(context, "jwt", jwt, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: 60 * 60,
});
return context.redirect(
new URL(
`${config.frontend.routes.consent}?${new URLSearchParams({
redirect_uri: flow.application.redirectUri,
code,
client_id: flow.application.clientId,
application: flow.application.name,
website: flow.application.website ?? "",
scope: flow.application.scopes,
response_type: "code",
}).toString()}`,
config.http.base_url,
).toString(),
if (!user.hasPermission(RolePermissions.OAuth)) {
return returnError(
context,
{
redirect_uri: flow.application?.redirectUri,
client_id: flow.application?.clientId,
response_type: "code",
scope: flow.application?.scopes,
},
"invalid_request",
`User does not have the '${RolePermissions.OAuth}' permission`,
);
},
),
}
if (!flow.application) {
return context.json({ error: "Application not found" }, 500);
}
const code = randomString(32, "hex");
await db.insert(Tokens).values({
accessToken: randomString(64, "base64url"),
code: code,
scope: flow.application.scopes,
tokenType: TokenType.Bearer,
userId: user.id,
applicationId: flow.application.id,
});
// Try and import the key
const privateKey = await crypto.subtle.importKey(
"pkcs8",
Buffer.from(config.oidc.keys?.private ?? "", "base64"),
"Ed25519",
false,
["sign"],
);
// Generate JWT
const jwt = await new SignJWT({
sub: user.id,
iss: new URL(config.http.base_url).origin,
aud: flow.application.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(privateKey);
// Redirect back to application
setCookie(context, "jwt", jwt, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: 60 * 60,
});
return context.redirect(
new URL(
`${config.frontend.routes.consent}?${new URLSearchParams({
redirect_uri: flow.application.redirectUri,
code,
client_id: flow.application.clientId,
application: flow.application.name,
website: flow.application.website ?? "",
scope: flow.application.scopes,
response_type: "code",
}).toString()}`,
config.http.base_url,
).toString(),
);
}),
);

View file

@ -1,6 +1,6 @@
import { apiRoute, applyConfig, handleZodError } from "@/api";
import { apiRoute, applyConfig } from "@/api";
import { oauthRedirectUri } from "@/constants";
import { zValidator } from "@hono/zod-validator";
import { createRoute } from "@hono/zod-openapi";
import type { Context } from "hono";
import {
calculatePKCECodeChallenge,
@ -35,6 +35,21 @@ export const schemas = {
}),
};
const route = createRoute({
method: "get",
path: "/oauth/sso",
summary: "Initiate SSO login flow",
request: {
query: schemas.query,
},
responses: {
302: {
description:
"Redirect to SSO login, or redirect to login page with error",
},
},
});
const returnError = (
context: Context,
query: object,
@ -59,87 +74,80 @@ const returnError = (
};
export default apiRoute((app) =>
app.on(
meta.allowedMethods,
meta.route,
zValidator("query", schemas.query, handleZodError),
async (context) => {
// This is the Versia client's client_id, not the external OAuth provider's client_id
const { issuer: issuerId, client_id } = context.req.valid("query");
const body = await context.req.query();
app.openapi(route, async (context) => {
// This is the Versia client's client_id, not the external OAuth provider's client_id
const { issuer: issuerId, client_id } = context.req.valid("query");
const body = await context.req.query();
if (!client_id || client_id === "undefined") {
return returnError(
context,
body,
"invalid_request",
"client_id is required",
);
}
const issuer = config.oidc.providers.find(
(provider) => provider.id === issuerId,
if (!client_id || client_id === "undefined") {
return returnError(
context,
body,
"invalid_request",
"client_id is required",
);
}
if (!issuer) {
return returnError(
context,
body,
"invalid_request",
"issuer is invalid",
);
}
const issuer = config.oidc.providers.find(
(provider) => provider.id === issuerId,
);
const issuerUrl = new URL(issuer.url);
const authServer = await discoveryRequest(issuerUrl, {
algorithm: "oidc",
}).then((res) => processDiscoveryResponse(issuerUrl, res));
const codeVerifier = generateRandomCodeVerifier();
const application = await db.query.Applications.findFirst({
where: (application, { eq }) =>
eq(application.clientId, client_id),
});
if (!application) {
return returnError(
context,
body,
"invalid_request",
"client_id is invalid",
);
}
// Store into database
const newFlow = (
await db
.insert(OpenIdLoginFlows)
.values({
codeVerifier,
applicationId: application.id,
issuerId,
})
.returning()
)[0];
const codeChallenge =
await calculatePKCECodeChallenge(codeVerifier);
return context.redirect(
`${authServer.authorization_endpoint}?${new URLSearchParams({
client_id: issuer.client_id,
redirect_uri: `${oauthRedirectUri(issuerId)}?flow=${
newFlow.id
}`,
response_type: "code",
scope: "openid profile email",
// PKCE
code_challenge_method: "S256",
code_challenge: codeChallenge,
}).toString()}`,
if (!issuer) {
return returnError(
context,
body,
"invalid_request",
"issuer is invalid",
);
},
),
}
const issuerUrl = new URL(issuer.url);
const authServer = await discoveryRequest(issuerUrl, {
algorithm: "oidc",
}).then((res) => processDiscoveryResponse(issuerUrl, res));
const codeVerifier = generateRandomCodeVerifier();
const application = await db.query.Applications.findFirst({
where: (application, { eq }) => eq(application.clientId, client_id),
});
if (!application) {
return returnError(
context,
body,
"invalid_request",
"client_id is invalid",
);
}
// Store into database
const newFlow = (
await db
.insert(OpenIdLoginFlows)
.values({
codeVerifier,
applicationId: application.id,
issuerId,
})
.returning()
)[0];
const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
return context.redirect(
`${authServer.authorization_endpoint}?${new URLSearchParams({
client_id: issuer.client_id,
redirect_uri: `${oauthRedirectUri(issuerId)}?flow=${
newFlow.id
}`,
response_type: "code",
scope: "openid profile email",
// PKCE
code_challenge_method: "S256",
code_challenge: codeChallenge,
}).toString()}`,
);
}),
);

View file

@ -1,5 +1,5 @@
import { apiRoute, applyConfig, handleZodError, jsonOrForm } from "@/api";
import { zValidator } from "@hono/zod-validator";
import { apiRoute, applyConfig, jsonOrForm } from "@/api";
import { createRoute } from "@hono/zod-openapi";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "~/drizzle/db";
@ -50,90 +50,137 @@ export const schemas = {
}),
};
const route = createRoute({
method: "post",
path: "/oauth/token",
summary: "Get token",
middleware: [jsonOrForm()],
request: {
body: {
content: {
"application/json": {
schema: schemas.json,
},
"application/x-www-form-urlencoded": {
schema: schemas.json,
},
"multipart/form-data": {
schema: schemas.json,
},
},
},
},
responses: {
200: {
description: "Token",
content: {
"application/json": {
schema: z.object({
access_token: z.string(),
token_type: z.string(),
expires_in: z.number().optional().nullable(),
id_token: z.string().optional().nullable(),
refresh_token: z.string().optional().nullable(),
scope: z.string().optional(),
created_at: z.number(),
}),
},
},
},
401: {
description: "Authorization error",
content: {
"application/json": {
schema: z.object({
error: z.string(),
error_description: z.string(),
}),
},
},
},
},
});
export default apiRoute((app) =>
app.on(
meta.allowedMethods,
meta.route,
jsonOrForm(),
zValidator("json", schemas.json, handleZodError),
async (context) => {
const { grant_type, code, redirect_uri, client_id, client_secret } =
context.req.valid("json");
app.openapi(route, async (context) => {
const { grant_type, code, redirect_uri, client_id, client_secret } =
context.req.valid("json");
switch (grant_type) {
case "authorization_code": {
if (!code) {
return context.json(
{
error: "invalid_request",
error_description: "Code is required",
},
401,
);
}
switch (grant_type) {
case "authorization_code": {
if (!code) {
return context.json(
{
error: "invalid_request",
error_description: "Code is required",
},
401,
);
}
if (!redirect_uri) {
return context.json(
{
error: "invalid_request",
error_description: "Redirect URI is required",
},
401,
);
}
if (!redirect_uri) {
return context.json(
{
error: "invalid_request",
error_description: "Redirect URI is required",
},
401,
);
}
if (!client_id) {
return context.json(
{
error: "invalid_request",
error_description: "Client ID is required",
},
401,
);
}
if (!client_id) {
return context.json(
{
error: "invalid_request",
error_description: "Client ID is required",
},
401,
);
}
// Verify the client_secret
const client = await db.query.Applications.findFirst({
where: (application, { eq }) =>
eq(application.clientId, client_id),
});
// Verify the client_secret
const client = await db.query.Applications.findFirst({
where: (application, { eq }) =>
eq(application.clientId, client_id),
});
if (!client || client.secret !== client_secret) {
return context.json(
{
error: "invalid_client",
error_description: "Invalid client credentials",
},
401,
);
}
if (!client || client.secret !== client_secret) {
return context.json(
{
error: "invalid_client",
error_description: "Invalid client credentials",
},
401,
);
}
const token = await db.query.Tokens.findFirst({
where: (token, { eq, and }) =>
and(
eq(token.code, code),
eq(token.redirectUri, decodeURI(redirect_uri)),
eq(token.clientId, client_id),
),
});
const token = await db.query.Tokens.findFirst({
where: (token, { eq, and }) =>
and(
eq(token.code, code),
eq(token.redirectUri, decodeURI(redirect_uri)),
eq(token.clientId, client_id),
),
});
if (!token) {
return context.json(
{
error: "invalid_grant",
error_description: "Code not found",
},
401,
);
}
if (!token) {
return context.json(
{
error: "invalid_grant",
error_description: "Code not found",
},
401,
);
}
// Invalidate the code
await db
.update(Tokens)
.set({ code: null })
.where(eq(Tokens.id, token.id));
// Invalidate the code
await db
.update(Tokens)
.set({ code: null })
.where(eq(Tokens.id, token.id));
return context.json({
return context.json(
{
access_token: token.accessToken,
token_type: "Bearer",
expires_in: token.expiresAt
@ -149,17 +196,18 @@ export default apiRoute((app) =>
created_at: Math.floor(
new Date(token.createdAt).getTime() / 1000,
),
});
}
},
200,
);
}
}
return context.json(
{
error: "unsupported_grant_type",
error_description: "Unsupported grant type",
},
401,
);
},
),
return context.json(
{
error: "unsupported_grant_type",
error_description: "Unsupported grant type",
},
401,
);
}),
);