-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
238 lines (212 loc) · 6.82 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
232
233
234
235
236
237
238
// Core dependencies
const path = require('path')
// NPM dependencies
const Sentry = require('@sentry/node')
// Tracing needs to be imported for it to work
// Source: https://docs.sentry.io/platforms/node/performance/
// eslint-disable-next-line no-unused-vars
const Tracing = require('@sentry/tracing')
const compression = require('compression')
const flash = require('connect-flash')
const cookieParser = require('cookie-parser')
const express = require('express')
const session = require('express-session')
const grant = require('grant-express')
const helmet = require('helmet')
const i18nMiddleware = require('i18next-express-middleware')
const morgan = require('morgan')
const responseTime = require('response-time')
const favicon = require('serve-favicon')
// Local dependencies
const healthcheckApp = require('./app/healthcheck')
const locationsApp = require('./app/locations')
const router = require('./app/router')
const metrics = require('./common/lib/metrics')
const breadcrumbs = require('./common/middleware/breadcrumbs')
const checkSession = require('./common/middleware/check-session')
const ensureAuthenticated = require('./common/middleware/ensure-authenticated')
const ensureSelectedLocation = require('./common/middleware/ensure-selected-location')
const errorHandlers = require('./common/middleware/errors')
const locals = require('./common/middleware/locals')
const { setCanAccess } = require('./common/middleware/permissions')
const processOriginalRequestBody = require('./common/middleware/process-original-request-body')
const sentryEnrichScope = require('./common/middleware/sentry-enrich-scope')
const sentryRequestId = require('./common/middleware/sentry-request-id')
const setApiClient = require('./common/middleware/set-api-client')
const setLocation = require('./common/middleware/set-location')
const setLocations = require('./common/middleware/set-locations')
const setPrimaryNavigation = require('./common/middleware/set-primary-navigation')
const setServices = require('./common/middleware/set-services')
const setTransactionId = require('./common/middleware/set-transaction-id')
const setUser = require('./common/middleware/set-user')
const config = require('./config')
const i18n = require('./config/i18n')
const nunjucks = require('./config/nunjucks')
const { getAssetPath } = require('./config/nunjucks/globals')
const configPaths = require('./config/paths')
let redisStore
if (config.REDIS.SESSION) {
redisStore = require('./config/redis-store')()
}
// Global constants
const app = express()
if (config.IS_PRODUCTION) {
app.enable('trust proxy')
}
// Ensure we have a useful transaction id
app.use(setTransactionId)
if (config.SENTRY.DSN) {
Sentry.init({
dsn: config.SENTRY.DSN,
environment: config.SENTRY.ENVIRONMENT,
release: config.SENTRY.RELEASE,
// Half of all requests will be used for performance sampling
tracesSampleRate: 0.5,
})
app.use(
Sentry.Handlers.requestHandler({
// Ensure we don't include `data` to avoid sending any PPI
request: ['cookies', 'headers', 'method', 'query_string', 'url'],
user: ['id', 'username', 'permissions'],
})
)
app.use(sentryRequestId)
}
// Configure prometheus to handle metrics
metrics.init(app, config)
// Load the healthcheck app manually before anything
// else to ensure it will return some kind of response
// regardless of the app failing elsewhere
app.use(healthcheckApp.mountpath, healthcheckApp.router)
// view engine setup
app.set('view engine', 'njk')
nunjucks(app, config, configPaths)
// Static files
app.use(compression())
app.use(
favicon(path.join(configPaths.build, getAssetPath('images/favicon.ico')))
)
app.use(express.static(configPaths.build))
app.use(
'/assets',
express.static(
path.join(__dirname, '/node_modules/govuk-frontend/govuk/assets')
),
express.static(
path.join(__dirname, '/node_modules/@ministryofjustice/frontend/moj/assets')
)
)
// ensure i18n is loaded early as needed for error template
app.use(i18nMiddleware.handle(i18n))
const loggingFormat = config.IS_PRODUCTION ? 'combined' : 'dev'
app.use(morgan(loggingFormat))
app.use(express.json())
app.use(express.urlencoded({ extended: true, limit: '1mb' }))
app.use(cookieParser())
app.use(responseTime())
app.use(
session({
store: redisStore,
secret: config.SESSION.SECRET,
name: config.SESSION.NAME,
saveUninitialized: false,
resave: false,
rolling: true,
cookie: {
secure: config.IS_PRODUCTION,
maxAge: config.SESSION.TTL,
httpOnly: true,
},
})
)
app.use(checkSession)
app.use(setUser)
app.use(sentryEnrichScope)
app.use(flash())
app.use(breadcrumbs.init())
app.use(locals)
app.use(
grant({
defaults: {
origin:
(config.IS_PRODUCTION ? 'https' : 'http') + `://${config.SERVER_HOST}`,
callback: '/auth/callback',
transport: 'session',
state: true,
},
...config.AUTH_PROVIDERS,
})
)
// Set API client
app.use(setApiClient)
// Set services
app.use(setServices)
// Development environment helpers
if (config.IS_DEV) {
require('axios-debug-log')
const development = require('./common/middleware/development')
app.use(development.bypassAuth(config.AUTH_BYPASS_SSO))
app.use(development.setUserPermissions(config.USER_PERMISSIONS))
app.use(development.setUserLocations(config.USER_LOCATIONS))
}
app.use(
ensureAuthenticated({
provider: config.DEFAULT_AUTH_PROVIDER,
whitelist: config.AUTH_WHITELIST_URLS,
expiryMargin: config.AUTH_EXPIRY_MARGIN,
})
)
app.use(
ensureSelectedLocation({
locationsMountpath: locationsApp.mountpath,
whitelist: config.AUTH_WHITELIST_URLS,
})
)
app.use(setLocations)
// app.use(setLocation)
app.use('.*(?<!image)$', setLocation)
// unsafe-inline is required as govuk-template injects `js-enabled` class via inline script
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: [
"'self'",
"'unsafe-inline'",
'cdnjs.cloudflare.com',
'www.googletagmanager.com',
'www.google-analytics.com',
'api.os.uk',
],
connectSrc: [
"'self'",
"'unsafe-inline'",
'www.googletagmanager.com',
'www.google-analytics.com',
'api.os.uk',
],
imgSrc: [
"'self'",
'www.google-analytics.com',
'api.os.uk',
'data: blob:',
],
fontSrc: ["'self'", 'fonts.googleapis.com'],
styleSrc: ["'self'", "'unsafe-inline'", 'cdnjs.cloudflare.com'],
},
},
})
)
// Ensure body processed after reauthentication
app.use(processOriginalRequestBody())
// Add permission checker
app.use(setCanAccess)
// Routing
app.use(setPrimaryNavigation)
app.use(router)
// error handling
app.use(Sentry.Handlers.errorHandler())
app.use(errorHandlers.notFound)
app.use(errorHandlers.catchAll(config.IS_DEV))
module.exports = app