Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
253 lines (221 loc) · 9.63 KB
/
Copy pathapp.js
File metadata and controls
253 lines (221 loc) · 9.63 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
'use strict';
// Node builtin (not a require) so it runs before the Azure Monitor require-hook guard below.
try {
process.loadEnvFile();
} catch (err) {
// Silent fallback: use system environment variables (e.g. in container environments)
}
// Must start before any other require (it instruments via require hooks); guarded so tests stay silent.
if (process.env.APPLICATIONINSIGHTS_CONNECTION_STRING) {
const { useAzureMonitor } = require('@azure/monitor-opentelemetry');
useAzureMonitor({
enablePerformanceCounters: false,
instrumentationOptions: {
winston: { enabled: true },
// Mongo spans were 0.17 GB/day of a 0.25 GB workspace cap; requests and logs stay.
mongoDb: { enabled: false }
}
});
}
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var uploadDir = process.env.UPLOAD_DIRECTORY || './uploads/';
var hostname = process.env.API_HOSTNAME || 'localhost:3000';
var YAML = require('js-yaml');
var swaggerUi = require('swagger-ui-express');
var app_helper = require('./app_helper');
var createRouter = require('./api/middleware/swagger-router');
var swaggerSpec = YAML.load(fs.readFileSync('./api/swagger/swagger.yaml', 'utf8'));
const rateLimit = require('express-rate-limit');
const rateLimitKey = require('./api/helpers/rateLimitKey');
const analytics = require('./api/helpers/analytics');
const pushClient = require('./api/helpers/pushClient');
const demiPush = require('./api/helpers/demiPush');
var api_default_port = 3000;
var express_server;
var defaultLog = app_helper.defaultLog;
// Increase postbody sizing.
// `text/plain` is parsed as JSON as well. That was added for Typesense's SearchClient, which sent
// multi_search bodies as text/plain to dodge a CORS preflight; Typesense is gone, but the parsing
// stays because it is a request-handling behaviour of the whole API and some other client may rely
// on it. Narrow it deliberately, with callers checked, rather than as cleanup.
app.use(express.json({ limit: '10mb', type: ['application/json', 'text/plain'] }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
// disable powered by header
app.disable('x-powered-by');
// Trust only in-cluster hops (router, rproxy). External callers cannot forge req.ip via X-Forwarded-For;
// an in-cluster caller could, and nothing here guards that.
app.set('trust proxy', 'loopback, linklocal, uniquelocal');
// Enable CORS
// Reflect the requesting origin instead of '*' so that credentialed requests
// (those carrying an Authorization header) are accepted by all browsers.
app.use(function (req, res, next) {
defaultLog.info(`${req.method} ${req.url}`);
const origin = req.headers.origin || '';
const corsAllowList = process.env.CORS_ALLOW_LIST
? process.env.CORS_ALLOW_LIST.split(',').map(o => o.trim())
: [
'http://localhost:4200',
'http://localhost:4300',
'http://localhost:8080',
'https://eagle-dev.apps.silver.devops.gov.bc.ca',
'https://eagle-test.apps.silver.devops.gov.bc.ca',
'https://projects.eao.gov.bc.ca'
];
if (corsAllowList.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
} else {
res.setHeader('Access-Control-Allow-Origin', '*');
}
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE, HEAD');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Authorization,responseType');
res.setHeader('Access-Control-Expose-Headers', 'x-total-count,x-pending-comment-count,x-next-comment-id');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Vary', 'Origin');
if (req.method === 'GET') {
// Authenticated requests must not be cached — admin users need fresh data
// after mutations (delete, publish, etc.). Public GETs can cache briefly.
if (req.headers.authorization) {
res.setHeader('Cache-Control', 'no-store');
} else {
res.setHeader('Cache-Control', 'max-age=60');
}
} else {
res.setHeader('Cache-Control', 'no-store');
}
// headers for zap scan issues
res.setHeader('X-XSS-Protection', '1');
res.setHeader('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload');
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
next();
});
// Health check — responds immediately without DB dependency.
// Used by CI smoke-test wait loop and OpenShift readiness probes.
app.get('/api/health', function (req, res) {
res.status(200).json({ status: 'ok' });
});
app.use(require('./api/middleware/edgeOnly'));
// Analytics proxy — forwards /analytics/* to a local eagle-analytics service.
// In production, nginx routes /analytics directly. This route serves local dev
// where proxy.conf.js sends /analytics to eagle-api.
var analyticsTarget = process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3001';
app.use('/analytics', function (req, res) {
var targetUrl = analyticsTarget + '/analytics' + req.url;
fetch(targetUrl, {
method: req.method,
body: req.body ? JSON.stringify(req.body) : undefined,
headers: { 'Content-Type': 'application/json' },
signal: AbortSignal.timeout(5000)
})
.then(async function (response) {
let data;
try {
data = await response.json();
} catch (e) {
data = null;
}
res.status(response.status).json(data);
})
.catch(function (err) {
if (err.name === 'TimeoutError') {
res.status(504).json({ error: 'Analytics service timeout' });
} else {
res.status(502).json({ error: 'Analytics service unavailable' });
}
});
});
// Swagger UI — serve the API docs at /api/docs
if (hostname !== 'localhost:3000') {
swaggerSpec.schemes = ['https'];
}
swaggerSpec.host = hostname;
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// Rate limiter — applied before the auto-wired router so it runs on all /api routes.
// NOTE: health check at /api/health is registered above and responds before reaching
// this limiter, so health probes are not counted against the rate limit.
const globalLimiter = rateLimit({
windowMs: 60 * 1000,
limit: 200,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: { error: 'Too many requests. Please try again later.' },
keyGenerator: rateLimitKey,
});
app.use('/api', globalLimiter);
// Backward-compatible project redirects
const projectRedirectMiddleware = require('./api/middleware/projectRedirect');
app.use(projectRedirectMiddleware());
// Auto-wired API router — reads swagger.yaml and registers one Express route per
// operation, populates req.swagger.params, enforces Bearer auth, and calls the
// matching controller function.
var controllerDirs = [
path.join(__dirname, 'api/controllers'),
path.join(__dirname, 'api/tasks')
];
app.use('/api', createRouter(swaggerSpec, controllerDirs));
app.use(require('./api/middleware/errorHandler'));
// Make sure uploads directory exists
try {
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
} catch (e) {
defaultLog.info('Couldn\'t create upload folder:', e);
}
// Skip MongoDB connection and server startup in test mode
// Tests handle their own database connection to in-memory MongoDB
if (process.env.NODE_ENV !== 'test') {
app_helper.loadMongoose().then(async () => {
// Start Agenda job queue after MongoDB is connected
const { startJobQueue } = require('./api/helpers/jobQueue');
await startJobQueue().catch(err => defaultLog.error('[jobQueue] Failed to start:', err.message));
express_server = app.listen(api_default_port, '0.0.0.0', function() {
defaultLog.info('Started server on port ' + api_default_port);
// Run startup configuration checks for email helper
try {
require('./api/helpers/email').checkConfig();
} catch (err) {
defaultLog.error('Failed to run email config check:', err.message);
}
});
}).catch(function (err) {
// loadMongoose() already retried and exited on exhaustion, but catch any
// unexpected rejection here too — crashing is better than serving 400s.
defaultLog.error('Fatal: MongoDB connection failed:', err);
process.exit(1);
});
}
// Log unhandled rejections but let the process survive.
// Mongoose auto-reconnects on transient MongoDB errors (timeouts, topology
// changes). Crashing here caused 90+ pod restarts per week in production.
process.on('unhandledRejection', function(reason) {
defaultLog.error('Unhandled Rejection:', reason);
});
// How long shutdown waits on the buffered analytics rows. Short: losing them costs a few rows, and
// the wait is also the head start jobQueue's own SIGTERM listener gets before this exits.
const ANALYTICS_DRAIN_MS = 3000;
async function shutdown() {
const drained = analytics.flush().catch(err => defaultLog.error('[analytics] shutdown flush failed', { error: err.message }));
await Promise.race([drained, new Promise(resolve => setTimeout(resolve, ANALYTICS_DRAIN_MS).unref())]);
if (express_server) {
defaultLog.info('Shutting down gracefully');
express_server.close(() => {
defaultLog.info('Closed out remaining connections');
pushClient.logUnsent();
demiPush.logParked();
process.exit(0);
});
}
}
// Nothing else called shutdown(). jobQueue registers a SIGTERM listener of its own and Node runs
// both; the drain above is what keeps this from exiting out from under it.
process.once('SIGTERM', shutdown);
module.exports = app;
exports.shutdown = shutdown;
exports.api_default_port = api_default_port;
exports.dbConnection = app_helper.dbConnection;