Newer
Older
#!/usr/bin/env node
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla BrowserID.
*
* The Initial Developer of the Original Code is Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
http = require('http');
urlparse = require('urlparse'),
express = require('express');
Lloyd Hilaiel
committed
wsapi = require('../lib/wsapi.js'),
httputils = require('../lib/httputils.js'),
secrets = require('../lib/secrets.js'),
db = require('../lib/db.js'),
config = require('../lib/configuration.js'),
heartbeat = require('../lib/heartbeat.js'),
metrics = require('../lib/metrics.js'),
Lloyd Hilaiel
committed
logger = require('../lib/logging.js').logger,
Lloyd Hilaiel
committed
forward = require('../lib/http_forward'),
Lloyd Hilaiel
committed
shutdown = require('../lib/shutdown'),
views = require('../lib/browserid/views.js');
Lloyd Hilaiel
committed
var app = undefined;
Lloyd Hilaiel
committed
app = express.createServer();
logger.info("browserid server starting up");
// verify that we have a keysigner configured
if (!config.get('keysigner_url')) {
logger.error('missing required configuration - url for the keysigner (KEYSIGNER_URL in env)');
process.exit(1);
}
Lloyd Hilaiel
committed
// verify that we have a dbwriter configured
if (!config.get('dbwriter_url')) {
logger.error('missing required configuration - url for the dbwriter (DBWRITER_URL in env)');
process.exit(1);
}
Lloyd Hilaiel
committed
// NOTE: ordering of middleware registration is important in this file, it is the
// order in which middleware will be invoked as requests are processed.
Lloyd Hilaiel
committed
// #1 - Setup health check / heartbeat middleware.
// This is in front of logging on purpose. see issue #537
Lloyd Hilaiel
committed
heartbeat.setup(app);
Lloyd Hilaiel
committed
// #2 - logging! all requests other than __heartbeat__ are logged
app.use(express.logger({
Lloyd Hilaiel
committed
format: config.get('express_log_format'),
stream: {
write: function(x) {
logger.info(typeof x === 'string' ? x.trim() : x);
Lloyd Hilaiel
committed
}
var statsd_config = config.get('statsd');
if (statsd_config && statsd_config.enabled) {
logger_statsd = require("connect-logger-statsd");
app.use(logger_statsd({
host: statsd_config.hostname || "localhost",
port: statsd_config.port || 8125,
prefix: statsd_config.prefix || "browserid.webhead."
}));
}
Lloyd Hilaiel
committed
// #3 - Add Strict-Transport-Security headers if we're serving over SSL
if (config.get('scheme') == 'https') {
app.use(function(req, resp, next) {
// expires in 30 days, include subdomains like www
resp.setHeader("Strict-Transport-Security", "max-age=2592000; includeSubdomains");
next();
});
}
// #4 - prevent framing of everything. content underneath that needs to be
// framed must explicitly remove the x-frame-options
app.use(function(req, resp, next) {
resp.setHeader('x-frame-options', 'DENY');
next();
});
// #5 - redirection! redirect requests to the "verifier" or to the "dbwriter"
// processes
if (config.get('verifier_url')) {
app.use(function(req, res, next) {
if (/^\/verify$/.test(req.url)) {
forward(
config.get('verifier_url'), req, res,
function(err) {
if (err) {
logger.error("error forwarding request:", err);
}
});
Lloyd Hilaiel
committed
} else {
return next();
}
});
Lloyd Hilaiel
committed
// #6 - verify all JSON responses are objects - prevents regression on issue #217
app.use(function(req, resp, next) {
var realRespJSON = resp.json;
resp.json = function(obj) {
if (!obj || typeof obj !== 'object') {
logger.error("INTERNAL ERROR! *all* json responses must be objects");
return httputils.serverError(resp, "broken internal API implementation");
}
realRespJSON.call(resp, obj);
};
return next();
});
Lloyd Hilaiel
committed
// #7 - perform response substitution to support local/dev/beta environments
// (specifically, this replaces URLs in responses, e.g. https://browserid.org
// with https://diresworb.org)
config.performSubstitution(app);
Lloyd Hilaiel
committed
// #8 - handle /wsapi requests
Lloyd Hilaiel
committed
wsapi.setup({
forward_writes: config.get('dbwriter_url')
}, app);
Lloyd Hilaiel
committed
// #9 - handle views for dynamicish content
views.setup(app);
Ben Adida
committed
Lloyd Hilaiel
committed
// #10 - if nothing else has caught this request, serve static files
app.use(express.static(path.join(__dirname, "..", "resources", "static")));
Lloyd Hilaiel
committed
// #11 - calls to /code_update from localhost will restart the daemon,
// this feature is not externally accessible and is only used by
// the update logic
shutdown.installUpdateHandler(app, function(readyForShutdown) {
logger.debug("closing database connection");
db.close(readyForShutdown)
Lloyd Hilaiel
committed
Ben Adida
committed
// #11.5 - custom 404
app.use(function(req, res,next) {
res.statusCode = 404;
res.write("Cannot find this resource");
res.end();
});
Lloyd Hilaiel
committed
// #12 if the BROWSERID_FAKE_VERIFICATION env var is defined, we'll include
// fake_verification.js. This is used during testing only and should
// never be included in a production deployment
if (process.env['BROWSERID_FAKE_VERIFICATION']) {
Lloyd Hilaiel
committed
require('../lib/browserid/fake_verification.js').addVerificationWSAPI(app);
Lloyd Hilaiel
committed
}
// open the databse
db.open(config.get('database'), function (error) {
if (error) {
logger.error("can't open database: " + error);
// let async logging flush, then exit 1
return setTimeout(function() { process.exit(1); }, 0);
}
Lloyd Hilaiel
committed
// shut down express gracefully on SIGINT
shutdown.handleTerminationSignals(app, function(readyForShutdown) {
db.close(readyForShutdown)
});
Lloyd Hilaiel
committed
var bindTo = config.get('bind_to');
app.listen(bindTo.port, bindTo.host, function() {
logger.info("running on http://" + app.address().address + ":" + app.address().port);
Lloyd Hilaiel
committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// #13 if the CREATE_TEST_USERS env var is defined, we'll try to create
// some test users
if (process.env['CREATE_TEST_USERS']) {
logger.warn("creating test users... this can take a while...");
bcrypt.gen_salt(config.get('bcrypt_work_factor'), function (err, salt) {
if (err) {
logger.error("error creating test users - bcrypt salt gen: " + err);
process.exit(1);
}
bcrypt.encrypt("THE PASSWORD", salt, function(err, hash) {
if (err) {
logger.error("error creating test users - bcrypt encrypt pass: " + err);
process.exit(1);
}
var want = parseInt(process.env['CREATE_TEST_USERS']);
var have = 0;
for (i = 1; i <= want; i++) {
db.addTestUser(i + "@loadtest.domain", hash, function(err, email) {
if (++have == want) {
logger.warn("created " + want + " test users");
}
});
}
});
});
}