Skip to content

Commit

Permalink
Moving away from csurf and to csrf-sync
Browse files Browse the repository at this point in the history
Fixes a security vulnerability GHSA-pxg6-pf52-xh8x and brings our UI more inline with HMPPS Typescript template

```
csurf has been deprecated for some time and this removes that dependency and implements the synchronizer token pattern using csrf-sync.

Note: Previously csurf used to generate new tokens on every request. The new library generates tokens once per session which is preferrable due to the extra calls to redis that per-request would generate. It is possible to force a refresh/revocation of a token by explicitly calling: req.csrfToken(true)

See PR #481

```
Quote from https://github.com/ministryofjustice/hmpps-template-typescript/blob/2e139f5e9e3a6dbfaa0c6bbbc240513556102a8f/CHANGELOG.md
PR: https://github.com/ministryofjustice/hmpps-template-typescript/pull/481/files
  • Loading branch information
aliuk2012 committed Dec 19, 2024
1 parent 62eda52 commit 0ad20d4
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 107 deletions.
111 changes: 8 additions & 103 deletions package-lock.json

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

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
"compression": "^1.7.4",
"connect-flash": "^0.1.1",
"connect-redis": "^7.0.0",
"csurf": "^1.11.0",
"csrf-sync": "^4.0.3",
"date-fns": "^3.0.0",
"dotenv": "^16.4.4",
"express": "^4.21.0",
Expand Down Expand Up @@ -173,7 +173,6 @@
"@types/compression": "^1.7.2",
"@types/connect-flash": "0.0.40",
"@types/cookie-session": "^2.0.44",
"@types/csurf": "^1.11.2",
"@types/express-session": "^1.17.5",
"@types/http-errors": "^2.0.0",
"@types/jest": "^29.0.0",
Expand Down
14 changes: 12 additions & 2 deletions server/middleware/setUpCsrf.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Router } from 'express'
import csurf from 'csurf'
import { csrfSync } from 'csrf-sync'

const testMode = process.env.NODE_ENV === 'test'

Expand All @@ -8,7 +8,17 @@ export default function setUpCsrf(): Router {

// CSRF protection
if (!testMode) {
router.use(csurf())
const {
csrfSynchronisedProtection, // This is the default CSRF protection middleware.
} = csrfSync({
// By default, csrf-sync uses x-csrf-token header, but we use the token in forms and send it in the request body, so change getTokenFromRequest so it grabs from there
getTokenFromRequest: req => {
// eslint-disable-next-line no-underscore-dangle
return req.body._csrf
},
})

router.use(csrfSynchronisedProtection)
}

router.use((req, res, next) => {
Expand Down

0 comments on commit 0ad20d4

Please sign in to comment.