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

PP-13360 csrf express middleware #1314

Merged
merged 2 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
15 changes: 14 additions & 1 deletion .secrets.baseline
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@
{
"path": "detect_secrets.filters.allowlist.is_line_allowlisted"
},
{
"path": "detect_secrets.filters.common.is_baseline_file",
"filename": ".secrets.baseline"
},
{
"path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
"min_level": 2
Expand Down Expand Up @@ -116,7 +120,16 @@
"is_verified": false,
"line_number": 20
}
],
"src/utils/middleware/csrf.middleware.js": [
{
"type": "Secret Keyword",
"filename": "src/utils/middleware/csrf.middleware.js",
"hashed_secret": "fb23222a82d3fc0120ff287e546fee1be335c81a",
"is_verified": false,
"line_number": 16
}
]
},
"generated_at": "2024-07-22T14:03:26Z"
"generated_at": "2024-12-16T18:58:18Z"
}
1 change: 1 addition & 0 deletions karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ module.exports = karma => karma.set({
exclude: [
'**/axios-base-client.test.js',
'analytics/**/*.js',
'utils/middleware/**/*.js',
'**/errors.test.js'
],
plugins: [
Expand Down
135 changes: 135 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"prepare": "npm run transpile && npm run browserify-analytics",
"test": "npm run jest-tests npm && npm run karma-tests",
"karma-tests": "karma start",
"jest-tests": "jest src/analytics src/utils/axios-base-client/axios-base-client.test.js",
"jest-tests": "jest src/analytics src/utils/axios-base-client/axios-base-client.test.js src/utils/middleware/*.test.js",
"lint": "standard --fix"
},
"repository": {
Expand Down Expand Up @@ -112,6 +112,7 @@
"@babel/cli": "^7.4.4",
"@babel/core": "^7.4.5",
"@babel/preset-env": "^7.4.5",
"@types/express": "^5.0.0",
"babelify": "^10.0.0",
"brfs": "^2.0.2",
"browser-env": "^3.2.6",
Expand Down Expand Up @@ -144,6 +145,7 @@
},
"dependencies": {
"axios": "^1.6.5",
"csrf": "^3.1.0",
"lodash": "4.17.21",
"moment-timezone": "0.5.43",
"rfc822-validate": "1.0.0",
Expand Down
81 changes: 81 additions & 0 deletions src/utils/middleware/csrf.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const csrf = require('csrf')

class CsrfError extends Error {
constructor (message) {
super(message)
this.name = 'CsrfError'
}
}

/**
* @param logger {Logger}
* @param sessionName {string} the name of the object on the request where the secret key will be stored
* @param secretName {string} the name of the key in session object that will hold the secret value
* @param tokenName {string} the name of the key on the request body/query that will hold the token value
*/
const configureCsrfMiddleware = (logger, sessionName, secretName = 'csrfSecret', tokenName = 'csrfToken') => {
logger.debug('--- CSRF middleware configuration ---')
logger.debug(`Secret is set at req['${sessionName}']['${secretName}']`)
logger.debug(`Token is checked at req.body|query['${tokenName}']`)
logger.debug('-------------------------------------')

/**
* @param req {e.Request}
* @param res {e.Response}
* @param next {e.NextFunction}
*/
const setSecret = (req, res, next) => {
const csrfSecret = req[sessionName]?.[secretName]
if (!csrfSecret) {
logger.debug('Synchronising CSRF secret')
req[sessionName][secretName] = csrf().secretSync()
}
next()
}

/**
* @param req {e.Request}
* @param res {e.Response}
* @param next {e.NextFunction}
*/
const checkToken = (req, res, next) => {
// short circuit the check if method is not PUT/POST
if (!['PUT', 'POST'].includes(req.method.toUpperCase())) {
return next()
}
const csrfSecret = req[sessionName]?.[secretName]
const csrfToken = req.body?.[tokenName] || req.query?.[tokenName]
if (!csrfSecret) {
return next(new CsrfError(`CSRF secret was not found on ${sessionName} when validating token`))
}
if (!csrfToken) {
return next(new CsrfError('CSRF token was not found in body or query for PUT/POST request'))
}
if (!csrf().verify(csrfSecret, csrfToken)) {
return next(new CsrfError('Invalid CSRF token'))
}
next()
}

/**
* @param req {e.Request}
* @param res {e.Response}
* @param next {e.NextFunction}
*/
const generateToken = (req, res, next) => {
const csrfSecret = req[sessionName][secretName]
res.locals.csrf = csrf().create(csrfSecret)
next()
}

return {
setSecret,
checkToken,
generateToken
}
}

module.exports = {
configureCsrfMiddleware,
CsrfError
}
Loading
Loading