Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: disable new CORS rules for OS Proxy endpoint #2672

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions api.planx.uk/modules/ordnanceSurvey/controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useProxy } from "../../shared/middleware/proxy";
import { NextFunction, Request, Response } from "express";
import { IncomingMessage } from "http";
import { request } from "https";

export const OS_DOMAIN = "https://api.os.uk";

Expand Down Expand Up @@ -28,16 +29,19 @@ export const useOrdnanceSurveyProxy = async (

return useProxy({
target: OS_DOMAIN,
onProxyRes: (proxyRes) => setCORPHeaders(proxyRes),
onProxyRes: (proxyRes) => setCORPHeaders(proxyRes, req),
pathRewrite: (fullPath, req) => appendAPIKey(fullPath, req),
})(req, res, next);
};

const isValid = (req: Request): boolean =>
MAP_ALLOWLIST.some((re) => re.test(req.headers?.referer as string));

const setCORPHeaders = (proxyRes: IncomingMessage): void => {
const setCORPHeaders = (proxyRes: IncomingMessage, req: Request): void => {
proxyRes.headers["Cross-Origin-Resource-Policy"] = "cross-origin";
proxyRes.headers["Access-Control-Allow-Origin"] = req.headers.origin;
proxyRes.headers["Access-Control-Allow-Headers"] =
"Origin, X-Requested-With, Content-Type, Accept";
};

export const appendAPIKey = (fullPath: string, req: Request): string => {
Expand Down
14 changes: 13 additions & 1 deletion api.planx.uk/modules/ordnanceSurvey/routes.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import cors from "cors";
import { Router } from "express";
import { useOrdnanceSurveyProxy } from "./controller";

const router = Router();

router.use("/proxy/ordnance-survey", useOrdnanceSurveyProxy);
// Because this route already uses MAP_ALLOWLIST, disable global CORS checks so map repo docs and HTML templates are accessible
const osProxyCORSOptions = {
credentials: true,
methods: "*",
};

router.options("/proxy/ordnance-survey", cors(osProxyCORSOptions));
router.use(
"/proxy/ordnance-survey",
cors(osProxyCORSOptions),
useOrdnanceSurveyProxy,
);

export default router;
Loading