From aa60f5ccea5877f9c04f237b64ff1dd63ba197d8 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 5 Apr 2025 09:51:39 -0400 Subject: [PATCH] Bring error handling to spec for oauth endpoints --- server/commands/userProvisioner.test.ts | 2 +- .../requestTracer.ts} | 4 +- .../CleanupOAuthAuthorizationCodeTask.test.ts | 37 +++++++++++ .../CleanupOAuthAuthorizationCodeTask.ts | 2 +- server/routes/api/index.ts | 4 +- server/routes/oauth/index.ts | 10 ++- .../oauth/middlewares/oauthErrorHandler.ts | 41 ++++++++++++ server/test/factories.ts | 63 ++++++++++++++++++- server/utils/oauth/OAuthInterface.ts | 37 ++++++++++- 9 files changed, 188 insertions(+), 12 deletions(-) rename server/{routes/api/middlewares/apiTracer.ts => middlewares/requestTracer.ts} (81%) create mode 100644 server/queues/tasks/CleanupOAuthAuthorizationCodeTask.test.ts create mode 100644 server/routes/oauth/middlewares/oauthErrorHandler.ts diff --git a/server/commands/userProvisioner.test.ts b/server/commands/userProvisioner.test.ts index 88bc6259f8..32a2e93b38 100644 --- a/server/commands/userProvisioner.test.ts +++ b/server/commands/userProvisioner.test.ts @@ -192,7 +192,7 @@ describe("userProvisioner", () => { it("should prefer isAdmin argument over defaultUserRole", async () => { const team = await buildTeam({ - defaultUserRole: "viewer", + defaultUserRole: UserRole.Viewer, }); const authenticationProviders = await team.$get("authenticationProviders"); const authenticationProvider = authenticationProviders[0]; diff --git a/server/routes/api/middlewares/apiTracer.ts b/server/middlewares/requestTracer.ts similarity index 81% rename from server/routes/api/middlewares/apiTracer.ts rename to server/middlewares/requestTracer.ts index 8d41dca22c..437437064a 100644 --- a/server/routes/api/middlewares/apiTracer.ts +++ b/server/middlewares/requestTracer.ts @@ -1,8 +1,8 @@ import { Context, Next } from "koa"; import { addTags, getRootSpanFromRequestContext } from "@server/logging/tracer"; -export default function apiTracer() { - return async function apiTracerMiddleware(ctx: Context, next: Next) { +export default function requestTracer() { + return async function requestTracerMiddleware(ctx: Context, next: Next) { const params = ctx.request.body ?? ctx.request.query; for (const key in params) { diff --git a/server/queues/tasks/CleanupOAuthAuthorizationCodeTask.test.ts b/server/queues/tasks/CleanupOAuthAuthorizationCodeTask.test.ts new file mode 100644 index 0000000000..f9fc17ae97 --- /dev/null +++ b/server/queues/tasks/CleanupOAuthAuthorizationCodeTask.test.ts @@ -0,0 +1,37 @@ +import { subMonths } from "date-fns"; +import { OAuthAuthorizationCode } from "@server/models"; +import { buildOAuthAuthorizationCode } from "@server/test/factories"; +import CleanupOAuthAuthorizationCodeTask from "./CleanupOAuthAuthorizationCodeTask"; + +const codeExists = async (code: OAuthAuthorizationCode) => { + const found = await OAuthAuthorizationCode.findByPk(code.id); + return !!found; +}; + +describe("CleanupOAuthAuthorizationCodeTask", () => { + it("should delete authorization codes expired more than one month ago", async () => { + const brandNewCode = await buildOAuthAuthorizationCode({ + expiresAt: new Date(), + }); + const oldCode = await buildOAuthAuthorizationCode({ + expiresAt: subMonths(new Date(), 2), + }); + + const task = new CleanupOAuthAuthorizationCodeTask(); + await task.perform(); + + expect(await codeExists(brandNewCode)).toBe(true); + expect(await codeExists(oldCode)).toBe(false); + }); + + it("should not delete codes that expired less than one month ago", async () => { + const recentCode = await buildOAuthAuthorizationCode({ + expiresAt: new Date(), + }); + + const task = new CleanupOAuthAuthorizationCodeTask(); + await task.perform(); + + expect(await codeExists(recentCode)).toBe(true); + }); +}); diff --git a/server/queues/tasks/CleanupOAuthAuthorizationCodeTask.ts b/server/queues/tasks/CleanupOAuthAuthorizationCodeTask.ts index 6a61407330..572c8c1ec6 100644 --- a/server/queues/tasks/CleanupOAuthAuthorizationCodeTask.ts +++ b/server/queues/tasks/CleanupOAuthAuthorizationCodeTask.ts @@ -1,7 +1,7 @@ import { subMonths } from "date-fns"; import { Op } from "sequelize"; import Logger from "@server/logging/Logger"; -import { OAuthAuthorizationCode } from "@server/models/oauth/OAuthAuthorizationCode"; +import { OAuthAuthorizationCode } from "@server/models"; import BaseTask, { TaskPriority, TaskSchedule } from "./BaseTask"; type Props = Record; diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index 0d6a7fb8b2..452ac4506b 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -5,6 +5,7 @@ import userAgent, { UserAgentContext } from "koa-useragent"; import env from "@server/env"; import { NotFoundError } from "@server/errors"; import coalesceBody from "@server/middlewares/coaleseBody"; +import requestTracer from "@server/middlewares/requestTracer"; import { AppState, AppContext } from "@server/types"; import { Hook, PluginManager } from "@server/utils/PluginManager"; import apiKeys from "./apiKeys"; @@ -25,7 +26,6 @@ import installation from "./installation"; import integrations from "./integrations"; import apiErrorHandler from "./middlewares/apiErrorHandler"; import apiResponse from "./middlewares/apiResponse"; -import apiTracer from "./middlewares/apiTracer"; import editor from "./middlewares/editor"; import notifications from "./notifications"; import oauthClients from "./oauthClients"; @@ -61,7 +61,7 @@ api.use( ); api.use(coalesceBody()); api.use(userAgent); -api.use(apiTracer()); +api.use(requestTracer()); api.use(apiResponse()); api.use(apiErrorHandler()); api.use(editor()); diff --git a/server/routes/oauth/index.ts b/server/routes/oauth/index.ts index 991e87a699..e48c094135 100644 --- a/server/routes/oauth/index.ts +++ b/server/routes/oauth/index.ts @@ -3,12 +3,12 @@ import Koa from "koa"; import bodyParser from "koa-body"; import Router from "koa-router"; import auth from "@server/middlewares/authentication"; +import requestTracer from "@server/middlewares/requestTracer"; import { OAuthInterface } from "@server/utils/oauth/OAuthInterface"; +import oauthErrorHandler from "./middlewares/oauthErrorHandler"; const app = new Koa(); - const router = new Router(); - const oauth = new OAuth2Server({ model: OAuthInterface, }); @@ -43,6 +43,10 @@ router.post("/token", async (ctx) => { const token = await oauth.token(request, response); + if (response.headers) { + ctx.set(response.headers); + } + ctx.body = { access_token: token.accessToken, refresh_token: token.refreshToken, @@ -54,6 +58,8 @@ router.post("/token", async (ctx) => { }; }); +app.use(requestTracer()); +app.use(oauthErrorHandler()); app.use(bodyParser()); app.use(router.routes()); diff --git a/server/routes/oauth/middlewares/oauthErrorHandler.ts b/server/routes/oauth/middlewares/oauthErrorHandler.ts new file mode 100644 index 0000000000..820afe08a2 --- /dev/null +++ b/server/routes/oauth/middlewares/oauthErrorHandler.ts @@ -0,0 +1,41 @@ +import { Context, Next } from "koa"; +import { + ValidationError as SequelizeValidationError, + EmptyResultError as SequelizeEmptyResultError, +} from "sequelize"; + +/** + * To adhere to the OAuth 2.0 specification, errors from the /token and /authorize routes + * follow the snake_case convention with `error` and `error_description` keys, rather than + * our standard error format. + */ +export default function oauthErrorHandler() { + return async function oauthErrorHandlerMiddleware(ctx: Context, next: Next) { + try { + await next(); + } catch (err) { + if (err instanceof SequelizeEmptyResultError) { + ctx.status = 404; + ctx.body = { + error: "invalid_request", + error_description: "Resource not found", + }; + return; + } + if (err instanceof SequelizeValidationError) { + ctx.status = 400; + ctx.body = { + error: "invalid_request", + error_description: err.errors[0].message, + }; + return; + } + + ctx.status = err.code || 500; + ctx.body = { + error: err.name, + error_description: err.message, + }; + } + }; +} diff --git a/server/test/factories.ts b/server/test/factories.ts index 921c75a9fc..9cce1b88c9 100644 --- a/server/test/factories.ts +++ b/server/test/factories.ts @@ -43,6 +43,9 @@ import { Pin, Comment, Import, + OAuthAuthorizationCode, + OAuthClient, + AuthenticationProvider, } from "@server/models"; import AttachmentHelper from "@server/models/helpers/AttachmentHelper"; @@ -137,7 +140,11 @@ export async function buildSubscription(overrides: Partial = {}) { }); } -export function buildTeam(overrides: Record = {}) { +export function buildTeam( + overrides: Omit, "authenticationProviders"> & { + authenticationProviders?: Partial[]; + } = {} +) { return Team.create( { name: faker.company.name(), @@ -691,6 +698,60 @@ export async function buildPin(overrides: Partial = {}): Promise { return Pin.create(overrides); } +export async function buildOAuthClient(overrides: Partial = {}) { + if (!overrides.teamId) { + const team = await buildTeam(); + overrides.teamId = team.id; + } + + if (!overrides.createdById) { + const user = await buildUser({ + teamId: overrides.teamId, + }); + overrides.createdById = user.id; + } + + return OAuthClient.create({ + name: faker.company.name(), + description: faker.lorem.paragraph(), + redirectUris: ["https://example.com/oauth/callback"], + published: true, + ...overrides, + }); +} + +export async function buildOAuthAuthorizationCode( + overrides: Partial = {} +) { + if (!overrides.userId) { + const user = await buildUser(); + overrides.userId = user.id; + } + + if (!overrides.expiresAt) { + overrides.expiresAt = new Date(); + } + + const code = randomstring.generate(32); + + let client; + if (overrides.oauthClientId) { + client = await OAuthClient.findByPk(overrides.oauthClientId, { + rejectOnEmpty: true, + }); + } else { + client = await buildOAuthClient(); + overrides.oauthClientId = client.id; + } + + return OAuthAuthorizationCode.create({ + authorizationCodeHash: OAuthAuthorizationCode.hash(code), + scope: ["read"], + redirectUri: client.redirectUris[0], + ...overrides, + }); +} + export function buildProseMirrorDoc(content: DeepPartial[]) { return Node.fromJSON(schema, { type: "doc", diff --git a/server/utils/oauth/OAuthInterface.ts b/server/utils/oauth/OAuthInterface.ts index e97fa7f099..b33aacf966 100644 --- a/server/utils/oauth/OAuthInterface.ts +++ b/server/utils/oauth/OAuthInterface.ts @@ -200,8 +200,39 @@ export const OAuthInterface: RefreshTokenModel & return false; }, - async validateRedirectUri() { - // TODO - return true; + /** + * Ensure the redirect URI is not plain HTTP. Custom protocols are allowed. + * + * @param uri The redirect URI to validate. + * @returns True if the URI is valid, false otherwise. + */ + async validateRedirectUri(uri) { + return !uri.startsWith("http://"); + }, + + /** + * Invoked to check if the requested scope is valid for a particular client/user combination. + * + * @param scope The requested scopes. + * @returns The scopes if valid, false otherwise. + */ + async validateScope(user, client, scope) { + if (!scope) { + return []; + } + + const scopes = Array.isArray(scope) ? scope : [scope]; + return scopes.some((s: string) => { + if (s === "read" || s === "write") { + return true; + } + + const periodCount = (s.match(/\./g) || []).length; + const colonCount = (s.match(/:/g) || []).length; + + return periodCount === 1 || colonCount === 1; + }) + ? scopes + : false; }, };