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

feat(cubejs-server): Integrated support for TLS #213

Merged
merged 5 commits into from
Sep 27, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 12 additions & 0 deletions packages/cubejs-server/__mocks__/http.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const http = jest.requireActual("http");

http.__mockServer = {
listen: jest.fn((opts, cb) => cb && cb(null)),
close: jest.fn((cb) => cb && cb(null)),
delete: jest.fn()
};

http.createServer = jest.fn(() => http.__mockServer);


module.exports = http;
13 changes: 13 additions & 0 deletions packages/cubejs-server/__mocks__/https.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const https = jest.requireActual("https");

https.__mockServer = {
listen: jest.fn((opts, cb) => cb && cb(null)),
close: jest.fn((cb) => cb && cb(null)),
delete: jest.fn(),
setSecureContext: jest.fn()
};

https.createServer = jest.fn(() => https.__mockServer);

module.exports = https;

11 changes: 11 additions & 0 deletions packages/cubejs-server/__snapshots__/index.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`CubeServer listen given that CUBEJS_ENABLE_TLS is true, should create an http server listening to PORT to redirect to https 1`] = `
"(req, res) => {
res.writeHead(301, {
// FIXME: Does this work if the port is not 443?
philippefutureboy marked this conversation as resolved.
Show resolved Hide resolved
Location: \`https://\${req.headers.host}\${req.url}\`
});
res.end();
}"
`;
88 changes: 88 additions & 0 deletions packages/cubejs-server/config/env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"use strict";

const fs = require("fs");
const path = require("path");
const paths = require("./paths");

// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve("./paths")];

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
"The NODE_ENV environment variable is required but was not specified."
);
}

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== "test" && `${paths.dotenv}.local`,
paths.dotenv,
].filter(Boolean);

// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach((dotenvFile) => {
if (fs.existsSync(dotenvFile)) {
require("dotenv-expand")(
require("dotenv").config({
path: dotenvFile,
})
);
}
});

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebook/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || "")
.split(path.delimiter)
.filter((folder) => folder && !path.isAbsolute(folder))
.map((folder) => path.resolve(appDirectory, folder))
.join(path.delimiter);

// Grab NODE_ENV and CUBEJS_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const CUBEJS = /^CUBEJS_/i;

function getEnvironment() {
const raw = Object.keys(process.env)
.filter((key) => CUBEJS.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether we’re running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || "development",
}
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
"process.env": Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};

return { raw, stringified };
}

module.exports = getEnvironment;
33 changes: 33 additions & 0 deletions packages/cubejs-server/config/paths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"use strict";

const path = require("path");
const fs = require("fs");

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);
const moduleFileExtensions = ["js", "json"];

// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find((extension) =>
fs.existsSync(resolveFn(`${filePath}.${extension}`))
);

if (extension) {
return resolveFn(`${filePath}.${extension}`);
}

return resolveFn(`${filePath}.js`);
};

// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp(".env"),
appPath: resolveApp("."),
appIndexJs: resolveModule(resolveApp, "src/index.js"),
appPackageJson: resolveApp("package.json")
};

module.exports.moduleFileExtensions = moduleFileExtensions;
92 changes: 75 additions & 17 deletions packages/cubejs-server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,32 +5,90 @@ class CubejsServer {
constructor(config) {
config = config || {};
this.core = CubejsServerCore.create(config);
this.redirector = null;
this.server = null;
}

async listen() {
async listen(options = {}) {
try {
const express = require('express');
if (this.server) {
throw new Error("CubeServer is already listening");
}

const http = require("http");
const https = require("https");
const util = require("util");
const express = require("express");
const app = express();
const bodyParser = require('body-parser');
app.use(require('cors')());
app.use(bodyParser.json({ limit: '50mb' }));
const bodyParser = require("body-parser");
app.use(require("cors")());
app.use(bodyParser.json({ limit: "50mb" }));

await this.core.initApp(app);
const port = process.env.PORT || 4000;

return new Promise((resolve, reject) => {
app.listen(port, (err) => {
if (err) {
reject(err);
return;
}
resolve({ app, port });
});
})
const PORT = process.env.PORT || 4000;
const TLS_PORT = process.env.TLS_PORT || 4433;

if (process.env.CUBEJS_ENABLE_TLS === "true") {
this.redirector = http.createServer((req, res) => {
res.writeHead(301, {
// FIXME: Does this work if the port is not 443?
Location: `https://${req.headers.host}${req.url}`
});
res.end();
});
this.redirector.listen(PORT);
this.server = https.createServer(options, app);
this.server.listen(TLS_PORT, err => {
if (err) {
this.server = null;
this.redirector = null;
reject(err);
return;
}
this.redirector.close = util.promisify(this.redirector.close);
this.server.close = util.promisify(this.server.close);
resolve({ app, port: PORT, tlsPort: TLS_PORT, server: this.server });
});
} else {
this.server = http.createServer(options, app);
this.server.listen(PORT, err => {
if (err) {
this.server = null;
this.redirector = null;
reject(err);
return;
}
resolve({ app, port: PORT, server: this.server });
});
}
});
} catch (e) {
this.core.event &&
(await this.core.event("Dev Server Fatal Error", {
error: (e.stack || e.message || e).toString()
}));
throw e;
}
}

async close() {
try {
if (!this.server) {
throw new Error("CubeServer is not started.");
}
await this.server.close();
this.server = null;
if (this.redirector) {
await this.redirector.close();
this.redirector = null;
}
} catch (e) {
this.core.event && (await this.core.event('Dev Server Fatal Error', {
error: (e.stack || e.message || e).toString()
}));
this.core.event &&
(await this.core.event("Dev Server Fatal Error", {
error: (e.stack || e.message || e).toString()
}));
throw e;
}
}
Expand Down
Loading