[web] Make SamlLogHandler.log() calls asynchronous (#17207)

* [web] Refactor exports in ErrorController

* [web] Make SamlLogHandler.log() async

* [web] await for SamlLogHandler.log() in ErrorController

* [web] await for SamlLogHandler.log() in SAMLMiddleware

* [web] await for SamlLogHandler.log() async controllers

* [web] await for SamlLogHandler.log() in SAMLManager

* [web] Remove explicit wait when testing SAML logs

After making the logs asynchronouse the wait
is no longer needed

* [web] Avoid using async with SamlLogHandler.log on callbacks

* Add expressifyErrorHandler to promise-utils

* Tighten assertion in SAMLMiddlewareTests

Co-authored-by: Jakob Ackermann <jakob.ackermann@overleaf.com>

* Updated SamlLogHandler.log to await for promise

---------

Co-authored-by: Jakob Ackermann <jakob.ackermann@overleaf.com>
GitOrigin-RevId: 3645923fae8096a9ba25dc9087f1a36231528569
This commit is contained in:
Miguel Serrano 2024-02-22 15:59:17 +01:00 committed by Copybot
parent 680c9b9570
commit f4454cfe7e
5 changed files with 163 additions and 117 deletions

View file

@ -10,6 +10,7 @@ module.exports = {
callbackifyAll, callbackifyAll,
callbackifyMultiResult, callbackifyMultiResult,
expressify, expressify,
expressifyErrorHandler,
promiseMapWithLimit, promiseMapWithLimit,
} }
@ -208,6 +209,17 @@ function expressify(fn) {
} }
} }
/**
* Transform an async function into an Error Handling Express middleware
*
* Any error will be passed to the error middlewares via `next()`
*/
function expressifyErrorHandler(fn) {
return (err, req, res, next) => {
fn(err, req, res, next).catch(next)
}
}
/** /**
* Map values in `array` with the async function `fn` * Map values in `array` with the async function `fn`
* *

View file

@ -4,6 +4,8 @@ const {
promisifyClass, promisifyClass,
callbackifyMultiResult, callbackifyMultiResult,
callbackifyAll, callbackifyAll,
expressify,
expressifyErrorHandler,
} = require('../..') } = require('../..')
describe('promisifyAll', function () { describe('promisifyAll', function () {
@ -324,3 +326,23 @@ describe('callbackifyAll', function () {
}) })
}) })
}) })
describe('expressify', function () {
it('should propagate any rejection to the "next" callback', function (done) {
const fn = () => Promise.reject(new Error('rejected'))
expressify(fn)({}, {}, error => {
expect(error.message).to.equal('rejected')
done()
})
})
})
describe('expressifyErrorHandler', function () {
it('should propagate any rejection to the "next" callback', function (done) {
const fn = () => Promise.reject(new Error('rejected'))
expressifyErrorHandler(fn)({}, {}, {}, error => {
expect(error.message).to.equal('rejected')
done()
})
})
})

View file

@ -1,34 +1,33 @@
let ErrorController
const Errors = require('./Errors') const Errors = require('./Errors')
const SessionManager = require('../Authentication/SessionManager') const SessionManager = require('../Authentication/SessionManager')
const SamlLogHandler = require('../SamlLog/SamlLogHandler') const SamlLogHandler = require('../SamlLog/SamlLogHandler')
const HttpErrorHandler = require('./HttpErrorHandler') const HttpErrorHandler = require('./HttpErrorHandler')
const { plainTextResponse } = require('../../infrastructure/Response') const { plainTextResponse } = require('../../infrastructure/Response')
const { expressifyErrorHandler } = require('@overleaf/promise-utils')
module.exports = ErrorController = { function notFound(req, res) {
notFound(req, res) {
res.status(404) res.status(404)
res.render('general/404', { title: 'page_not_found' }) res.render('general/404', { title: 'page_not_found' })
}, }
forbidden(req, res) { function forbidden(req, res) {
res.status(403) res.status(403)
res.render('user/restricted') res.render('user/restricted')
}, }
serverError(req, res) { function serverError(req, res) {
res.status(500) res.status(500)
res.render('general/500', { title: 'Server Error' }) res.render('general/500', { title: 'Server Error' })
}, }
handleError(error, req, res, next) { async function handleError(error, req, res, next) {
const shouldSendErrorResponse = !res.headersSent const shouldSendErrorResponse = !res.headersSent
const user = SessionManager.getSessionUser(req.session) const user = SessionManager.getSessionUser(req.session)
req.logger.addFields({ err: error }) req.logger.addFields({ err: error })
// log errors related to SAML flow // log errors related to SAML flow
if (req.session && req.session.saml) { if (req.session && req.session.saml) {
req.logger.setLevel('error') req.logger.setLevel('error')
SamlLogHandler.log(req, { error }) await SamlLogHandler.promises.log(req, { error })
} }
if (error.code === 'EBADCSRFTOKEN') { if (error.code === 'EBADCSRFTOKEN') {
req.logger.addFields({ user }) req.logger.addFields({ user })
@ -39,7 +38,7 @@ module.exports = ErrorController = {
} else if (error instanceof Errors.NotFoundError) { } else if (error instanceof Errors.NotFoundError) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
if (shouldSendErrorResponse) { if (shouldSendErrorResponse) {
ErrorController.notFound(req, res) notFound(req, res)
} }
} else if ( } else if (
error instanceof URIError && error instanceof URIError &&
@ -53,7 +52,7 @@ module.exports = ErrorController = {
} else if (error instanceof Errors.ForbiddenError) { } else if (error instanceof Errors.ForbiddenError) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
if (shouldSendErrorResponse) { if (shouldSendErrorResponse) {
ErrorController.forbidden(req, res) forbidden(req, res)
} }
} else if (error instanceof Errors.TooManyRequestsError) { } else if (error instanceof Errors.TooManyRequestsError) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
@ -80,7 +79,7 @@ module.exports = ErrorController = {
} else { } else {
req.logger.setLevel('error') req.logger.setLevel('error')
if (shouldSendErrorResponse) { if (shouldSendErrorResponse) {
ErrorController.serverError(req, res) serverError(req, res)
} }
} }
if (!shouldSendErrorResponse) { if (!shouldSendErrorResponse) {
@ -88,9 +87,9 @@ module.exports = ErrorController = {
// the connection. // the connection.
next(error) next(error)
} }
}, }
handleApiError(err, req, res, next) { function handleApiError(err, req, res, next) {
req.logger.addFields({ err }) req.logger.addFields({ err })
if (err instanceof Errors.NotFoundError) { if (err instanceof Errors.NotFoundError) {
req.logger.setLevel('warn') req.logger.setLevel('warn')
@ -105,5 +104,12 @@ module.exports = ErrorController = {
req.logger.setLevel('error') req.logger.setLevel('error')
res.sendStatus(500) res.sendStatus(500)
} }
}, }
module.exports = {
notFound,
forbidden,
serverError,
handleError: expressifyErrorHandler(handleError),
handleApiError,
} }

View file

@ -2,8 +2,9 @@ const { SamlLog } = require('../../models/SamlLog')
const SessionManager = require('../Authentication/SessionManager') const SessionManager = require('../Authentication/SessionManager')
const logger = require('@overleaf/logger') const logger = require('@overleaf/logger')
const { err: errSerializer } = require('@overleaf/logger/serializers') const { err: errSerializer } = require('@overleaf/logger/serializers')
const { callbackify } = require('util')
function log(req, data, samlAssertion) { async function log(req, data, samlAssertion) {
let providerId, sessionId let providerId, sessionId
data = data || {} data = data || {}
@ -61,18 +62,17 @@ function log(req, data, samlAssertion) {
'SamlLog JSON.stringify Error' 'SamlLog JSON.stringify Error'
) )
} }
samlLog.save(err => { await samlLog.save()
if (err) {
logger.error({ err, sessionId, providerId }, 'SamlLog Error')
}
})
} catch (err) { } catch (err) {
logger.error({ err, sessionId, providerId }, 'SamlLog Error') logger.error({ err, sessionId, providerId }, 'SamlLog Error')
} }
} }
const SamlLogHandler = { const SamlLogHandler = {
log: callbackify(log),
promises: {
log, log,
},
} }
module.exports = SamlLogHandler module.exports = SamlLogHandler

View file

@ -29,8 +29,8 @@ describe('SamlLogHandler', function () {
}) })
describe('with valid data object', function () { describe('with valid data object', function () {
beforeEach(function () { beforeEach(async function () {
SamlLogHandler.log( await SamlLogHandler.promises.log(
{ {
session: { saml: { universityId: providerId } }, session: { saml: { universityId: providerId } },
sessionID: sessionId, sessionID: sessionId,
@ -54,11 +54,11 @@ describe('SamlLogHandler', function () {
}) })
describe('when a json stringify error occurs', function () { describe('when a json stringify error occurs', function () {
beforeEach(function () { beforeEach(async function () {
const circularRef = {} const circularRef = {}
circularRef.circularRef = circularRef circularRef.circularRef = circularRef
SamlLogHandler.log( await SamlLogHandler.promises.log(
{ {
session: { saml: { universityId: providerId } }, session: { saml: { universityId: providerId } },
sessionID: sessionId, sessionID: sessionId,
@ -81,10 +81,13 @@ describe('SamlLogHandler', function () {
}) })
describe('when logging error occurs', function () { describe('when logging error occurs', function () {
beforeEach(function () { let err
samlLog.save = sinon.stub().yields('error')
SamlLogHandler.log( beforeEach(async function () {
err = new Error()
samlLog.save = sinon.stub().rejects(err)
await SamlLogHandler.promises.log(
{ {
session: { saml: { universityId: providerId } }, session: { saml: { universityId: providerId } },
sessionID: sessionId, sessionID: sessionId,
@ -95,7 +98,10 @@ describe('SamlLogHandler', function () {
it('should log error', function () { it('should log error', function () {
this.logger.error.should.have.been.calledOnce.and.calledWithMatch( this.logger.error.should.have.been.calledOnce.and.calledWithMatch(
{ err: 'error', providerId, sessionId: sessionId.substr(0, 8) }, {
err,
sessionId: sessionId.substr(0, 8),
},
'SamlLog Error' 'SamlLog Error'
) )
}) })