Skip to content

Commit

Permalink
Merge pull request #289 from moonrailgun/moonrailgun/assets-cors-pref…
Browse files Browse the repository at this point in the history
…light-req

Fix cors problem in assets
  • Loading branch information
icebob authored Jan 8, 2022
2 parents 137cc0e + e461070 commit 3880935
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 28 deletions.
74 changes: 46 additions & 28 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,31 @@ module.exports = {
this.sendError(req, res, err);
},

corsHandler(settings, req, res) {
// CORS headers
if (settings.cors) {
// Set CORS headers to `res`
this.writeCorsHeaders(settings, req, res, true);

// Is it a Preflight request?
if (req.method == "OPTIONS" && req.headers["access-control-request-method"]) {
// 204 - No content
res.writeHead(204, {
"Content-Length": "0"
});
res.end();

if (settings.logging) {
this.logResponse(req, res);
}

return true;
}
}

return false;
},

/**
* HTTP request handler. It is called from native NodeJS HTTP server.
*
Expand Down Expand Up @@ -351,6 +376,11 @@ module.exports = {
if (result == null) {
// Not routed.

const shouldBreak = this.corsHandler(this.settings, req, res); // check cors settings first
if(shouldBreak) {
return;
}

// Serve assets static files
if (this.serve) {
this.serve(req, res, err => {
Expand Down Expand Up @@ -391,24 +421,9 @@ module.exports = {
await composeThen.call(this, req, res, ...route.middlewares);
let params = {};

// CORS headers
if (route.cors) {
// Set CORS headers to `res`
this.writeCorsHeaders(route, req, res, true);

// Is it a Preflight request?
if (req.method == "OPTIONS" && req.headers["access-control-request-method"]) {
// 204 - No content
res.writeHead(204, {
"Content-Length": "0"
});
res.end();

if (route.logging)
this.logResponse(req, res);

return resolve(true);
}
const shouldBreak = this.corsHandler(route, req, res);
if(shouldBreak) {
return resolve(true);
}

// Merge params
Expand Down Expand Up @@ -865,16 +880,19 @@ module.exports = {

const ctx = req.$ctx;
let responseType = "application/json; charset=utf-8";
if (ctx.meta.$responseType) {
responseType = ctx.meta.$responseType;
}
if (ctx.meta.$responseHeaders) {
Object.keys(ctx.meta.$responseHeaders).forEach(key => {
if (key === "Content-Type" && !responseType)
responseType = ctx.meta.$responseHeaders[key];
else
res.setHeader(key, ctx.meta.$responseHeaders[key]);
});

if (ctx) {
if (ctx.meta.$responseType) {
responseType = ctx.meta.$responseType;
}
if (ctx.meta.$responseHeaders) {
Object.keys(ctx.meta.$responseHeaders).forEach(key => {
if (key === "Content-Type" && !responseType)
responseType = ctx.meta.$responseHeaders[key];
else
res.setHeader(key, ctx.meta.$responseHeaders[key]);
});
}
}

// Return with the error as JSON object
Expand Down
50 changes: 50 additions & 0 deletions test/integration/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,56 @@ describe("Test only assets", () => {

});

describe("Test assets with cors", () => {
let broker;
let service;
let server;

beforeAll(() => {
[broker, service, server] = setup({
assets: {
folder: path.join(__dirname, "..", "assets")
},
routes: null,
cors: {
origin: "a"
}
});
return broker.start();
});
afterAll(() => broker.stop());

it("pass cors and return 204", () => {
return request(server)
.options("/lorem.txt")
.set("Origin", "a")
.set("Access-Control-Request-Method", "GET")
.then(res => {
expect(res.statusCode).toBe(204);
});
});

it("pass cors (not exist file) and return 204", () => {
return request(server)
.options("/not-found.txt")
.set("Origin", "a")
.set("Access-Control-Request-Method", "GET")
.then(res => {
expect(res.statusCode).toBe(204);
});
});

it("not pass cors and return 204", () => {
return request(server)
.options("/lorem.txt")
.set("Origin", "b")
.set("Access-Control-Request-Method", "GET")
.then(res => {
expect(res.statusCode).toBe(403);
});
});
});

describe("Test assets & API route", () => {
let broker;
let service;
Expand Down
1 change: 1 addition & 0 deletions test/unit/service/httpHandler.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const MockContext = () => Object.assign({
logger: MockLogger(),
sendError: jest.fn(),
send404: jest.fn(),
corsHandler: jest.fn(() => false),
});

const MockRequest = () => Object.assign(jest.fn(), { headers: {} });
Expand Down

0 comments on commit 3880935

Please sign in to comment.