Skip to content

Commit

Permalink
Merge pull request #4297 from coralproject/fix/comment-oembed-cors
Browse files Browse the repository at this point in the history
[CORL-2872]: Add cors to single comment embed oembed endpoint
  • Loading branch information
tessalt committed Jul 19, 2023
2 parents 9de5be9 + d9cef98 commit da6cfaf
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
33 changes: 30 additions & 3 deletions src/core/server/app/middleware/commentEmbedWhitelisted.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { AppOptions } from "coral-server/app";
import { CorsOptionsDelegate } from "cors";

import { MongoContext } from "coral-server/data/context";
import { retrieveComment } from "coral-server/models/comment";
import { retrieveSite } from "coral-server/models/site";
import { RequestHandler } from "coral-server/types/express";
import { Request, RequestHandler } from "coral-server/types/express";

import { AppOptions } from "..";
import { getRequesterOrigin } from "../helpers";

export const commentEmbedWhitelisted =
Expand All @@ -29,7 +32,10 @@ export const commentEmbedWhitelisted =
if (siteID) {
const site = await retrieveSite(mongo, tenant.id, siteID);
if (site) {
const origin = getRequesterOrigin(req);
let origin: string | null | undefined = getRequesterOrigin(req);
if (!origin) {
origin = req.header("Origin");
}
if (origin) {
if (site.allowedOrigins.includes(origin)) {
return next();
Expand All @@ -40,3 +46,24 @@ export const commentEmbedWhitelisted =
}
res.sendStatus(401);
};

/**
* Creates the options for the "cors" middleware which whitelists
* site origins for the single comment embed.
*
* @param mongo the database connection
* @returns CorsOptionsDelegate
*/
export function createCommentEmbedCorsOptionsDelegate(
mongo: MongoContext
): CorsOptionsDelegate {
return async (req: Request, callback) => {
const originHeader = req.header("Origin");
const tenantID = req.coral.tenant?.id;
if (!originHeader || !tenantID) {
callback(null, { origin: false }); // disable CORS for this request
return;
}
callback(null, { origin: true });
};
}
3 changes: 3 additions & 0 deletions src/core/server/app/router/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import cors from "cors";
import express from "express";
import passport from "passport";

Expand All @@ -12,6 +13,7 @@ import {
authenticate,
commentEmbedWhitelisted,
corsWhitelisted,
createCommentEmbedCorsOptionsDelegate,
cspSiteMiddleware,
JSONErrorHandler,
jsonMiddleware,
Expand Down Expand Up @@ -96,6 +98,7 @@ export function createAPIRouter(app: AppOptions, options: RouterOptions) {
router.get(
"/services/oembed",
commentEmbedWhitelisted(app),
cors(createCommentEmbedCorsOptionsDelegate(app.mongo)),
oembedProviderHandler(app)
);
router.get(
Expand Down

0 comments on commit da6cfaf

Please sign in to comment.