-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserver.ts
More file actions
423 lines (381 loc) · 12.7 KB
/
server.ts
File metadata and controls
423 lines (381 loc) · 12.7 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/// <reference types="node" />
/// <reference types="express" />
import 'reflect-metadata';
const { formatError } = require('./services/keystone_overrides/formatError');
const { Keystone } = require('@keystonejs/keystone');
const { Oauth2ProxyAuthStrategy } = require('./auth/auth-oauth2-proxy');
const { PasswordAuthStrategy } = require('@keystonejs/auth-password');
const { AdminUIApp } = require('@keystonejs/app-admin-ui');
const { generate } = require('@graphql-codegen/cli');
const { NextApp } = require('@keystonejs/app-next');
const { ApiProxyApp } = require('./api-proxy');
const { ApiGraphqlWhitelistApp } = require('./api-graphql-whitelist');
const { ApiHealthApp } = require('./api-health');
const { MaintenanceApp } = require('./api-maintpage');
const { ApiOpenapiApp } = require('./api-openapi');
const { ApiDSProxyApp } = require('./api-proxy-ds');
const { OpsMetrics } = require('./services/report/ops-metrics');
const initialiseData = require('./initial-data');
const session = require('express-session');
const redis = require('redis');
let RedisStore = require('connect-redis')(session);
const {
putFeedWorker,
deleteFeedWorker,
getFeedWorker,
} = require('./batch/feed-worker');
const { Retry } = require('./services/tasked');
const { EnforcementPoint } = require('./authz/enforcement');
const { loadRulesAndWatch } = require('./authz/enforcement');
const { logger } = require('./logger');
const apiPath = '/gql/api';
const PROJECT_NAME = 'APS Service Portal';
const { KnexAdapter } = require('@keystonejs/adapter-knex');
const knexAdapterConfig = {
knexOptions: {
debug: process.env.LOG_LEVEL === 'debug' ? false : false,
connection: {
host: process.env.KNEX_HOST,
port: process.env.KNEX_PORT,
user: process.env.KNEX_USER,
password: process.env.KNEX_PASSWORD,
database: process.env.KNEX_DATABASE,
},
},
};
const { MongooseAdapter } = require('@keystonejs/adapter-mongoose');
const mongooseAdapterConfig = {
mongoUri: process.env.MONGO_URL,
user: process.env.MONGO_USER,
pass: process.env.MONGO_PASSWORD,
};
// GraphQL TypeScript codegen. Will output a `types.d.ts` file to `./src`
async function generateTypes() {
await Promise.all(
['/nextapp/shared/types/query.types.ts', '/services/keystone/types.ts'].map(
async (path: string) => {
await generate(
{
schema: `http://localhost:3000${apiPath}`,
generates: {
[process.cwd() + path]: {
plugins: ['typescript'],
},
},
},
true
);
}
)
);
}
const adapter = process.env.ADAPTER ? process.env.ADAPTER : 'mongoose';
require('dotenv').config();
loadRulesAndWatch(process.env.NODE_ENV);
const state = { connected: false };
const keystone = new Keystone({
onConnect(keystone: any) {
if (process.env.CREATE_TABLES !== 'true') {
initialiseData(keystone);
}
console.log('CONNECTED!');
state.connected = true;
if (process.env.NODE_ENV === 'development') {
setTimeout(() => generateTypes, 2000);
}
},
adapter:
adapter == 'knex'
? new KnexAdapter(knexAdapterConfig)
: new MongooseAdapter(mongooseAdapterConfig),
cookieSecret: process.env.COOKIE_SECRET,
cookie: {
secure: process.env.COOKIE_SECURE === 'true', // Default to true in production
//maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days
maxAge: 1000 * 60 * 60 * 24, // 1 day
sameSite: true,
},
sessionStore:
process.env.SESSION_STORE === 'redis'
? new RedisStore({
client: redis.createClient({
url: process.env.REDIS_URL,
password: process.env.REDIS_PASSWORD,
}),
})
: null,
});
const yamlReport = [];
for (const _list of [
'AccessRequest',
'Activity',
'Alert',
'Application',
'Blob',
'Content',
'CredentialIssuer',
'Dataset',
'Environment',
'GatewayConsumer',
'GatewayGroup',
'GatewayPlugin',
'GatewayRoute',
'GatewayService',
'Label',
'Legal',
'Metric',
'Organization',
'OrganizationUnit',
'Product',
'ServiceAccess',
'TemporaryIdentity',
'User',
]) {
const list = require('./lists/' + _list);
if ('extensions' in list) {
console.log('Registering Extension!');
list.extensions.map((ext: any) => ext(keystone));
}
logger.info(' %s', _list);
list.access = EnforcementPoint;
for (const entry of Object.entries(list.fields)) {
logger.info(' %s', entry[0]);
//list.fields[entry[0]].access = FieldEnforcementPoint
}
const out = { list: _list, fields: Object.keys(list.fields).sort() };
yamlReport.push(out);
keystone.createList(_list, list);
}
const report = require('js-yaml').dump(yamlReport);
for (const _list of [
'AliasedQueries',
'BusinessProfile',
'ConsumerGroups',
'ConsumerProducts',
'ConsumerScopesAndRoles',
'CredentialIssuerExt',
'Namespace',
'NamespaceActivity',
'OrganizationPolicy',
'ServiceAccess',
'ServiceAccount',
'UMAPolicy',
'UMAResourceSet',
'UMAPermissionTicket',
'UserExt',
]) {
const list = require('./lists/extensions/' + _list);
if ('extensions' in list) {
console.log('Registering Extension!');
list.extensions.map((ext: any) => ext(keystone));
}
}
const strategyType = process.env.AUTH_STRATEGY || 'Password';
console.log('Auth Strategy: ' + strategyType);
const authStrategy =
strategyType === 'Password'
? keystone.createAuthStrategy({
type: PasswordAuthStrategy,
list: 'User',
})
: keystone.createAuthStrategy({
type: Oauth2ProxyAuthStrategy,
list: 'TemporaryIdentity',
signinPath: 'oauth2/sign_in',
config: {
onAuthenticated: (
{ token, item, isNewItem }: any,
req: any,
res: any
) => {
const redirect = req.query?.f ? req.query.f : '/';
// Doing a 302 redirect does not set the cookie properly because it is SameSite 'Strict'
// and the Origin of the request was from an IdP
res.header('Content-Type', 'text/html');
res.send(
`<html><head><meta http-equiv="refresh" content="0;URL='${redirect}'"></head></html>`
);
},
},
hooks: {
afterAuth: async ({
operation,
item,
success,
message,
token,
originalInput,
resolvedData,
context,
listKey,
}: any) => {
console.log('AFTER AUTH');
console.log('ctx = ' + context.session);
},
},
});
const { pages } = require('./admin-hooks.js');
const apps = [
new ApiHealthApp(state),
new ApiOpenapiApp(),
new MaintenanceApp(),
new ApiDSProxyApp({ url: process.env.SSR_API_ROOT }),
new ApiProxyApp({ gwaApiUrl: process.env.GWA_API_URL }),
new ApiGraphqlWhitelistApp({
apiPath,
apollo: {
formatError: (err: any) => {
logger.error('GraphQL Error: %s', err);
const error = formatError(err);
const data = error.extensions?.exception?.response?.data;
if (!dev && error.extensions?.exception) {
logger.warn('Removing exception details from error response');
delete error.extensions['exception'];
}
if (data) {
logger.error(' %s', data);
}
return error;
},
},
}),
new AdminUIApp({
name: PROJECT_NAME,
adminPath: '/admin',
apiPath,
signinPath: 'oauth2/sign_in',
authStrategy,
pages: pages,
enableDefaultRoute: false,
}),
new NextApp({ dir: 'nextapp' }),
];
const dev = process.env.NODE_ENV !== 'production';
const configureExpress = (app: any) => {
const express = require('express');
// if there is code coverage information
// then expose an endpoint that returns it
if (process.env.TEST_COVERAGE) {
console.log('have code coverage, will add middleware for express');
console.log(`to fetch: GET /__coverage__`);
require('@cypress/code-coverage/middleware/express')(app);
}
app.use(express.json({ limit: '300kb' }));
app.use(function errorHandler(err: any, req: any, res: any, next: any) {
if (err instanceof SyntaxError) {
return res.status(422).json({
message: 'Syntax Error Parsing JSON',
});
}
next();
});
// app.get('/', (req, res, next) => {
// console.log(req.path)
// req.path == "/" ? res.redirect('/home') : next()
// })
app.get('/feed/:entity/:refKey/:refKeyValue', (req: any, res: any) => {
const context = keystone.createContext({ skipAccessControl: true });
getFeedWorker(context, req, res).catch((err: any) => {
console.log(err);
res.status(400).json({ result: 'error', error: '' + err });
});
});
app.put('/feed/:entity', (req: any, res: any) => {
const context = keystone.createContext({
skipAccessControl: true,
authentication: {
item: { name: 'Feeder Bot', namespace: req.body?.namespace },
},
});
putFeedWorker(context, req, res).catch((err: any) => {
console.log(err);
res.status(400).json({ result: 'error', error: '' + err });
});
});
app.put('/feed/:entity/:id', (req: any, res: any) => {
const context = keystone.createContext({ skipAccessControl: true });
putFeedWorker(context, req, res).catch((err: any) =>
res.status(400).json({ result: 'error', error: '' + err })
);
});
app.delete('/feed/:entity/:id', (req: any, res: any) => {
const context = keystone.createContext({ skipAccessControl: true });
deleteFeedWorker(context, req, res);
});
app.put('/migration/import', async (req: any, res: any) => {
const { MigrationFromV1 } = require('./batch/migrationV1');
await new MigrationFromV1(keystone).report(req.body);
await new MigrationFromV1(keystone)
.migrate(req.body)
.then(() => {
res.status(200).json({ result: 'migrated' });
})
.catch((err: any) => {
console.log('Error Migrating ' + err);
res.status(400).json({ result: 'failed' });
});
});
app.post('/migration/report', async (req: any, res: any) => {
const { MigrationFromV1 } = require('./batch/migrationV1');
await new MigrationFromV1(keystone)
.report(req.body)
.then(() => {
res.status(200).json({ result: 'reported' });
})
.catch((err: any) => {
console.log('Error Migrating ' + err);
res.status(400).json({ result: 'failed' });
});
});
// Added for handling failed calls that require orchestrating multiple changes
app.put('/tasked/:id', async (req: any, res: any) => {
const tasked = new Retry(process.env.WORKING_PATH, req.params['id']);
await tasked.start();
res.status(200).json({ result: 'ok' });
});
const opsMetrics = new OpsMetrics(keystone);
opsMetrics.initialize();
app.get('/metrics', async (req: any, res: any) => {
await opsMetrics.generateMetrics();
await opsMetrics.store();
res.set('Content-Type', 'text/plain');
res.end('');
});
app.get('/about', (req: any, res: any) => {
res.status(200).json({
version: process.env.NEXT_PUBLIC_APP_VERSION,
revision: process.env.NEXT_PUBLIC_APP_REVISION,
cluster: process.env.NEXT_PUBLIC_KUBE_CLUSTER,
apiRootUrl: process.env.NEXT_PUBLIC_API_ROOT,
identities: {
developer: (process.env.NEXT_PUBLIC_DEVELOPER_IDS || '').split(','),
provider: (process.env.NEXT_PUBLIC_PROVIDER_IDS || '').split(','),
},
identityContent: require('./auth/methods.json'),
accountLinks: {
bceidUrl: process.env.NEXT_PUBLIC_ACCOUNT_BCEID_URL,
bcscUrl: process.env.NEXT_PUBLIC_ACCOUNT_BCSC_URL,
},
helpLinks: {
helpDeskUrl: process.env.NEXT_PUBLIC_HELP_DESK_URL,
helpChatUrl: process.env.NEXT_PUBLIC_HELP_CHAT_URL,
helpIssueUrl: process.env.NEXT_PUBLIC_HELP_ISSUE_URL,
helpApiDocsUrl: process.env.NEXT_PUBLIC_HELP_API_DOCS_URL,
helpSupportUrl: process.env.NEXT_PUBLIC_HELP_SUPPORT_URL,
helpReleaseUrl: process.env.NEXT_PUBLIC_HELP_RELEASE_URL,
helpStatusUrl: process.env.NEXT_PUBLIC_HELP_STATUS_URL,
helpAddOrgUrl: process.env.NEXT_PUBLIC_HELP_ADD_ORG_URL,
helpChangeOrgUrl: process.env.NEXT_PUBLIC_CHANGE_ORG_URL,
},
});
});
// const { NotificationService } = require('./services/notification/notification.service')
// const nc = new NotificationService(new ConfigService())
// nc.notify ({email: "aidan.cope@gmail.com", name: "Aidan Cope"}, { template: 'email-template', subject: 'Yeah!'}).then ((answer:any) => {
// console.log("DONE!")
// console.log("ANSWER = " + JSON.stringify(answer))
// }).catch ((err: any) => {
// console.log("ERROR ! " + err)
// })
};
export { keystone, apps, dev, configureExpress };