From e2dd6221f86fd83a72cc2c3e6b65cedbe9b018be Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 27 Apr 2025 10:55:05 -0400 Subject: [PATCH] Extract subdomain auth redirect (#9070) * Extract subdomain auth redirect * docs --- plugins/github/server/api/github.ts | 45 ++++++--------------- plugins/linear/server/api/linear.ts | 53 ++++++------------------- plugins/notion/server/api/notion.ts | 53 ++++++------------------- plugins/slack/server/auth/slack.ts | 38 ++++++------------ server/middlewares/apexAuthRedirect.ts | 54 ++++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 142 deletions(-) create mode 100644 server/middlewares/apexAuthRedirect.ts diff --git a/plugins/github/server/api/github.ts b/plugins/github/server/api/github.ts index 993b630b94..b961df3132 100644 --- a/plugins/github/server/api/github.ts +++ b/plugins/github/server/api/github.ts @@ -1,13 +1,12 @@ import Router from "koa-router"; import find from "lodash/find"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; import { createContext } from "@server/context"; -import Logger from "@server/logging/Logger"; +import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { IntegrationAuthentication, Integration, Team } from "@server/models"; +import { IntegrationAuthentication, Integration } from "@server/models"; import { APIContext } from "@server/types"; import { GitHubUtils } from "../../shared/GitHubUtils"; import { GitHub } from "../github"; @@ -17,10 +16,17 @@ const router = new Router(); router.get( "github.callback", - auth({ - optional: true, - }), + auth({ optional: true }), validate(T.GitHubCallbackSchema), + apexAuthRedirect({ + getTeamId: (ctx) => ctx.input.query.state, + getRedirectPath: (ctx, team) => + GitHubUtils.callbackUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }), + getErrorPath: () => GitHubUtils.errorUrl("unauthenticated"), + }), transaction(), async (ctx: APIContext) => { const { @@ -43,33 +49,6 @@ router.get( return; } - // this code block accounts for the root domain being unable to - // access authentication for subdomains. We must forward to the appropriate - // subdomain to complete the oauth flow - if (!user) { - if (teamId) { - try { - const team = await Team.findByPk(teamId, { - rejectOnEmpty: true, - transaction, - }); - return parseDomain(ctx.host).teamSubdomain === team.subdomain - ? ctx.redirect("/") - : ctx.redirectOnClient( - GitHubUtils.callbackUrl({ - baseUrl: team.url, - params: ctx.request.querystring, - }) - ); - } catch (err) { - Logger.error(`Error fetching team for teamId: ${teamId}!`, err); - return ctx.redirect(GitHubUtils.errorUrl("unauthenticated")); - } - } else { - return ctx.redirect(GitHubUtils.errorUrl("unauthenticated")); - } - } - const client = await GitHub.authenticateAsUser(code!, teamId); const installationsByUser = await client.requestAppInstallations(); const installation = find( diff --git a/plugins/linear/server/api/linear.ts b/plugins/linear/server/api/linear.ts index db8469b176..4b879a4f97 100644 --- a/plugins/linear/server/api/linear.ts +++ b/plugins/linear/server/api/linear.ts @@ -1,11 +1,10 @@ import Router from "koa-router"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; -import Logger from "@server/logging/Logger"; +import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { IntegrationAuthentication, Integration, Team } from "@server/models"; +import { IntegrationAuthentication, Integration } from "@server/models"; import { APIContext } from "@server/types"; import { Linear } from "../linear"; import UploadLinearWorkspaceLogoTask from "../tasks/UploadLinearWorkspaceLogoTask"; @@ -20,49 +19,21 @@ router.get( optional: true, }), validate(T.LinearCallbackSchema), + apexAuthRedirect({ + getTeamId: (ctx) => LinearUtils.parseState(ctx.input.query.state)?.teamId, + getRedirectPath: (ctx, team) => + LinearUtils.callbackUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }), + getErrorPath: () => LinearUtils.errorUrl("unauthenticated"), + }), transaction(), async (ctx: APIContext) => { - const { code, state, error } = ctx.input.query; + const { code, error } = ctx.input.query; const { user } = ctx.state.auth; const { transaction } = ctx.state; - let parsedState; - try { - parsedState = LinearUtils.parseState(state); - } catch { - ctx.redirect(LinearUtils.errorUrl("invalid_state")); - return; - } - - const { teamId } = parsedState; - - // this code block accounts for the root domain being unable to - // access authentication for subdomains. We must forward to the appropriate - // subdomain to complete the oauth flow - if (!user) { - if (teamId) { - try { - const team = await Team.findByPk(teamId, { - rejectOnEmpty: true, - transaction, - }); - return parseDomain(ctx.host).teamSubdomain === team.subdomain - ? ctx.redirect("/") - : ctx.redirectOnClient( - LinearUtils.callbackUrl({ - baseUrl: team.url, - params: ctx.request.querystring, - }) - ); - } catch (err) { - Logger.error(`Error fetching team for teamId: ${teamId}!`, err); - return ctx.redirect(LinearUtils.errorUrl("unauthenticated")); - } - } else { - return ctx.redirect(LinearUtils.errorUrl("unauthenticated")); - } - } - // Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain. if (error) { ctx.redirect(LinearUtils.errorUrl(error)); diff --git a/plugins/notion/server/api/notion.ts b/plugins/notion/server/api/notion.ts index 7a59eb7c4d..e9b534f204 100644 --- a/plugins/notion/server/api/notion.ts +++ b/plugins/notion/server/api/notion.ts @@ -1,11 +1,10 @@ import Router from "koa-router"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; -import Logger from "@server/logging/Logger"; +import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { Integration, IntegrationAuthentication, Team } from "@server/models"; +import { Integration, IntegrationAuthentication } from "@server/models"; import { APIContext } from "@server/types"; import { NotionClient } from "../notion"; import * as T from "./schema"; @@ -17,49 +16,21 @@ router.get( "notion.callback", auth({ optional: true }), validate(T.NotionCallbackSchema), + apexAuthRedirect({ + getTeamId: (ctx) => NotionUtils.parseState(ctx.input.query.state)?.teamId, + getRedirectPath: (ctx, team) => + NotionUtils.callbackUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }), + getErrorPath: () => NotionUtils.errorUrl("unauthenticated"), + }), transaction(), async (ctx: APIContext) => { - const { code, state, error } = ctx.input.query; + const { code, error } = ctx.input.query; const { user } = ctx.state.auth; const { transaction } = ctx.state; - let parsedState; - try { - parsedState = NotionUtils.parseState(state); - } catch { - ctx.redirect(NotionUtils.errorUrl("invalid_state")); - return; - } - - const { teamId } = parsedState; - - // This code block accounts for the root domain being unable to access authentication for subdomains. - // We must forward to the appropriate subdomain to complete the oauth flow. - if (!user) { - if (teamId) { - try { - const team = await Team.findByPk(teamId, { - rejectOnEmpty: true, - transaction, - }); - - return parseDomain(ctx.host).teamSubdomain === team.subdomain - ? ctx.redirect("/") - : ctx.redirectOnClient( - NotionUtils.callbackUrl({ - baseUrl: team.url, - params: ctx.request.querystring, - }) - ); - } catch (err) { - Logger.error(`Error fetching team for teamId: ${teamId}!`, err); - return ctx.redirect(NotionUtils.errorUrl("unauthenticated")); - } - } else { - return ctx.redirect(NotionUtils.errorUrl("unauthenticated")); - } - } - // Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain. if (error) { ctx.redirect(NotionUtils.errorUrl(error)); diff --git a/plugins/slack/server/auth/slack.ts b/plugins/slack/server/auth/slack.ts index 58064c779b..e703193353 100644 --- a/plugins/slack/server/auth/slack.ts +++ b/plugins/slack/server/auth/slack.ts @@ -4,16 +4,15 @@ import Router from "koa-router"; import { Profile } from "passport"; import { Strategy as SlackStrategy } from "passport-slack-oauth2"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; import accountProvisioner from "@server/commands/accountProvisioner"; import { ValidationError } from "@server/errors"; +import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; import auth from "@server/middlewares/authentication"; import passportMiddleware from "@server/middlewares/passport"; import validate from "@server/middlewares/validate"; import { IntegrationAuthentication, Integration, - Team, User, Collection, } from "@server/models"; @@ -126,6 +125,15 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { "slack.post", auth({ optional: true }), validate(T.SlackPostSchema), + apexAuthRedirect({ + getTeamId: (ctx) => SlackUtils.parseState(ctx.input.query.state)?.teamId, + getRedirectPath: (ctx, team) => + SlackUtils.connectUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }), + getErrorPath: () => SlackUtils.errorUrl("unauthenticated"), + }), async (ctx: APIContext) => { const { code, error, state } = ctx.input.query; const { user } = ctx.state.auth; @@ -144,31 +152,7 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { throw ValidationError("Invalid state"); } - const { teamId, collectionId, type } = parsedState; - - // This code block accounts for the root domain being unable to access authentication for - // subdomains. We must forward to the appropriate subdomain to complete the OAuth flow. - if (!user) { - if (teamId) { - try { - const team = await Team.findByPk(teamId, { - rejectOnEmpty: true, - }); - return parseDomain(ctx.host).teamSubdomain === team.subdomain - ? ctx.redirect("/") - : ctx.redirectOnClient( - SlackUtils.connectUrl({ - baseUrl: team.url, - params: ctx.request.querystring, - }) - ); - } catch (err) { - return ctx.redirect(SlackUtils.errorUrl("unauthenticated")); - } - } else { - return ctx.redirect(SlackUtils.errorUrl("unauthenticated")); - } - } + const { collectionId, type } = parsedState; switch (type) { case IntegrationType.Post: { diff --git a/server/middlewares/apexAuthRedirect.ts b/server/middlewares/apexAuthRedirect.ts new file mode 100644 index 0000000000..6b959b7273 --- /dev/null +++ b/server/middlewares/apexAuthRedirect.ts @@ -0,0 +1,54 @@ +import { Next } from "koa"; +import { parseDomain } from "@shared/utils/domains"; +import { Team } from "@server/models"; +import { APIContext } from "@server/types"; + +/** + * An authentication middleware that should be used on routes that return from external auth flows + * to the apex domain. In these cases the user will be redirected to the correct subdomain where + * they are authenticated. + * + * @param options Options for the middleware + * @returns Koa middleware function + */ +export default function apexAuthRedirect({ + getTeamId, + getRedirectPath, + getErrorPath, +}: { + /** Get the team ID for the current request */ + getTeamId: (ctx: APIContext) => string | null | undefined; + /** Get the redirect URL for the given team ID */ + getRedirectPath: (ctx: APIContext, team: Team) => string; + /** Get the error URL for the current request */ + getErrorPath: (ctx: APIContext) => string; +}) { + return async function apexAuthRedirectMiddleware( + ctx: APIContext, + next: Next + ) { + const { user } = ctx.state.auth; + if (user) { + return next(); + } + + const teamId = getTeamId(ctx); + + if (teamId) { + try { + const team = await Team.findByPk(teamId, { + attributes: ["id", "subdomain"], + rejectOnEmpty: true, + }); + + return parseDomain(ctx.host).teamSubdomain === team.subdomain + ? ctx.redirect("/") + : ctx.redirectOnClient(getRedirectPath(ctx, team)); + } catch (err) { + return ctx.redirect(getErrorPath(ctx)); + } + } else { + return ctx.redirect(getErrorPath(ctx)); + } + }; +}