Skip full user auth for most page renders

Previously, the user's session cookie was being checked against the
database for all non-static requests.  However, this is not really
needed and wastes resources (and is slow).

For most page views (e.g. index, channel page), just parsing the value
of the cookie is sufficient:

  * The cookies are already HMAC signed, so tampering with them ought to
    be for all reasonable purposes, impossible.
  * Assuming the worst case, all a nefarious user could manage to do is
    change the text of the "Welcome, {user}" and cause a (non-functional)
    ACP link to appear clientside, both of which are already possible by
    using the Inspect Element tool.

For authenticated pages (currently, the ACP, and anything under
/account/), the full database check is still performed (for now).
This commit is contained in:
Calvin Montgomery 2017-08-01 21:40:26 -07:00
parent 0118a6fb15
commit 6043647cb7
8 changed files with 154 additions and 88 deletions

View File

@ -2,7 +2,7 @@
"author": "Calvin Montgomery", "author": "Calvin Montgomery",
"name": "CyTube", "name": "CyTube",
"description": "Online media synchronizer and chat", "description": "Online media synchronizer and chat",
"version": "3.43.3", "version": "3.44.0",
"repository": { "repository": {
"url": "http://github.com/calzoneman/sync" "url": "http://github.com/calzoneman/sync"
}, },

View File

@ -17,36 +17,34 @@ exports.genSession = function (account, expiration, cb) {
var hashInput = [account.name, account.password, expiration, salt].join(":"); var hashInput = [account.name, account.password, expiration, salt].join(":");
var hash = sha256(hashInput); var hash = sha256(hashInput);
cb(null, [account.name, expiration, salt, hash].join(":")); cb(null, [account.name, expiration, salt, hash, account.global_rank].join(":"));
}; };
exports.verifySession = function (input, cb) { exports.verifySession = function (input, cb) {
if (typeof input !== "string") { if (typeof input !== "string") {
return cb("Invalid auth string"); return cb(new Error("Invalid auth string"));
} }
var parts = input.split(":"); var parts = input.split(":");
if (parts.length !== 4) { if (parts.length !== 4 && parts.length !== 5) {
return cb("Invalid auth string"); return cb(new Error("Invalid auth string"));
} }
var name = parts[0]; const [name, expiration, salt, hash, global_rank] = parts;
var expiration = parts[1];
var salt = parts[2];
var hash = parts[3];
if (Date.now() > parseInt(expiration)) { if (Date.now() > parseInt(expiration, 10)) {
return cb("Session expired"); return cb(new Error("Session expired"));
} }
dbAccounts.getUser(name, function (err, account) { dbAccounts.getUser(name, function (err, account) {
if (err) { if (err) {
if (!(err instanceof Error)) err = new Error(err);
return cb(err); return cb(err);
} }
var hashInput = [account.name, account.password, expiration, salt].join(":"); var hashInput = [account.name, account.password, expiration, salt].join(":");
if (sha256(hashInput) !== hash) { if (sha256(hashInput) !== hash) {
return cb("Invalid auth string"); return cb(new Error("Invalid auth string"));
} }
cb(null, account); cb(null, account);

View File

@ -51,7 +51,7 @@ function handleAccountEdit(req, res) {
/** /**
* Handles a request to change the user"s password * Handles a request to change the user"s password
*/ */
function handleChangePassword(req, res) { async function handleChangePassword(req, res) {
var name = req.body.name; var name = req.body.name;
var oldpassword = req.body.oldpassword; var oldpassword = req.body.oldpassword;
var newpassword = req.body.newpassword; var newpassword = req.body.newpassword;
@ -70,7 +70,8 @@ function handleChangePassword(req, res) {
return; return;
} }
if (!req.user) { const reqUser = await webserver.authorize(req);
if (!reqUser) {
sendPug(res, "account-edit", { sendPug(res, "account-edit", {
errorMessage: "You must be logged in to change your password" errorMessage: "You must be logged in to change your password"
}); });
@ -105,7 +106,6 @@ function handleChangePassword(req, res) {
}); });
} }
res.user = user;
var expiration = new Date(parseInt(req.signedCookies.auth.split(":")[1])); var expiration = new Date(parseInt(req.signedCookies.auth.split(":")[1]));
session.genSession(user, expiration, function (err, auth) { session.genSession(user, expiration, function (err, auth) {
if (err) { if (err) {
@ -114,20 +114,7 @@ function handleChangePassword(req, res) {
}); });
} }
if (req.hostname.indexOf(Config.get("http.root-domain")) >= 0) { webserver.setAuthCookie(req, res, expiration, auth);
res.cookie("auth", auth, {
domain: Config.get("http.root-domain-dotted"),
expires: expiration,
httpOnly: true,
signed: true
});
} else {
res.cookie("auth", auth, {
expires: expiration,
httpOnly: true,
signed: true
});
}
sendPug(res, "account-edit", { sendPug(res, "account-edit", {
successMessage: "Password changed." successMessage: "Password changed."
@ -188,18 +175,20 @@ function handleChangeEmail(req, res) {
/** /**
* Handles a GET request for /account/channels * Handles a GET request for /account/channels
*/ */
function handleAccountChannelPage(req, res) { async function handleAccountChannelPage(req, res) {
if (webserver.redirectHttps(req, res)) { if (webserver.redirectHttps(req, res)) {
return; return;
} }
if (!req.user) { const user = await webserver.authorize(req);
// TODO: error message
if (!user) {
return sendPug(res, "account-channels", { return sendPug(res, "account-channels", {
channels: [] channels: []
}); });
} }
db.channels.listUserChannels(req.user.name, function (err, channels) { db.channels.listUserChannels(user.name, function (err, channels) {
sendPug(res, "account-channels", { sendPug(res, "account-channels", {
channels: channels channels: channels
}); });
@ -229,7 +218,7 @@ function handleAccountChannel(req, res) {
/** /**
* Handles a request to register a new channel * Handles a request to register a new channel
*/ */
function handleNewChannel(req, res) { async function handleNewChannel(req, res) {
var name = req.body.name; var name = req.body.name;
if (typeof name !== "string") { if (typeof name !== "string") {
@ -237,13 +226,15 @@ function handleNewChannel(req, res) {
return; return;
} }
if (!req.user) { const user = await webserver.authorize(req);
// TODO: error message
if (!user) {
return sendPug(res, "account-channels", { return sendPug(res, "account-channels", {
channels: [] channels: []
}); });
} }
db.channels.listUserChannels(req.user.name, function (err, channels) { db.channels.listUserChannels(user.name, function (err, channels) {
if (err) { if (err) {
sendPug(res, "account-channels", { sendPug(res, "account-channels", {
channels: [], channels: [],
@ -260,8 +251,8 @@ function handleNewChannel(req, res) {
return; return;
} }
if (channels.length >= Config.get("max-channels-per-user") && if (channels.length >= Config.get("max-channels-per-user")
req.user.global_rank < 255) { && user.global_rank < 255) {
sendPug(res, "account-channels", { sendPug(res, "account-channels", {
channels: channels, channels: channels,
newChannelError: "You are not allowed to register more than " + newChannelError: "You are not allowed to register more than " +
@ -270,9 +261,9 @@ function handleNewChannel(req, res) {
return; return;
} }
db.channels.register(name, req.user.name, function (err, channel) { db.channels.register(name, user.name, function (err, channel) {
if (!err) { if (!err) {
Logger.eventlog.log("[channel] " + req.user.name + "@" + Logger.eventlog.log("[channel] " + user.name + "@" +
req.realIP + req.realIP +
" registered channel " + name); " registered channel " + name);
var sv = Server.getServer(); var sv = Server.getServer();
@ -304,14 +295,16 @@ function handleNewChannel(req, res) {
/** /**
* Handles a request to delete a new channel * Handles a request to delete a new channel
*/ */
function handleDeleteChannel(req, res) { async function handleDeleteChannel(req, res) {
var name = req.body.name; var name = req.body.name;
if (typeof name !== "string") { if (typeof name !== "string") {
res.send(400); res.send(400);
return; return;
} }
if (!req.user) { const user = await webserver.authorize(req);
// TODO: error
if (!user) {
return sendPug(res, "account-channels", { return sendPug(res, "account-channels", {
channels: [], channels: [],
}); });
@ -327,8 +320,8 @@ function handleDeleteChannel(req, res) {
return; return;
} }
if ((!channel.owner || channel.owner.toLowerCase() !== req.user.name.toLowerCase()) && req.user.global_rank < 255) { if ((!channel.owner || channel.owner.toLowerCase() !== user.name.toLowerCase()) && user.global_rank < 255) {
db.channels.listUserChannels(req.user.name, function (err2, channels) { db.channels.listUserChannels(user.name, function (err2, channels) {
sendPug(res, "account-channels", { sendPug(res, "account-channels", {
channels: err2 ? [] : channels, channels: err2 ? [] : channels,
deleteChannelError: "You do not have permission to delete this channel" deleteChannelError: "You do not have permission to delete this channel"
@ -339,7 +332,7 @@ function handleDeleteChannel(req, res) {
db.channels.drop(name, function (err) { db.channels.drop(name, function (err) {
if (!err) { if (!err) {
Logger.eventlog.log("[channel] " + req.user.name + "@" + Logger.eventlog.log("[channel] " + user.name + "@" +
req.realIP + " deleted channel " + req.realIP + " deleted channel " +
name); name);
} }
@ -356,7 +349,7 @@ function handleDeleteChannel(req, res) {
chan.emit("empty"); chan.emit("empty");
} }
} }
db.channels.listUserChannels(req.user.name, function (err2, channels) { db.channels.listUserChannels(user.name, function (err2, channels) {
sendPug(res, "account-channels", { sendPug(res, "account-channels", {
channels: err2 ? [] : channels, channels: err2 ? [] : channels,
deleteChannelError: err ? err : undefined deleteChannelError: err ? err : undefined
@ -369,19 +362,21 @@ function handleDeleteChannel(req, res) {
/** /**
* Handles a GET request for /account/profile * Handles a GET request for /account/profile
*/ */
function handleAccountProfilePage(req, res) { async function handleAccountProfilePage(req, res) {
if (webserver.redirectHttps(req, res)) { if (webserver.redirectHttps(req, res)) {
return; return;
} }
if (!req.user) { const user = await webserver.authorize(req);
// TODO: error message
if (!user) {
return sendPug(res, "account-profile", { return sendPug(res, "account-profile", {
profileImage: "", profileImage: "",
profileText: "" profileText: ""
}); });
} }
db.users.getProfile(req.user.name, function (err, profile) { db.users.getProfile(user.name, function (err, profile) {
if (err) { if (err) {
sendPug(res, "account-profile", { sendPug(res, "account-profile", {
profileError: err, profileError: err,
@ -421,10 +416,12 @@ function validateProfileImage(image, callback) {
/** /**
* Handles a POST request to edit a profile * Handles a POST request to edit a profile
*/ */
function handleAccountProfile(req, res) { async function handleAccountProfile(req, res) {
csrf.verify(req); csrf.verify(req);
if (!req.user) { const user = await webserver.authorize(req);
// TODO: error message
if (!user) {
return sendPug(res, "account-profile", { return sendPug(res, "account-profile", {
profileImage: "", profileImage: "",
profileText: "", profileText: "",
@ -437,7 +434,7 @@ function handleAccountProfile(req, res) {
validateProfileImage(rawImage, (error, image) => { validateProfileImage(rawImage, (error, image) => {
if (error) { if (error) {
db.users.getProfile(req.user.name, function (err, profile) { db.users.getProfile(user.name, function (err, profile) {
var errorMessage = err || error.message; var errorMessage = err || error.message;
sendPug(res, "account-profile", { sendPug(res, "account-profile", {
profileImage: profile ? profile.image : "", profileImage: profile ? profile.image : "",
@ -448,7 +445,7 @@ function handleAccountProfile(req, res) {
return; return;
} }
db.users.setProfile(req.user.name, { image: image, text: text }, function (err) { db.users.setProfile(user.name, { image: image, text: text }, function (err) {
if (err) { if (err) {
sendPug(res, "account-profile", { sendPug(res, "account-profile", {
profileImage: "", profileImage: "",

View File

@ -7,19 +7,20 @@ var db = require("../database");
var Config = require("../config"); var Config = require("../config");
function checkAdmin(cb) { function checkAdmin(cb) {
return function (req, res) { return async function (req, res) {
if (!req.user) { const user = await webserver.authorize(req);
if (!user) {
return res.send(403); return res.send(403);
} }
if (req.user.global_rank < 255) { if (user.global_rank < 255) {
res.send(403); res.send(403);
Logger.eventlog.log("[acp] Attempted GET "+req.path+" from non-admin " + Logger.eventlog.log("[acp] Attempted GET "+req.path+" from non-admin " +
user.name + "@" + req.realIP); user.name + "@" + req.realIP);
return; return;
} }
cb(req, res, req.user); cb(req, res, user);
}; };
} }

View File

@ -73,28 +73,16 @@ function handleLogin(req, res) {
return; return;
} }
if (req.hostname.indexOf(Config.get("http.root-domain")) >= 0) { webserver.setAuthCookie(req, res, expiration, auth);
// Prevent non-root cookie from screwing things up
res.clearCookie("auth");
res.cookie("auth", auth, {
domain: Config.get("http.root-domain-dotted"),
expires: expiration,
httpOnly: true,
signed: true
});
} else {
res.cookie("auth", auth, {
expires: expiration,
httpOnly: true,
signed: true
});
}
if (dest) { if (dest) {
res.redirect(dest); res.redirect(dest);
} else { } else {
res.user = user; sendPug(res, "login", {
sendPug(res, "login", {}); loggedIn: true,
loginName: user.name,
superadmin: user.global_rank >= 255
});
} }
}); });
}); });
@ -108,7 +96,7 @@ function handleLoginPage(req, res) {
return; return;
} }
if (req.user) { if (res.locals.loggedIn) {
return sendPug(res, "login", { return sendPug(res, "login", {
wasAlreadyLoggedIn: true wasAlreadyLoggedIn: true
}); });
@ -130,7 +118,7 @@ function handleLogout(req, res) {
csrf.verify(req); csrf.verify(req);
res.clearCookie("auth"); res.clearCookie("auth");
req.user = res.user = null; res.locals.loggedIn = res.locals.loginName = res.locals.superadmin = false;
// Try to find an appropriate redirect // Try to find an appropriate redirect
var dest = req.body.dest || req.header("referer"); var dest = req.body.dest || req.header("referer");
dest = dest && dest.match(/login|logout|account/) ? null : dest; dest = dest && dest.match(/login|logout|account/) ? null : dest;
@ -155,7 +143,7 @@ function handleRegisterPage(req, res) {
return; return;
} }
if (req.user) { if (res.locals.loggedIn) {
sendPug(res, "register", {}); sendPug(res, "register", {});
return; return;
} }

View File

@ -1,19 +1,62 @@
import { setAuthCookie } from '../webserver';
const STATIC_RESOURCE = /\..+$/; const STATIC_RESOURCE = /\..+$/;
export default function initialize(app, session) { export default function initialize(app, session) {
app.use((req, res, next) => { app.use(async (req, res, next) => {
if (STATIC_RESOURCE.test(req.path)) { if (STATIC_RESOURCE.test(req.path)) {
return next(); return next();
} else if (!req.signedCookies || !req.signedCookies.auth) { } else if (!req.signedCookies || !req.signedCookies.auth) {
return next(); return next();
} else { } else {
session.verifySession(req.signedCookies.auth, (err, account) => { const [
if (!err) { name, expiration, salt, hash, global_rank
req.user = res.user = account; ] = req.signedCookies.auth.split(':');
}
next(); if (!name || !expiration || !salt || !hash) {
}); // Invalid auth cookie
return next();
}
let rank;
if (!global_rank) {
rank = await backfillRankIntoAuthCookie(
session,
new Date(parseInt(expiration, 10)),
req,
res
);
} else {
rank = parseInt(global_rank, 10);
}
res.locals.loggedIn = true;
res.locals.loginName = name;
res.locals.superadmin = rank >= 255;
next();
} }
}); });
} }
async function backfillRankIntoAuthCookie(session, expiration, req, res) {
return new Promise((resolve, reject) => {
session.verifySession(req.signedCookies.auth, (err, account) => {
if (err) {
reject(err);
return;
}
session.genSession(account, expiration, (err2, auth) => {
if (err2) {
// genSession never returns an error, but it still
// has a callback parameter for one, so just in case...
reject(new Error('This should never happen: ' + err2));
return;
}
setAuthCookie(req, res, expiration, auth);
resolve(parseInt(auth.split(':')[4], 10));
});
});
});
}

View File

@ -40,9 +40,10 @@ function sendPug(res, view, locals) {
if (!locals) { if (!locals) {
locals = {}; locals = {};
} }
locals.loggedIn = locals.loggedIn || !!res.user; locals.loggedIn = nvl(locals.loggedIn, res.locals.loggedIn);
locals.loginName = locals.loginName || res.user ? res.user.name : false; locals.loginName = nvl(locals.loginName, res.locals.loginName);
locals.superadmin = locals.superadmin || res.user ? res.user.global_rank >= 255 : false; locals.superadmin = nvl(locals.superadmin, res.locals.superadmin);
if (!(view in cache) || Config.get("debug")) { if (!(view in cache) || Config.get("debug")) {
var file = path.join(templates, view + ".pug"); var file = path.join(templates, view + ".pug");
var fn = pug.compile(fs.readFileSync(file), { var fn = pug.compile(fs.readFileSync(file), {
@ -55,6 +56,11 @@ function sendPug(res, view, locals) {
res.send(html); res.send(html);
} }
function nvl(a, b) {
if (typeof a === 'undefined') return b;
return a;
}
module.exports = { module.exports = {
sendPug: sendPug sendPug: sendPug
}; };

View File

@ -12,6 +12,8 @@ import * as HTTPStatus from './httpstatus';
import { CSRFError, HTTPError } from '../errors'; import { CSRFError, HTTPError } from '../errors';
import counters from '../counters'; import counters from '../counters';
import { Summary, Counter } from 'prom-client'; import { Summary, Counter } from 'prom-client';
import session from '../session';
const verifySessionAsync = require('bluebird').promisify(session.verifySession);
const LOGGER = require('@calzoneman/jsli')('webserver'); const LOGGER = require('@calzoneman/jsli')('webserver');
@ -227,5 +229,36 @@ module.exports = {
initializeErrorHandlers(app); initializeErrorHandlers(app);
}, },
redirectHttps: redirectHttps redirectHttps: redirectHttps,
authorize: async function authorize(req) {
if (!req.signedCookies || !req.signedCookies.auth) {
return false;
}
try {
return await verifySessionAsync(req.signedCookies.auth);
} catch (error) {
return false;
}
},
setAuthCookie: function setAuthCookie(req, res, expiration, auth) {
if (req.hostname.indexOf(Config.get("http.root-domain")) >= 0) {
// Prevent non-root cookie from screwing things up
res.clearCookie("auth");
res.cookie("auth", auth, {
domain: Config.get("http.root-domain-dotted"),
expires: expiration,
httpOnly: true,
signed: true
});
} else {
res.cookie("auth", auth, {
expires: expiration,
httpOnly: true,
signed: true
});
}
}
}; };