forked from stoplightio/prism
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
413 lines (371 loc) · 13.5 KB
/
index.ts
File metadata and controls
413 lines (371 loc) · 13.5 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
import { IPrismComponents, IPrismDiagnostic, IPrismInput } from '@stoplight/prism-core';
import {
DiagnosticSeverity,
Dictionary,
IHttpHeaderParam,
IHttpOperation,
IHttpOperationResponse,
IMediaTypeContent,
INodeExample,
} from '@stoplight/types';
import caseless from 'caseless';
import * as chalk from 'chalk';
import * as E from 'fp-ts/Either';
import * as Record from 'fp-ts/Record';
import { pipe } from 'fp-ts/function';
import * as A from 'fp-ts/Array';
import { sequenceT } from 'fp-ts/Apply';
import * as R from 'fp-ts/Reader';
import * as O from 'fp-ts/Option';
import * as RE from 'fp-ts/ReaderEither';
import { get, groupBy, isNumber, isString, keyBy, mapValues, partial, pick } from 'lodash';
import { Logger } from 'pino';
import { is } from 'type-is';
import {
ContentExample,
IHttpMockConfig,
IHttpOperationConfig,
IHttpRequest,
IHttpResponse,
PayloadGenerator,
ProblemJsonError,
} from '../types';
import withLogger from '../withLogger';
import { UNAUTHORIZED, UNPROCESSABLE_ENTITY, INVALID_CONTENT_TYPE, SCHEMA_TOO_COMPLEX } from './errors';
import { generate, generateStatic, SchemaTooComplexGeneratorError } from './generator/JSONSchema';
import helpers from './negotiator/NegotiatorHelpers';
import { IHttpNegotiationResult } from './negotiator/types';
import { runCallback } from './callback/callbacks';
import { logRequest, logResponse } from '../utils/logger';
import {
decodeUriEntities,
deserializeFormBody,
findContentByMediaTypeOrFirst,
splitUriParams,
parseMultipartFormDataParams,
} from '../validator/validators/body';
import { parseMIMEHeader } from '../validator/validators/headers';
import { NonEmptyArray } from 'fp-ts/NonEmptyArray';
export { resetGenerator as resetJSONSchemaGenerator } from './generator/JSONSchema';
const eitherRecordSequence = Record.sequence(E.Applicative);
const eitherSequence = sequenceT(E.Apply);
const mock: IPrismComponents<IHttpOperation, IHttpRequest, IHttpResponse, IHttpMockConfig>['mock'] = ({
resource,
input,
config,
}) => {
const payloadGenerator: PayloadGenerator = config.dynamic
? partial(generate, resource, resource['__bundle__'])
: partial(generateStatic, resource);
return pipe(
withLogger(logger => {
logRequest({ logger, prefix: `${chalk.grey('< ')}`, ...pick(input.data, 'body', 'headers') });
// setting default values
const acceptMediaType = input.data.headers && caseless(input.data.headers).get('accept');
if (!config.mediaTypes && acceptMediaType) {
logger.info(`Request contains an accept header: ${acceptMediaType}`);
config.mediaTypes = acceptMediaType.split(',');
}
return config;
}),
R.chain(mockConfig => negotiateResponse(mockConfig, input, resource)),
R.chain(result => negotiateDeprecation(result, resource)),
R.chain(result => assembleResponse(result, payloadGenerator, config.ignoreExamples ?? false)),
R.chain(
response =>
/* Note: This is now just logging the errors without propagating them back. This might be moved as a first
level concept in Prism.
*/
logger =>
pipe(
response,
E.map(mockResponseLogger(logger)),
E.map(response => runCallbacks({ resource, request: input.data, response })(logger)),
E.chain(() => response)
)
)
);
};
function mockResponseLogger(logger: Logger) {
const prefix = chalk.grey('> ');
return (response: IHttpResponse) => {
logger.info(`${prefix}Responding with "${response.statusCode}"`);
logResponse({
logger,
prefix,
...pick(response, 'statusCode', 'body', 'headers'),
});
return response;
};
}
function runCallbacks({
resource,
request,
response,
}: {
resource: IHttpOperation;
request: IHttpRequest;
response: IHttpResponse;
}) {
return withLogger(logger =>
pipe(
O.fromNullable(resource.callbacks),
O.map(callbacks =>
pipe(
callbacks,
A.map(callback =>
runCallback({ callback, request: parseBodyIfUrlEncoded(request, resource), response })(
logger.child({ name: 'CALLBACK' })
)()
)
)
)
)
);
}
/*
This function should not be here at all, but unfortunately due to some limitations of the Monad we're using (Either)
we cannot carry parsed informations in case of an error — which is what we do need instead.
*/
function parseBodyIfUrlEncoded(request: IHttpRequest, resource: IHttpOperation) {
const contentTypeHeader = caseless(request.headers || {}).get('content-type');
if (!contentTypeHeader) return request;
const [multipartBoundary, mediaType] = parseMIMEHeader(contentTypeHeader);
if (!is(mediaType, ['application/x-www-form-urlencoded', 'multipart/form-data'])) return request;
const specs = pipe(
O.fromNullable(resource.request),
O.chainNullableK(request => request.body),
O.chainNullableK(body => body.contents),
O.getOrElse(() => [] as IMediaTypeContent[])
);
const requestBody = request.body as string;
const encodedUriParams = pipe(
mediaType === 'multipart/form-data'
? parseMultipartFormDataParams(requestBody, multipartBoundary)
: splitUriParams(requestBody),
E.getOrElse<IPrismDiagnostic[], Dictionary<string>>(() => ({} as Dictionary<string>))
);
if (specs.length < 1) {
return Object.assign(request, { body: encodedUriParams });
}
const content = pipe(
O.fromNullable(mediaType),
O.chain(mediaType => findContentByMediaTypeOrFirst(specs, mediaType)),
O.map(({ content }) => content),
O.getOrElse(() => specs[0] || {})
);
const encodings = get(content, 'encodings', []);
if (!content.schema) return Object.assign(request, { body: encodedUriParams });
return Object.assign(request, {
body: deserializeFormBody(content.schema, encodings, decodeUriEntities(encodedUriParams, mediaType)),
});
}
export function createInvalidInputResponse(
failedValidations: NonEmptyArray<IPrismDiagnostic>,
responses: IHttpOperationResponse[],
mockConfig: IHttpOperationConfig
): R.Reader<Logger, E.Either<ProblemJsonError, IHttpNegotiationResult>> {
const expectedCodes = getExpectedCodesForViolations(failedValidations);
const isExampleKeyFromExpectedCodes = !!mockConfig.code && expectedCodes.includes(mockConfig.code);
return pipe(
withLogger(logger => {
logger.warn({ name: 'VALIDATOR' }, 'Request did not pass the validation rules');
failedValidations.map(failedValidation => logger.error({ name: 'VALIDATOR' }, failedValidation.message));
}),
R.chain(() =>
pipe(
helpers.negotiateOptionsForInvalidRequest(
responses,
expectedCodes,
isExampleKeyFromExpectedCodes ? mockConfig.exampleKey : undefined
),
RE.mapLeft(error => {
if (error instanceof ProblemJsonError && error.status === 404) {
return error;
}
return createResponseForViolations(failedValidations);
})
)
)
);
}
function getExpectedCodesForViolations(failedValidations: NonEmptyArray<IPrismDiagnostic>): NonEmptyArray<number> {
const hasSecurityViolations = findValidationByCode(failedValidations, 401);
if (hasSecurityViolations) {
return [401];
}
const hasInvalidContentTypeViolations = findValidationByCode(failedValidations, 415);
if (hasInvalidContentTypeViolations) {
return [415, 422, 400];
}
return [422, 400];
}
function createResponseForViolations(failedValidations: NonEmptyArray<IPrismDiagnostic>) {
const securityViolation = findValidationByCode(failedValidations, 401);
if (securityViolation) {
return createUnauthorisedResponse(securityViolation.tags);
}
const invalidContentViolation = findValidationByCode(failedValidations, 415);
if (invalidContentViolation) {
return createInvalidContentTypeResponse(invalidContentViolation);
}
return createUnprocessableEntityResponse(failedValidations);
}
function findValidationByCode(validations: NonEmptyArray<IPrismDiagnostic>, code: string | number) {
return validations.find(validation => validation.code === code);
}
export const createUnauthorisedResponse = (tags?: string[]): ProblemJsonError =>
ProblemJsonError.fromTemplate(
UNAUTHORIZED,
'Your request does not fullfil the security requirements and no HTTP unauthorized response was found in the spec, so Prism is generating this error for you.',
tags && tags.length ? { headers: { 'WWW-Authenticate': tags.join(',') } } : undefined
);
export const createUnprocessableEntityResponse = (validations: NonEmptyArray<IPrismDiagnostic>): ProblemJsonError =>
ProblemJsonError.fromTemplate(
UNPROCESSABLE_ENTITY,
'Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.',
{
validation: validations.map(detail => ({
location: detail.path,
severity: DiagnosticSeverity[detail.severity],
code: detail.code,
message: detail.message,
})),
}
);
export const createInvalidContentTypeResponse = (validation: IPrismDiagnostic): ProblemJsonError =>
ProblemJsonError.fromTemplate(INVALID_CONTENT_TYPE, validation.message);
function negotiateResponse(
mockConfig: IHttpOperationConfig,
input: IPrismInput<IHttpRequest>,
resource: IHttpOperation
): RE.ReaderEither<Logger, Error, IHttpNegotiationResult> {
const { [DiagnosticSeverity.Error]: errors, [DiagnosticSeverity.Warning]: warnings } = groupBy(
input.validations,
validation => validation.severity
);
if (errors && A.isNonEmpty(input.validations)) {
return createInvalidInputResponse(input.validations, resource.responses, mockConfig);
} else {
return pipe(
withLogger(logger => {
warnings && warnings.forEach(warn => logger.warn({ name: 'VALIDATOR' }, warn.message));
return logger.success(
{ name: 'VALIDATOR' },
'The request passed the validation rules. Looking for the best response'
);
}),
R.chain(() => helpers.negotiateOptionsForValidRequest(resource, mockConfig))
);
}
}
function negotiateDeprecation(
result: E.Either<Error, IHttpNegotiationResult>,
httpOperation: IHttpOperation
): RE.ReaderEither<Logger, Error, IHttpNegotiationResult> {
if (httpOperation.deprecated) {
return pipe(
withLogger(logger => {
logger.info('Adding "Deprecation" header since operation is deprecated');
return result;
}),
RE.map(result => ({
...result,
deprecated: true,
}))
);
}
return RE.fromEither(result);
}
const assembleResponse =
(
result: E.Either<Error, IHttpNegotiationResult>,
payloadGenerator: PayloadGenerator,
ignoreExamples: boolean
): R.Reader<Logger, E.Either<Error, IHttpResponse>> =>
logger =>
pipe(
E.Do,
E.bind('negotiationResult', () => result),
E.bind('mockedData', ({ negotiationResult }) =>
eitherSequence(
computeBody(negotiationResult, payloadGenerator, ignoreExamples),
computeMockedHeaders(negotiationResult.headers || [], payloadGenerator)
)
),
E.map(({ mockedData: [mockedBody, mockedHeaders], negotiationResult }) => {
const response: IHttpResponse = {
statusCode: parseInt(negotiationResult.code),
headers: {
...mockedHeaders,
...(negotiationResult.mediaType && {
'Content-type': negotiationResult.mediaType,
}),
...(negotiationResult.deprecated && {
deprecation: 'true',
}),
},
body: mockedBody,
};
logger.success(`Responding with the requested status code ${response.statusCode}`);
return response;
})
);
function isINodeExample(nodeExample: ContentExample | undefined): nodeExample is INodeExample {
return !!nodeExample && 'value' in nodeExample;
}
function computeMockedHeaders(headers: IHttpHeaderParam[], payloadGenerator: PayloadGenerator) {
return eitherRecordSequence(
mapValues(
keyBy(headers, h => h.name),
header => {
if (header.schema) {
if (header.examples && header.examples.length > 0) {
const example = header.examples[0];
if (isINodeExample(example)) {
return E.right(example.value);
}
} else {
return pipe(
payloadGenerator(header.schema),
mapPayloadGeneratorError('header'),
E.map(example => {
if (isNumber(example) || isString(example)) return example;
return null;
})
);
}
}
return E.right(null);
}
)
);
}
function computeBody(
negotiationResult: Pick<IHttpNegotiationResult, 'schema' | 'mediaType' | 'bodyExample'>,
payloadGenerator: PayloadGenerator,
ignoreExamples: boolean
): E.Either<Error, unknown> {
if (
!ignoreExamples &&
isINodeExample(negotiationResult.bodyExample) &&
negotiationResult.bodyExample.value !== undefined
) {
return E.right(negotiationResult.bodyExample.value);
}
if (negotiationResult.schema) {
return pipe(payloadGenerator(negotiationResult.schema), mapPayloadGeneratorError('body'));
}
return E.right(undefined);
}
const mapPayloadGeneratorError = (source: string) =>
E.mapLeft<Error, Error>(err => {
if (err instanceof SchemaTooComplexGeneratorError) {
return ProblemJsonError.fromTemplate(
SCHEMA_TOO_COMPLEX,
`Unable to generate ${source} for response. The schema is too complex to generate.`
);
}
return err;
});
export default mock;