-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapi.ts
More file actions
530 lines (482 loc) · 16.7 KB
/
api.ts
File metadata and controls
530 lines (482 loc) · 16.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/* eslint-disable max-lines */
import os from 'node:os';
import path from 'path';
import { ApolloServer } from '@apollo/server';
import { unwrapResolverError } from '@apollo/server/errors';
import { ApolloServerPluginLandingPageDisabled } from '@apollo/server/plugin/disabled';
import { expressMiddleware } from '@as-integrations/express4';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { MapperKind, mapSchema } from '@graphql-tools/utils';
import { SpanStatusCode } from '@opentelemetry/api';
import {
SEMATTRS_EXCEPTION_MESSAGE,
SEMATTRS_EXCEPTION_STACKTRACE,
SEMATTRS_EXCEPTION_TYPE,
} from '@opentelemetry/semantic-conventions';
import { GraphQLError, type GraphQLFormattedError } from 'graphql';
import bodyParser from 'body-parser';
import connectPgSimple from 'connect-pg-simple';
import cors from 'cors';
import express, { type ErrorRequestHandler } from 'express';
import session from 'express-session';
import { buildContext, GraphQLLocalStrategy } from 'graphql-passport';
import helmet from 'helmet';
import passport from 'passport';
import { MultiSamlStrategy } from '@node-saml/passport-saml';
import {
makeLoginIncorrectPasswordError,
makeLoginSsoRequiredError,
makeLoginUserDoesNotExistError,
} from './graphql/datasources/UserApi.js';
import resolvers, { type Context } from './graphql/resolvers.js';
import typeDefs from './graphql/schema.js';
import { authSchemaWrapper } from './graphql/utils/authorization.js';
import { type Dependencies } from './iocContainer/index.js';
import controllers from './routes/index.js';
import { jsonStringify } from './utils/encoding.js';
import {
ErrorType,
getErrorsFromAggregateError,
makeBadRequestError,
makeInternalServerError,
makeNotFoundError,
sanitizeError,
type SerializableError,
} from './utils/errors.js';
import { safePick } from './utils/misc.js';
import {
isNonEmptyArray,
type NonEmptyArray,
} from './utils/typescript-types.js';
function getCPUInfo() {
const cpus = os.cpus();
const total = cpus.reduce(
(acc, cpu) =>
acc +
cpu.times.user +
cpu.times.nice +
cpu.times.sys +
cpu.times.irq +
cpu.times.idle,
0,
);
const idle = cpus.reduce((acc, cpu) => acc + cpu.times.idle, 0);
return {
idle,
total,
};
}
async function getCPUUsage() {
const stats1 = getCPUInfo();
const startIdle = stats1.idle;
const startTotal = stats1.total;
await new Promise((resolve) => setTimeout(resolve, 1000));
const stats2 = getCPUInfo();
const endIdle = stats2.idle;
const endTotal = stats2.total;
return 1 - (endIdle - startIdle) / (endTotal - startTotal);
}
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const env = process.env.NODE_ENV || 'development';
const sessionStore = connectPgSimple(session);
export default async function makeApiServer(deps: Dependencies) {
const app = express();
const { User } = deps.Sequelize;
app.use(cors());
app.use(helmet(env === 'production' ? {} : { contentSecurityPolicy: false }));
app.use(express.json({ limit: '50mb' }));
app.get('/ready', async (_req, res) => {
const cpuUsage = await getCPUUsage();
if (cpuUsage > 0.75) {
return res.status(500).send('Unhealthy');
}
return res.status(200).send('Healthy');
});
/**
* Passport & User Session Configuration
*/
const {
DATABASE_HOST,
DATABASE_PORT = 5432,
DATABASE_NAME,
DATABASE_USER,
DATABASE_PASSWORD,
} = process.env;
const connectionString = `postgres://${DATABASE_USER}:${DATABASE_PASSWORD}@${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}`;
app.use(
session({
secret: process.env.SESSION_SECRET!,
store: new sessionStore({ conString: connectionString }),
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
sameSite: 'lax',
// 30 Days in milliseconds
maxAge: 30 * 24 * 60 * 60 * 1000,
},
resave: false,
saveUninitialized: false,
proxy: true,
}),
);
app.use(passport.initialize());
app.use(passport.session());
passport.use(
new MultiSamlStrategy(
{
passReqToCallback: true,
async getSamlOptions(req, done) {
// orgId path param should be set in the /saml/* route handlers
const orgId = req.params['orgId'];
if (!orgId) {
return done(
makeNotFoundError('orgId not found in path.', {
shouldErrorSpan: true,
}),
);
}
const samlSettings = await deps.OrgSettingsService.getSamlSettings(
orgId,
);
if (!samlSettings)
return done(
makeInternalServerError('Unexpected error.', {
shouldErrorSpan: true,
}),
);
if (!samlSettings.saml_enabled)
return done(
makeBadRequestError('SAML not enabled for this organization.', {
shouldErrorSpan: true,
}),
);
done(null, {
entryPoint: samlSettings.sso_url as string,
idpCert: samlSettings.cert as string,
// I could use UI_URL here but technically the API could be hosted
// on a different domain in the future so hopefully this is more
// robust, not that it will likely matter.
callbackUrl: `${deps.ConfigService.uiUrl}/api/v1/saml/login/${orgId}/callback`,
issuer: deps.ConfigService.uiUrl,
});
},
},
async (_req, profile, done) => {
try {
const user = await User.findOne({
where: { email: String(profile?.email) },
});
// we should have already checked for this, but couldn't hurt to check
// again
if (user == null) {
return done(
makeLoginUserDoesNotExistError({ shouldErrorSpan: true }),
);
}
return done(null, user as any);
} catch (e) {
return done(
makeInternalServerError('Unknown error during login attempt', {
shouldErrorSpan: true,
}),
);
}
},
async (_req, profile, done) => {
try {
const user = await User.findOne({
where: { email: String(profile?.email) },
});
// we should have already checked for this, but couldn't hurt to check
// again
if (user == null) {
return done(
makeLoginUserDoesNotExistError({ shouldErrorSpan: true }),
);
}
return done(null, user as any);
} catch (e) {
return done(
makeInternalServerError('Unknown error during login attempt', {
shouldErrorSpan: true,
}),
);
}
},
),
);
app.get(
'/saml/login/:orgId',
passport.authenticate('saml', { failureRedirect: '/', failureFlash: true }),
);
app.post(
`/saml/login/:orgId/callback`,
bodyParser.urlencoded({ extended: false }),
passport.authenticate('saml', {
failureRedirect: '/',
failureFlash: true,
}),
(_req, res) => {
res.redirect(`${deps.ConfigService.uiUrl}/dashboard`);
},
);
passport.use(
new GraphQLLocalStrategy(async (email, password, done) => {
try {
const user = await User.findOne({ where: { email: String(email) } });
if (user == null) {
return done(
makeLoginUserDoesNotExistError({ shouldErrorSpan: true }),
);
}
const samlSettings = await deps.OrgSettingsService.getSamlSettings(
user.orgId,
);
if (
samlSettings?.saml_enabled &&
// We allow Coop users to log in with email/password even if SSO is
// enabled
// so Coop employees can manage user accounts
String(email).split('@')[1] !== 'getcoop.com'
) {
return done(
makeLoginSsoRequiredError({
detail:
'SAML is enabled for this organization. Password login is disabled.',
shouldErrorSpan: true,
}),
);
}
if (!user.loginMethods.includes('password')) {
return done(
makeLoginIncorrectPasswordError({
detail: 'Password is not set for user.',
shouldErrorSpan: true,
}),
);
}
// if loginMethod is password, password should be set
if (
await User.passwordMatchesHash(
String(password),
user.password satisfies string | null as string,
)
) {
done(null, user);
} else {
done(makeLoginIncorrectPasswordError({ shouldErrorSpan: true }));
}
} catch (e) {
deps.Tracer.logActiveSpanFailedIfAny(e);
return done(
makeInternalServerError('Unknown error during login attempt', {
shouldErrorSpan: true,
}),
);
}
}),
);
passport.serializeUser((user: any, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
return User.findByPk(String(id), { rejectOnEmpty: true }).then((user) => {
done(null, user);
}, done);
});
/**
* Apollo Server - uses /api/graphql path
*/
const apolloServer = new ApolloServer<Context>({
schema: mapSchema(makeExecutableSchema({ typeDefs, resolvers }), {
[MapperKind.QUERY_ROOT_FIELD](
fieldConfig,
_fieldName,
_typeName,
schema,
) {
return authSchemaWrapper(fieldConfig, schema);
},
[MapperKind.MUTATION_ROOT_FIELD](
fieldConfig,
_fieldName,
_typeName,
schema,
) {
return authSchemaWrapper(fieldConfig, schema);
},
}),
plugins: [
...(process.env.NODE_ENV === 'production'
? [ApolloServerPluginLandingPageDisabled()]
: []),
],
introspection: process.env.NODE_ENV !== 'production',
formatError(formattedError, error) {
// unwrapResolverError removes the GraphQLError wrapper added by graphql-js
// when a non-GraphQL error is thrown from a resolver.
const rawError = unwrapResolverError(error);
// If the raw error is a GraphQLError (explicitly thrown by our code or
// generated by graphql-js for parse/validation errors), the formattedError
// is already correctly shaped -- pass it through.
if (rawError instanceof GraphQLError) {
return formattedError;
}
// For all other errors (CoopError, unexpected errors, context errors),
// sanitize to remove sensitive details and reformat for the client.
const sanitizedError = sanitizeError(
rawError instanceof Error ? rawError : (error as Error),
);
const { title: sanitizedErrorTitle, ...extensions } = sanitizedError;
return {
// When graphql-js wraps the resolver-thrown error in a GraphQLError,
// it automatically tracks some metadata about where the error was thrown
// from. That can be useful to clients, in a way that's a bit different
// from our CoopError.pointer field; it tells them whether a null
// value was return in the response because a given resolver failed, or
// because the field's value is actually null. So, we pass this
// metadata through as-is.
locations: formattedError.locations,
path: formattedError.path,
// Apollo server also defines some predefined error codes that it could
// be helpful for us to mimic on our custom errors (in case Apollo
// clients handle them out of the box). The true, Coop-assigned code
// for the error, though, will be in the `type` key, just like when
// sending errors in REST responses (though, for GQL, this lives under
// `extensions`).
code: extensions.type.includes(ErrorType.Unauthenticated)
? 'UNAUTHENTICATED'
: extensions.type.includes(ErrorType.Unauthorized)
? 'FORBIDDEN'
: extensions.type.includes(ErrorType.InvalidUserInput)
? 'BAD_USER_INPUT'
: 'INTERNAL_SERVER_ERROR',
// Then, this is info from the sanitized version of the actual thrown error.
message: sanitizedErrorTitle,
extensions,
} as unknown as GraphQLFormattedError;
},
});
await apolloServer.start();
app.use(
'/graphql',
express.json(),
expressMiddleware(apolloServer, {
context: async ({ req, res }) => ({
...buildContext({ req, res }),
services: makeGqlServices(deps),
dataSources: deps.DataSources,
} as unknown as Context),
}),
);
Object.entries(controllers).forEach(([_k, controller]) => {
controller.routes.forEach((it) => {
const handler = it.handler(deps);
app[it.method](
path.join(controller.pathPrefix, it.path),
...(Array.isArray(handler) ? handler : [handler]),
);
});
});
// catch 404 and forward to error handler
app.use(function (_req, _res, next) {
next(
makeNotFoundError('Requested route not found.', {
shouldErrorSpan: true,
}),
);
});
// error handler
app.use(async function (err, _req, res, _next) {
await deps.Tracer.addActiveSpan(
{ resource: 'app', operation: 'handleError' },
async (span) => {
span.recordException(err);
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
// I don't know if these attributes are necessary, with recordException
span.setAttribute(SEMATTRS_EXCEPTION_MESSAGE, err.message);
if (err.stack) {
span.setAttribute(SEMATTRS_EXCEPTION_STACKTRACE, err.stack);
}
span.setAttribute(SEMATTRS_EXCEPTION_TYPE, err.name);
const errors = (() => {
if (err instanceof AggregateError) {
const extractedErrors = getErrorsFromAggregateError(err);
return isNonEmptyArray(extractedErrors) ? extractedErrors : [err];
} else {
return [err];
}
})() satisfies NonEmptyArray<unknown>;
// If we had any nested errors (from an AggregateError),
// attach those to the span too.
if (errors.length > 1 || errors[0] !== err) {
span.setAttribute(
'errors',
jsonStringify(
errors.map((it) => safePick(it, ['name', 'message', 'stack'])),
),
);
}
// If we've already sent response headers or the response status code,
// we can't actually send a different status code here: it's an error
// in HTTP to send the headers portion of a response twice. So, we
// need to skip this step.
//
// This can happen, e.g., if we have a request handler that
// immediately responds with a 202/204 but then continues to do some
// processing work in the background, and that work errors.
if (!res.headersSent) {
const safeErrors = errors.map((it) =>
sanitizeError(it),
) satisfies SerializableError[] as NonEmptyArray<SerializableError>;
res.status(pickStatus(safeErrors)).json({ errors: safeErrors });
}
},
);
} as ErrorRequestHandler);
return {
app,
async shutdown() {
await Promise.all([
apolloServer.stop(),
deps.closeSharedResourcesForShutdown(),
]);
},
};
}
function pickStatus(safeErrors: NonEmptyArray<SerializableError>) {
return safeErrors[0].status;
}
function makeGqlServices(deps: Dependencies) {
return {
...safePick(deps, [
'ApiKeyService',
'DerivedFieldsService',
'getItemTypeEventuallyConsistent',
'getEnabledRulesForItemTypeEventuallyConsistent',
'ItemInvestigationService',
'ModerationConfigService',
'ManualReviewToolService',
'HMAHashBankService',
'NcmecService',
'OrgSettingsService',
'PartialItemsService',
'ReportingService',
'RuleEvaluator',
'Sequelize',
'SignalsService',
'SigningKeyPairService',
'UserManagementService',
'UserStatisticsService',
'UserHistoryQueries',
'UserStrikeService',
'SSOService',
]),
// Calling sendEmail straight from a resolver is hella sketch, as the
// resolvers shouldn’t have real business logic in them. Future sendEmail
// calls should be encapsulated inside some business-logic-containing
// service, and it’s that service that should be called from the resolvers.
legacy_DO_NOT_USE_DIRECTLY_sendEmail: deps.sendEmail,
};
}
export type GQLServices = ReturnType<typeof makeGqlServices>;