@nikhil-qeas/api-core 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +141 -5
  3. package/bin/qe-api.js +4 -4
  4. package/dist/contracts/assertions.d.ts +11 -0
  5. package/dist/contracts/assertions.js +31 -0
  6. package/dist/contracts/openapi.d.ts +28 -1
  7. package/dist/contracts/openapi.js +113 -0
  8. package/dist/graphql/graphql.d.ts +86 -0
  9. package/dist/graphql/graphql.js +312 -0
  10. package/dist/http/api-client.d.ts +5 -0
  11. package/dist/http/api-client.js +30 -6
  12. package/dist/http/cookies.d.ts +32 -0
  13. package/dist/http/cookies.js +116 -0
  14. package/dist/http/multipart.d.ts +20 -0
  15. package/dist/http/multipart.js +48 -0
  16. package/dist/http/types.d.ts +16 -0
  17. package/dist/index.d.ts +21 -2
  18. package/dist/index.js +11 -1
  19. package/dist/reporting/redaction.d.ts +4 -0
  20. package/dist/reporting/redaction.js +26 -2
  21. package/dist/security/authorization-matrix.d.ts +55 -0
  22. package/dist/security/authorization-matrix.js +102 -0
  23. package/dist/security/headers.d.ts +21 -0
  24. package/dist/security/headers.js +45 -0
  25. package/dist/security/policy.js +3 -2
  26. package/dist/security/sensitive-data.d.ts +22 -0
  27. package/dist/security/sensitive-data.js +76 -0
  28. package/dist/testing/json-path.d.ts +6 -0
  29. package/dist/testing/json-path.js +97 -0
  30. package/dist/testing/matchers.d.ts +63 -0
  31. package/dist/testing/matchers.js +164 -0
  32. package/dist/testing/spec-cases.d.ts +98 -0
  33. package/dist/testing/spec-cases.js +795 -0
  34. package/dist/testing/wait-for.d.ts +40 -0
  35. package/dist/testing/wait-for.js +82 -0
  36. package/package.json +1 -1
  37. package/templates/project/README.md +55 -6
  38. package/templates/project/__dot__env.example +5 -0
  39. package/templates/project/openapi/openapi.json +243 -19
  40. package/templates/project/src/clients/api.ts +27 -6
  41. package/templates/project/src/{config/environment.ts → environment.ts} +16 -1
  42. package/templates/project/src/observability.ts +1 -1
  43. package/templates/project/src/{contracts/openapi.ts → openapi.ts} +1 -1
  44. package/templates/project/tests/contract/openapi.contract.spec.ts +1 -1
  45. package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
  46. package/templates/project/tests/security/authorization.spec.ts +29 -0
  47. package/templates/project/tests/security/hygiene.spec.ts +37 -0
  48. package/templates/project/tests/security/spec-cases.spec.ts +24 -0
  49. package/templates/project/tests/security/write-protection.spec.ts +60 -0
  50. package/templates/project/tests/smoke/health.spec.ts +3 -3
  51. package/templates/project/tests/support/approved-writes.ts +27 -0
  52. package/templates/project/tests/support/identities.ts +24 -0
  53. package/templates/project/tests/support/mock-api.ts +62 -3
  54. /package/templates/project/{config/mocha.config.json → __dot__mocharc.json} +0 -0
@@ -0,0 +1,795 @@
1
+ import assert from 'node:assert/strict';
2
+ const METHODS = ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH'];
3
+ const SCHEMA_PREFIX = '#/components/schemas/';
4
+ const MAX_SAMPLE_DEPTH = 6;
5
+ const MAX_MUTATION_DEPTH = 3;
6
+ /** The longest string or array a "too long" case builds; a limit beyond this is not probed. */
7
+ const MAX_REPEAT = 10_000;
8
+ const RESERVED_HEADERS = new Set(['authorization', 'content-type', 'accept']);
9
+ // ---------------------------------------------------------------- small helpers
10
+ function isObject(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
11
+ function isString(value) { return typeof value === 'string'; }
12
+ function isContainer(value) { return typeof value === 'object' && value !== null; }
13
+ function num(value) { return typeof value === 'number' && Number.isFinite(value) ? value : undefined; }
14
+ function list(value) { return Array.isArray(value) ? value : []; }
15
+ function unescapeToken(token) { return token.replace(/~1/g, '/').replace(/~0/g, '~'); }
16
+ function clone(value) { return structuredClone(value); }
17
+ function sameJson(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
18
+ function safeRegExp(pattern) {
19
+ try {
20
+ return new RegExp(pattern, 'u');
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ function where(path, root = 'body') {
27
+ return path.reduce((text, segment) => typeof segment === 'number' ? `${text}[${segment}]` : `${text}.${segment}`, root);
28
+ }
29
+ function setAt(body, path, value) {
30
+ if (!path.length)
31
+ return value;
32
+ let cursor = body;
33
+ for (const segment of path.slice(0, -1))
34
+ cursor = isContainer(cursor) ? cursor[segment] : undefined;
35
+ const last = path[path.length - 1];
36
+ if (isContainer(cursor) && last !== undefined)
37
+ cursor[last] = value;
38
+ return body;
39
+ }
40
+ function removeAt(body, path) {
41
+ let cursor = body;
42
+ for (const segment of path.slice(0, -1))
43
+ cursor = isContainer(cursor) ? cursor[segment] : undefined;
44
+ const last = path[path.length - 1];
45
+ if (isContainer(cursor) && last !== undefined)
46
+ delete cursor[last];
47
+ return body;
48
+ }
49
+ function mulberry32(seed) {
50
+ let state = seed >>> 0;
51
+ return () => {
52
+ state = (state + 0x6D2B79F5) >>> 0;
53
+ let t = state;
54
+ t = Math.imul(t ^ (t >>> 15), t | 1);
55
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
56
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
57
+ };
58
+ }
59
+ function mergeSchemas(base, extra) {
60
+ const merged = { ...extra, ...base };
61
+ const properties = { ...(isObject(extra.properties) ? extra.properties : {}), ...(isObject(base.properties) ? base.properties : {}) };
62
+ if (Object.keys(properties).length)
63
+ merged.properties = properties;
64
+ const required = [...new Set([...list(extra.required), ...list(base.required)])];
65
+ if (required.length)
66
+ merged.required = required;
67
+ if (extra.additionalProperties === false || base.additionalProperties === false)
68
+ merged.additionalProperties = false;
69
+ return merged;
70
+ }
71
+ /** Follows local `$ref`s, merges `allOf`, and picks the first `oneOf`/`anyOf` alternative. Undefined when the schema cannot be resolved (remote or cyclic reference). */
72
+ function resolveSchema(doc, raw, depth = 0) {
73
+ if (!isObject(raw) || depth > 30)
74
+ return undefined;
75
+ if (typeof raw.$ref === 'string') {
76
+ if (!raw.$ref.startsWith(SCHEMA_PREFIX))
77
+ return undefined;
78
+ return resolveSchema(doc, doc.components?.schemas?.[unescapeToken(raw.$ref.slice(SCHEMA_PREFIX.length))], depth + 1);
79
+ }
80
+ let schema = { ...raw };
81
+ let ambiguous = false;
82
+ if (Array.isArray(raw.allOf)) {
83
+ for (const part of raw.allOf) {
84
+ const resolved = resolveSchema(doc, part, depth + 1);
85
+ if (!resolved)
86
+ continue;
87
+ schema = mergeSchemas(schema, resolved.schema);
88
+ ambiguous ||= resolved.ambiguous;
89
+ }
90
+ delete schema.allOf;
91
+ }
92
+ for (const key of ['oneOf', 'anyOf']) {
93
+ const alternatives = list(raw[key]);
94
+ if (!alternatives.length)
95
+ continue;
96
+ ambiguous = true;
97
+ const first = resolveSchema(doc, alternatives[0], depth + 1);
98
+ if (first)
99
+ schema = mergeSchemas(schema, first.schema);
100
+ delete schema[key];
101
+ }
102
+ return { schema, ambiguous };
103
+ }
104
+ function typesOf(schema) {
105
+ const declared = Array.isArray(schema.type) ? schema.type.filter(isString) : isString(schema.type) ? [schema.type] : [];
106
+ return schema.nullable === true && !declared.includes('null') ? [...declared, 'null'] : declared; // OpenAPI 3.0 nullable
107
+ }
108
+ function isNullable(schema) { return typesOf(schema).includes('null'); }
109
+ function primaryType(schema) {
110
+ const type = typesOf(schema).find(candidate => candidate !== 'null');
111
+ if (type)
112
+ return type;
113
+ if (isObject(schema.properties))
114
+ return 'object';
115
+ if (schema.items !== undefined)
116
+ return 'array';
117
+ return undefined;
118
+ }
119
+ /** Numeric limits from both dialects: 3.0 uses a boolean `exclusiveMinimum` beside `minimum`, 3.1 a numeric one. */
120
+ function boundsOf(schema) {
121
+ const bounds = { minExclusive: false, maxExclusive: false };
122
+ const minimum = num(schema.minimum);
123
+ const maximum = num(schema.maximum);
124
+ if (minimum !== undefined)
125
+ bounds.min = minimum;
126
+ if (maximum !== undefined)
127
+ bounds.max = maximum;
128
+ if (schema.exclusiveMinimum === true)
129
+ bounds.minExclusive = true;
130
+ const exclusiveMinimum = num(schema.exclusiveMinimum);
131
+ if (exclusiveMinimum !== undefined && (bounds.min === undefined || exclusiveMinimum >= bounds.min)) {
132
+ bounds.min = exclusiveMinimum;
133
+ bounds.minExclusive = true;
134
+ }
135
+ if (schema.exclusiveMaximum === true)
136
+ bounds.maxExclusive = true;
137
+ const exclusiveMaximum = num(schema.exclusiveMaximum);
138
+ if (exclusiveMaximum !== undefined && (bounds.max === undefined || exclusiveMaximum <= bounds.max)) {
139
+ bounds.max = exclusiveMaximum;
140
+ bounds.maxExclusive = true;
141
+ }
142
+ return bounds;
143
+ }
144
+ // ---------------------------------------------------------------- valid samples
145
+ const FORMAT_SAMPLES = {
146
+ uuid: '3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6b', 'date-time': '2026-01-01T00:00:00Z', date: '2026-01-01', time: '12:00:00Z',
147
+ email: 'qa@example.invalid', uri: 'https://example.invalid/', url: 'https://example.invalid/', hostname: 'example.invalid',
148
+ ipv4: '192.0.2.1', ipv6: '2001:db8::1', byte: 'c2FtcGxl'
149
+ };
150
+ const PATTERN_CANDIDATES = ['sample', 'A1', 'a', '1', 'abc123', 'ABC', 'test-1', '12345', 'user@example.invalid'];
151
+ function sampleString(schema, variant) {
152
+ const format = isString(schema.format) ? schema.format : undefined;
153
+ const known = format === undefined ? undefined : FORMAT_SAMPLES[format];
154
+ let value = known ?? (variant > 0 ? `sample-${variant}` : 'sample');
155
+ if (isString(schema.pattern)) {
156
+ const pattern = safeRegExp(schema.pattern);
157
+ if (pattern && !pattern.test(value))
158
+ value = PATTERN_CANDIDATES.find(candidate => pattern.test(candidate)) ?? value;
159
+ }
160
+ const min = num(schema.minLength);
161
+ const max = num(schema.maxLength);
162
+ if (known === undefined) {
163
+ while (min !== undefined && value.length < min && value.length < MAX_REPEAT)
164
+ value += 'a';
165
+ if (max !== undefined && value.length > max)
166
+ value = value.slice(0, Math.max(0, max));
167
+ }
168
+ return value;
169
+ }
170
+ function sampleNumber(schema, integer, variant) {
171
+ const bounds = boundsOf(schema);
172
+ const step = integer ? 1 : 0.5;
173
+ let value = 1;
174
+ if (bounds.min !== undefined)
175
+ value = bounds.minExclusive ? bounds.min + step : bounds.min;
176
+ else if (bounds.max !== undefined && bounds.max < 1)
177
+ value = bounds.maxExclusive ? bounds.max - step : bounds.max;
178
+ const multiple = num(schema.multipleOf);
179
+ if (multiple !== undefined && multiple > 0)
180
+ value = Math.ceil(value / multiple) * multiple;
181
+ return value + variant;
182
+ }
183
+ /** A valid value for the schema, or undefined when it cannot be built (unresolvable reference, too deep). Prefers the spec's own `const`, `example`, `default` and `enum`. */
184
+ function sample(doc, raw, variant = 0, depth = 0) {
185
+ const resolved = resolveSchema(doc, raw);
186
+ if (!resolved || depth > MAX_SAMPLE_DEPTH)
187
+ return undefined;
188
+ const { schema } = resolved;
189
+ if ('const' in schema)
190
+ return clone(schema.const);
191
+ if (schema.example !== undefined)
192
+ return clone(schema.example);
193
+ const examples = list(schema.examples);
194
+ if (examples.length)
195
+ return clone(examples[0]);
196
+ if (schema.default !== undefined)
197
+ return clone(schema.default);
198
+ const allowed = list(schema.enum);
199
+ if (allowed.length)
200
+ return clone(allowed[0]);
201
+ switch (primaryType(schema)) {
202
+ case 'string': return sampleString(schema, variant);
203
+ case 'integer': return sampleNumber(schema, true, variant);
204
+ case 'number': return sampleNumber(schema, false, variant);
205
+ case 'boolean': return true;
206
+ case 'null': return null;
207
+ case 'array': {
208
+ const min = num(schema.minItems) ?? 1;
209
+ const max = num(schema.maxItems);
210
+ const count = Math.min(Math.max(min, 1), max ?? Number.POSITIVE_INFINITY, 20);
211
+ return Array.from({ length: count }, (_, index) => sample(doc, schema.items, index, depth + 1)).filter(item => item !== undefined);
212
+ }
213
+ case 'object': {
214
+ const properties = isObject(schema.properties) ? schema.properties : {};
215
+ const required = new Set(list(schema.required).filter(isString));
216
+ const out = {};
217
+ for (const [name, property] of Object.entries(properties)) {
218
+ const resolvedProperty = resolveSchema(doc, property);
219
+ if (!resolvedProperty || resolvedProperty.schema.readOnly === true)
220
+ continue; // readOnly values are never sent
221
+ const hinted = resolvedProperty.schema.example !== undefined || resolvedProperty.schema.default !== undefined;
222
+ if (!required.has(name) && !hinted)
223
+ continue;
224
+ const value = sample(doc, property, 0, depth + 1);
225
+ if (value !== undefined)
226
+ out[name] = value;
227
+ }
228
+ return out;
229
+ }
230
+ default: return undefined;
231
+ }
232
+ }
233
+ // ---------------------------------------------------------------- invalid values
234
+ const INVALID_FORMAT = {
235
+ uuid: 'not-a-uuid', 'date-time': 'yesterday', date: '2026-13-45', time: '25:61:61', email: 'not-an-email', uri: 'not a uri',
236
+ url: 'not a uri', hostname: '-not a hostname-', ipv4: '999.999.999.999', ipv6: 'not:an:ipv6', byte: '***'
237
+ };
238
+ const PATTERN_BREAKERS = ['', '!', '\u0000', ' ', '~~~', 'ZZZ-###'];
239
+ /**
240
+ * Replacement values that break the schema, each tied to the rule it breaks. Parameters arrive as text, so for them a number or
241
+ * null is not a type violation of a string, and only values that cannot be read as the declared type count.
242
+ */
243
+ function badValues(schema, baseline, forParameter) {
244
+ const out = [];
245
+ const add = (description, violates, value) => { out.push({ description, violates, value }); };
246
+ const type = primaryType(schema);
247
+ if (type === 'string') {
248
+ if (!forParameter)
249
+ add('is a number instead of a string', 'type', 12345);
250
+ const min = num(schema.minLength);
251
+ if (min !== undefined && min > 0 && min <= MAX_REPEAT)
252
+ add(`is shorter than minLength ${min}`, 'minLength', 'a'.repeat(min - 1));
253
+ const max = num(schema.maxLength);
254
+ if (max !== undefined && max >= 0 && max < MAX_REPEAT)
255
+ add(`is longer than maxLength ${max}`, 'maxLength', 'a'.repeat(max + 1));
256
+ if (isString(schema.pattern)) {
257
+ const pattern = safeRegExp(schema.pattern);
258
+ const breaker = pattern ? PATTERN_BREAKERS.find(candidate => !pattern.test(candidate)) : undefined;
259
+ if (breaker !== undefined)
260
+ add('does not match its pattern', 'pattern', breaker);
261
+ }
262
+ const invalidFormat = isString(schema.format) ? INVALID_FORMAT[schema.format] : undefined;
263
+ if (invalidFormat !== undefined)
264
+ add(`is not a valid ${String(schema.format)}`, 'format', invalidFormat);
265
+ }
266
+ else if (type === 'integer' || type === 'number') {
267
+ add('is text instead of a number', 'type', 'not-a-number');
268
+ if (type === 'integer')
269
+ add('is not a whole number', 'type: integer', 1.5);
270
+ const bounds = boundsOf(schema);
271
+ if (bounds.min !== undefined)
272
+ add(`is below the minimum ${bounds.min}`, 'minimum', bounds.minExclusive ? bounds.min : bounds.min - 1);
273
+ if (bounds.max !== undefined)
274
+ add(`is above the maximum ${bounds.max}`, 'maximum', bounds.maxExclusive ? bounds.max : bounds.max + 1);
275
+ const multiple = num(schema.multipleOf);
276
+ if (multiple !== undefined && Number.isInteger(multiple) && multiple > 1)
277
+ add(`is not a multiple of ${multiple}`, 'multipleOf', multiple + 1);
278
+ }
279
+ else if (type === 'boolean') {
280
+ add('is text instead of a boolean', 'type', 'not-a-boolean');
281
+ }
282
+ else if (type === 'array') {
283
+ if (!forParameter)
284
+ add('is text instead of an array', 'type', 'not-an-array');
285
+ const minItems = num(schema.minItems);
286
+ if (minItems !== undefined && minItems > 0)
287
+ add(`has fewer than ${minItems} items`, 'minItems', (Array.isArray(baseline) ? baseline : []).slice(0, minItems - 1));
288
+ const maxItems = num(schema.maxItems);
289
+ if (maxItems !== undefined && maxItems >= 0 && maxItems < 1000) {
290
+ const item = Array.isArray(baseline) && baseline.length ? baseline[0] : 'item';
291
+ add(`has more than ${maxItems} items`, 'maxItems', Array.from({ length: maxItems + 1 }, () => clone(item)));
292
+ }
293
+ }
294
+ else if (type === 'object' && !forParameter) {
295
+ add('is text instead of an object', 'type', 'not-an-object');
296
+ add('is an array instead of an object', 'type', []);
297
+ }
298
+ if (type !== undefined && !isNullable(schema) && !forParameter)
299
+ add('is null', 'type: null', null);
300
+ const allowed = list(schema.enum);
301
+ if (allowed.length) {
302
+ const outsider = ['not-in-enum', 'NOT_IN_ENUM', -999_999].find(candidate => !allowed.some(entry => sameJson(entry, candidate)));
303
+ if (outsider !== undefined)
304
+ add('is not one of the allowed values', 'enum', outsider);
305
+ }
306
+ return out;
307
+ }
308
+ function walk(doc, node, value, path, depth, out) {
309
+ // An ambiguous node (oneOf/anyOf) has no single set of rules, so nothing is claimed about it.
310
+ if (depth >= MAX_MUTATION_DEPTH || node.ambiguous)
311
+ return;
312
+ const { schema } = node;
313
+ if (isObject(value) && primaryType(schema) === 'object') {
314
+ const properties = isObject(schema.properties) ? schema.properties : {};
315
+ const required = new Set(list(schema.required).filter(isString));
316
+ if (schema.additionalProperties === false) {
317
+ out.push({ description: `${where(path)} has an unexpected extra property`, violates: `${where(path)}: additionalProperties`, apply: body => setAt(body, [...path, '__unexpected__'], 'x') });
318
+ }
319
+ for (const [name, rawProperty] of Object.entries(properties)) {
320
+ const property = resolveSchema(doc, rawProperty);
321
+ if (!property || property.schema.readOnly === true)
322
+ continue;
323
+ const propertyPath = [...path, name];
324
+ const label = where(propertyPath);
325
+ const present = Object.prototype.hasOwnProperty.call(value, name);
326
+ if (present && required.has(name))
327
+ out.push({ description: `${label} is missing`, violates: `${label}: required`, apply: body => removeAt(body, propertyPath) });
328
+ if (!property.ambiguous) {
329
+ for (const bad of badValues(property.schema, value[name], false)) {
330
+ out.push({ description: `${label} ${bad.description}`, violates: `${label}: ${bad.violates}`, apply: body => setAt(body, propertyPath, clone(bad.value)) });
331
+ }
332
+ }
333
+ if (present)
334
+ walk(doc, property, value[name], propertyPath, depth + 1, out);
335
+ }
336
+ }
337
+ else if (Array.isArray(value) && value.length && primaryType(schema) === 'array') {
338
+ const items = resolveSchema(doc, schema.items);
339
+ if (!items)
340
+ return;
341
+ const itemPath = [...path, 0];
342
+ if (!items.ambiguous) {
343
+ for (const bad of badValues(items.schema, value[0], false)) {
344
+ out.push({ description: `${where(itemPath)} ${bad.description}`, violates: `${where(itemPath)}: ${bad.violates}`, apply: body => setAt(body, itemPath, clone(bad.value)) });
345
+ }
346
+ }
347
+ walk(doc, items, value[0], itemPath, depth + 1, out);
348
+ }
349
+ }
350
+ // ---------------------------------------------------------------- fuzz material
351
+ const FUZZ_STRINGS = [
352
+ { label: 'empty string', value: '', pathSafe: false },
353
+ { label: 'whitespace only', value: ' ', pathSafe: true },
354
+ { label: '10,000 characters', value: 'A'.repeat(10_000), pathSafe: false },
355
+ { label: 'unicode: emoji, accents, CJK', value: '😀 é ñ 漢字', pathSafe: true },
356
+ { label: 'right-to-left override', value: '‮evil', pathSafe: true },
357
+ { label: 'null byte', value: 'a\u0000b', pathSafe: true },
358
+ { label: 'CR LF', value: 'a\r\nInjected: header', pathSafe: true },
359
+ { label: 'SQL injection', value: '\' OR \'1\'=\'1', pathSafe: true },
360
+ { label: 'SQL drop table', value: '\'; DROP TABLE users; --', pathSafe: true },
361
+ { label: 'script tag', value: '<script>alert(1)</script>', pathSafe: true },
362
+ { label: 'path traversal', value: '../../../etc/passwd', pathSafe: false },
363
+ { label: 'template injection', value: '{{7*7}} ${7*7} #{7*7}', pathSafe: true },
364
+ { label: 'format string', value: '%s%s%s%n', pathSafe: false },
365
+ { label: 'NoSQL operator text', value: '{"$ne": null}', pathSafe: true }
366
+ ];
367
+ const FUZZ_NUMBERS = [
368
+ { label: 'zero', value: 0 },
369
+ { label: 'negative one', value: -1 },
370
+ { label: 'largest safe integer', value: Number.MAX_SAFE_INTEGER },
371
+ { label: 'smallest safe integer', value: Number.MIN_SAFE_INTEGER },
372
+ { label: 'very large number', value: 1e308 },
373
+ { label: 'tiny fraction', value: 1e-308 },
374
+ { label: 'fraction that is not exact', value: 0.1 + 0.2 }
375
+ ];
376
+ function fuzzTargets(doc, node, value, path, depth, out) {
377
+ if (depth >= MAX_MUTATION_DEPTH || node.ambiguous || !isObject(value) || primaryType(node.schema) !== 'object')
378
+ return;
379
+ for (const [name, rawProperty] of Object.entries(isObject(node.schema.properties) ? node.schema.properties : {})) {
380
+ const property = resolveSchema(doc, rawProperty);
381
+ if (!property || property.schema.readOnly === true || property.ambiguous)
382
+ continue;
383
+ const type = primaryType(property.schema);
384
+ const propertyPath = [...path, name];
385
+ if (type === 'string')
386
+ out.push({ path: propertyPath, kind: 'string' });
387
+ else if (type === 'integer' || type === 'number')
388
+ out.push({ path: propertyPath, kind: 'number' });
389
+ else if (type === 'object' && Object.prototype.hasOwnProperty.call(value, name))
390
+ fuzzTargets(doc, property, value[name], propertyPath, depth + 1, out);
391
+ }
392
+ }
393
+ function resolveComponent(doc, raw, bucket) {
394
+ let current = raw;
395
+ for (let hops = 0; hops < 10; hops++) {
396
+ if (!isObject(current))
397
+ return undefined;
398
+ if (typeof current.$ref !== 'string')
399
+ return current;
400
+ const prefix = `#/components/${bucket}/`;
401
+ if (!current.$ref.startsWith(prefix))
402
+ return undefined;
403
+ current = doc.components?.[bucket]?.[unescapeToken(current.$ref.slice(prefix.length))];
404
+ }
405
+ return undefined;
406
+ }
407
+ function mediaTypeOf(value) { return value.split(';', 1)[0]?.trim().toLowerCase() ?? ''; }
408
+ /**
409
+ * Builds test cases from an OpenAPI document: a valid request per operation, requests that break the spec's rules one at a time
410
+ * (negative), and hostile or extreme values (fuzz). Every negative case names the rule it breaks, and can be confirmed against the
411
+ * spec with `OpenApiValidator.assertRequest(case.check)`. Cases for POST, PUT, PATCH and DELETE send writes: run them only
412
+ * against an environment that may be written to.
413
+ */
414
+ export class OpenApiCases {
415
+ doc;
416
+ options;
417
+ operationsByKey = new Map();
418
+ constructor(doc, options = {}) {
419
+ this.doc = doc;
420
+ this.options = options;
421
+ if (typeof doc.openapi !== 'string' || !/^3\.[01]\./.test(doc.openapi))
422
+ throw new Error('Expected OpenAPI 3.0 or 3.1 document');
423
+ for (const [path, rawItem] of Object.entries(doc.paths)) {
424
+ if (!path.startsWith('/'))
425
+ continue; // x- extensions
426
+ if (!isObject(rawItem))
427
+ throw new Error(`Invalid OpenAPI path item ${path}`);
428
+ if (typeof rawItem.$ref === 'string')
429
+ throw new Error(`Path item references are not supported (${path})`);
430
+ for (const method of METHODS) {
431
+ const rawOperation = rawItem[method.toLowerCase()];
432
+ if (rawOperation === undefined)
433
+ continue;
434
+ if (!isObject(rawOperation))
435
+ throw new Error(`Invalid OpenAPI operation ${method} ${path}`);
436
+ this.operationsByKey.set(`${method} ${path}`, this.buildOperation(method, path, rawItem, rawOperation));
437
+ }
438
+ }
439
+ }
440
+ operations(filter = {}) {
441
+ return [...this.operationsByKey.values()].map(operation => operation.info).filter(info => (filter.methods === undefined || filter.methods.includes(info.method)) &&
442
+ (filter.tags === undefined || info.tags.some(tag => filter.tags?.includes(tag))));
443
+ }
444
+ /** One request that satisfies the spec. Expect it to be accepted. */
445
+ valid(reference) {
446
+ const operation = this.find(reference);
447
+ return this.makeCase(operation, 'valid', 1, 'a valid request', 'success', false, undefined, this.baseline(operation), true);
448
+ }
449
+ /** Requests that each break exactly one rule of the spec. Expect a 4xx for every one. */
450
+ negative(reference) {
451
+ const operation = this.find(reference);
452
+ const baseline = this.baseline(operation);
453
+ const cases = [];
454
+ const add = (description, violates, violatesSchema, draft) => {
455
+ cases.push(this.makeCase(operation, 'negative', cases.length + 1, description, 'rejected', violatesSchema, violates, draft, violatesSchema));
456
+ };
457
+ for (const parameter of operation.parameters) {
458
+ const present = parameter.location === 'path' ? baseline.pathParams[parameter.name] : parameter.location === 'query' ? baseline.query[parameter.name] : baseline.headers[parameter.name];
459
+ const label = `${parameter.location} parameter "${parameter.name}"`;
460
+ if (parameter.location !== 'path' && parameter.required && present !== undefined) {
461
+ const draft = clone(baseline);
462
+ if (parameter.location === 'query')
463
+ delete draft.query[parameter.name];
464
+ else
465
+ delete draft.headers[parameter.name];
466
+ add(`${label} is missing`, `${label}: required`, true, draft);
467
+ }
468
+ const resolved = resolveSchema(this.doc, parameter.schema);
469
+ if (!resolved || resolved.ambiguous)
470
+ continue;
471
+ for (const bad of badValues(resolved.schema, present, true)) {
472
+ if (parameter.location === 'path' && bad.value === '')
473
+ continue; // an empty path segment addresses a different route, not an invalid value
474
+ if (parameter.location === 'header' && typeof bad.value !== 'string' && typeof bad.value !== 'number')
475
+ continue;
476
+ const draft = clone(baseline);
477
+ if (parameter.location === 'path')
478
+ draft.pathParams[parameter.name] = bad.value;
479
+ else if (parameter.location === 'query')
480
+ draft.query[parameter.name] = bad.value;
481
+ else
482
+ draft.headers[parameter.name] = String(bad.value);
483
+ add(`${label} ${bad.description}`, `${label}: ${bad.violates}`, true, draft);
484
+ }
485
+ }
486
+ if (operation.bodySchema !== undefined) {
487
+ const root = resolveSchema(this.doc, operation.bodySchema);
488
+ if (operation.bodyRequired && baseline.json !== undefined) {
489
+ const draft = clone(baseline);
490
+ delete draft.json;
491
+ add('the required body is missing', 'body: required', true, draft);
492
+ }
493
+ if (root && baseline.json !== undefined) {
494
+ const mutations = [];
495
+ if (!root.ambiguous)
496
+ for (const bad of badValues(root.schema, baseline.json, false))
497
+ mutations.push({ description: `body ${bad.description}`, violates: `body: ${bad.violates}`, apply: () => clone(bad.value) });
498
+ walk(this.doc, root, baseline.json, [], 0, mutations);
499
+ for (const mutation of mutations) {
500
+ const draft = clone(baseline);
501
+ draft.json = mutation.apply(draft.json);
502
+ add(mutation.description, mutation.violates, true, draft);
503
+ }
504
+ }
505
+ if (baseline.json !== undefined) {
506
+ add('the body is not valid JSON', 'body: malformed JSON', false, { ...clone(baseline), json: undefined, rawBody: '{"broken": ' });
507
+ add('the body has an unsupported content type', 'content-type: text/plain', false, { ...clone(baseline), json: undefined, rawBody: JSON.stringify(baseline.json), contentType: 'text/plain' });
508
+ }
509
+ }
510
+ return cases;
511
+ }
512
+ /** Hostile and extreme values in every string and number field. Expect the API to answer without failing (no 5xx); 2xx and 4xx are both acceptable. */
513
+ fuzz(reference) {
514
+ const operation = this.find(reference);
515
+ const baseline = this.baseline(operation);
516
+ const candidates = [];
517
+ const addString = (target, apply, pathParameter) => {
518
+ for (const fuzz of FUZZ_STRINGS) {
519
+ if (pathParameter && !fuzz.pathSafe)
520
+ continue;
521
+ const draft = clone(baseline);
522
+ apply(draft, fuzz.value);
523
+ candidates.push({ description: `${target} gets ${fuzz.label}`, violates: `${target}: ${fuzz.label}`, draft });
524
+ }
525
+ };
526
+ const addNumber = (target, apply) => {
527
+ for (const fuzz of FUZZ_NUMBERS) {
528
+ const draft = clone(baseline);
529
+ apply(draft, fuzz.value);
530
+ candidates.push({ description: `${target} gets ${fuzz.label}`, violates: `${target}: ${fuzz.label}`, draft });
531
+ }
532
+ };
533
+ for (const parameter of operation.parameters) {
534
+ if (parameter.location === 'header')
535
+ continue; // invalid header values are rejected by the HTTP stack before they reach the API
536
+ const type = primaryType(resolveSchema(this.doc, parameter.schema)?.schema ?? {});
537
+ const label = `${parameter.location} parameter "${parameter.name}"`;
538
+ const set = (draft, value) => {
539
+ if (parameter.location === 'path')
540
+ draft.pathParams[parameter.name] = value;
541
+ else
542
+ draft.query[parameter.name] = value;
543
+ };
544
+ if (type === 'string')
545
+ addString(label, set, parameter.location === 'path');
546
+ else if (type === 'integer' || type === 'number')
547
+ addNumber(label, set);
548
+ }
549
+ if (operation.bodySchema !== undefined && baseline.json !== undefined) {
550
+ const root = resolveSchema(this.doc, operation.bodySchema);
551
+ const targets = [];
552
+ if (root)
553
+ fuzzTargets(this.doc, root, baseline.json, [], 0, targets);
554
+ for (const target of targets) {
555
+ const label = where(target.path);
556
+ if (target.kind === 'string')
557
+ addString(label, (draft, value) => { draft.json = setAt(draft.json, target.path, value); }, false);
558
+ else
559
+ addNumber(label, (draft, value) => { draft.json = setAt(draft.json, target.path, value); });
560
+ }
561
+ const nested = clone(baseline);
562
+ nested.json = undefined;
563
+ nested.rawBody = `${'['.repeat(200)}${']'.repeat(200)}`;
564
+ candidates.push({ description: 'the body is nested 200 levels deep', violates: 'body: deep nesting', draft: nested });
565
+ if (isObject(baseline.json)) {
566
+ const inner = JSON.stringify(baseline.json);
567
+ const polluted = clone(baseline);
568
+ polluted.json = undefined;
569
+ polluted.rawBody = `{"__proto__":{"polluted":true}${inner === '{}' ? '' : ','}${inner.slice(1)}`;
570
+ candidates.push({ description: 'the body carries a __proto__ key', violates: 'body: prototype pollution', draft: polluted });
571
+ }
572
+ }
573
+ const limit = Math.max(0, Math.floor(this.options.maxFuzzCases ?? 60));
574
+ const chosen = this.choose(candidates.length, limit);
575
+ return chosen.map((index, position) => {
576
+ const candidate = candidates[index];
577
+ if (!candidate)
578
+ throw new Error('Internal error: fuzz candidate index out of range');
579
+ return this.makeCase(operation, 'fuzz', position + 1, candidate.description, 'survives', false, candidate.violates, candidate.draft, false);
580
+ });
581
+ }
582
+ /**
583
+ * Authentication cases for a protected operation: no credentials, invalid credentials of each kind the spec declares (bearer, Basic,
584
+ * API key in a header, query or cookie), an empty bearer token and credentials of the wrong type. Each must be refused with a 401 or
585
+ * 403 (a 400 is also accepted for malformed credentials). An operation without a security requirement, or with optional
586
+ * authentication, has none. The requests are sent without the client's own credentials (`skipAuth`).
587
+ */
588
+ security(reference) {
589
+ const operation = this.find(reference);
590
+ if (!operation.info.protected)
591
+ return [];
592
+ const baseline = this.baseline(operation);
593
+ const cases = [];
594
+ const add = (description, violates, accept, change) => {
595
+ const draft = clone(baseline);
596
+ draft.skipAuth = true;
597
+ for (const place of operation.apiKeyPlaces) {
598
+ // Start from a request that carries no credential at all, wherever the spec says one travels.
599
+ if (place.location === 'query')
600
+ delete draft.query[place.name];
601
+ else
602
+ for (const key of Object.keys(draft.headers))
603
+ if (key.toLowerCase() === (place.location === 'cookie' ? 'cookie' : place.name.toLowerCase()))
604
+ delete draft.headers[key];
605
+ }
606
+ change(draft);
607
+ cases.push(this.makeCase(operation, 'security', cases.length + 1, description, 'denied', false, violates, draft, false, accept));
608
+ };
609
+ add('no credentials are sent', 'credentials: none', [401, 403], () => undefined);
610
+ for (const credential of operation.credentials)
611
+ add(credential.description, credential.violates, credential.accept, credential.apply);
612
+ return cases;
613
+ }
614
+ // -------------------------------------------------------------- internals
615
+ buildOperation(method, path, item, operation) {
616
+ const declared = new Map(); // an operation parameter overrides a path-level one of the same name
617
+ const clientHeaders = new Set();
618
+ for (const raw of [...list(item.parameters), ...list(operation.parameters)]) {
619
+ const parameter = resolveComponent(this.doc, raw, 'parameters');
620
+ if (!parameter || !isString(parameter.name))
621
+ continue;
622
+ const location = parameter.in;
623
+ if (location !== 'path' && location !== 'query' && location !== 'header')
624
+ continue; // cookies are not generated
625
+ if (location === 'header' && RESERVED_HEADERS.has(parameter.name.toLowerCase())) {
626
+ if (parameter.required === true)
627
+ clientHeaders.add(parameter.name);
628
+ continue;
629
+ }
630
+ declared.set(`${location}:${parameter.name}`, { name: parameter.name, location, required: parameter.required === true || location === 'path', schema: parameter.schema });
631
+ }
632
+ const body = operation.requestBody === undefined ? undefined : resolveComponent(this.doc, operation.requestBody, 'requestBodies');
633
+ const content = body && isObject(body.content) ? body.content : {};
634
+ const jsonType = Object.keys(content).find(type => mediaTypeOf(type) === 'application/json' || mediaTypeOf(type).endsWith('+json'));
635
+ const jsonMedia = jsonType === undefined ? undefined : content[jsonType];
636
+ const requirements = list(operation.security !== undefined ? operation.security : this.doc.security).filter(isObject);
637
+ const isProtected = requirements.length > 0 && !requirements.some(requirement => Object.keys(requirement).length === 0); // an empty requirement means authentication is optional
638
+ const { credentials, places } = isProtected ? this.credentialsFor(requirements) : { credentials: [], places: [] };
639
+ return {
640
+ info: {
641
+ method, path, operationId: isString(operation.operationId) ? operation.operationId : undefined,
642
+ tags: list(operation.tags).filter(isString), jsonBody: jsonType !== undefined, protected: isProtected,
643
+ unsupportedBody: Object.keys(content).filter(type => type !== jsonType)
644
+ },
645
+ parameters: [...declared.values()],
646
+ clientHeaders: [...clientHeaders],
647
+ bodySchema: isObject(jsonMedia) ? jsonMedia.schema : undefined,
648
+ bodyRequired: body?.required === true,
649
+ credentials,
650
+ apiKeyPlaces: places
651
+ };
652
+ }
653
+ /** The wrong credentials worth trying for the schemes the requirements name. */
654
+ credentialsFor(requirements) {
655
+ const schemes = new Map();
656
+ for (const requirement of requirements) {
657
+ for (const name of Object.keys(requirement)) {
658
+ const scheme = this.doc.components?.securitySchemes?.[name];
659
+ if (isObject(scheme))
660
+ schemes.set(name, scheme);
661
+ }
662
+ }
663
+ const credentials = [];
664
+ const places = [];
665
+ let bearer = false;
666
+ let basic = false;
667
+ for (const scheme of schemes.values()) {
668
+ const httpScheme = isString(scheme.scheme) ? scheme.scheme.toLowerCase() : '';
669
+ const where = scheme.in;
670
+ if ((scheme.type === 'http' && httpScheme === 'bearer') || scheme.type === 'oauth2' || scheme.type === 'openIdConnect')
671
+ bearer = true;
672
+ else if (scheme.type === 'http' && httpScheme === 'basic')
673
+ basic = true;
674
+ else if (scheme.type === 'apiKey' && isString(scheme.name) && (where === 'header' || where === 'query' || where === 'cookie')) {
675
+ const place = { location: where, name: scheme.name };
676
+ places.push(place);
677
+ credentials.push({
678
+ description: `an invalid API key is sent in the ${where} "${place.name}"`, violates: `credentials: invalid API key (${where})`, accept: [401, 403],
679
+ apply: draft => {
680
+ if (place.location === 'query')
681
+ draft.query[place.name] = 'invalid-api-key';
682
+ else if (place.location === 'cookie')
683
+ draft.headers.Cookie = `${place.name}=invalid-api-key`;
684
+ else
685
+ draft.headers[place.name] = 'invalid-api-key';
686
+ }
687
+ });
688
+ }
689
+ }
690
+ if (bearer) {
691
+ credentials.push({ description: 'an invalid bearer token is sent', violates: 'credentials: invalid bearer token', accept: [401, 403], apply: draft => { draft.headers.Authorization = 'Bearer invalid-token-for-testing'; } }, { description: 'an empty bearer token is sent', violates: 'credentials: empty bearer token', accept: [400, 401, 403], apply: draft => { draft.headers.Authorization = 'Bearer'; } });
692
+ }
693
+ if (basic)
694
+ credentials.push({ description: 'invalid Basic credentials are sent', violates: 'credentials: invalid Basic credentials', accept: [401, 403], apply: draft => { draft.headers.Authorization = 'Basic aW52YWxpZDppbnZhbGlk'; } });
695
+ if (bearer && !basic) {
696
+ credentials.push({ description: 'credentials of the wrong type are sent (Basic instead of Bearer)', violates: 'credentials: wrong scheme', accept: [400, 401, 403], apply: draft => { draft.headers.Authorization = 'Basic aW52YWxpZDppbnZhbGlk'; } });
697
+ }
698
+ return { credentials, places };
699
+ }
700
+ find(reference) {
701
+ const operation = this.operationsByKey.get(`${reference.method} ${reference.path}`);
702
+ if (!operation)
703
+ throw new Error(`Operation not found in the OpenAPI document: ${reference.method} ${reference.path}`);
704
+ return operation;
705
+ }
706
+ /** A request that satisfies the spec: required parameters, an example or sampled body, and any known-good values the caller supplied. */
707
+ baseline(operation) {
708
+ const override = this.options.baselines?.[`${operation.info.method} ${operation.info.path}`];
709
+ const draft = { pathParams: { ...override?.pathParams }, query: { ...override?.query }, headers: { ...override?.headers } };
710
+ for (const parameter of operation.parameters) {
711
+ const supplied = parameter.location === 'path' ? draft.pathParams[parameter.name] : parameter.location === 'query' ? draft.query[parameter.name] : draft.headers[parameter.name];
712
+ if (supplied !== undefined)
713
+ continue;
714
+ const resolved = resolveSchema(this.doc, parameter.schema);
715
+ const hinted = resolved !== undefined && (resolved.schema.example !== undefined || resolved.schema.default !== undefined);
716
+ if (!parameter.required && !hinted)
717
+ continue;
718
+ const value = sample(this.doc, parameter.schema);
719
+ if (value === undefined)
720
+ continue;
721
+ if (parameter.location === 'path')
722
+ draft.pathParams[parameter.name] = value;
723
+ else if (parameter.location === 'query')
724
+ draft.query[parameter.name] = value;
725
+ else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
726
+ draft.headers[parameter.name] = String(value);
727
+ }
728
+ if (operation.bodySchema !== undefined) {
729
+ const json = override?.json !== undefined ? clone(override.json) : sample(this.doc, operation.bodySchema);
730
+ if (json !== undefined)
731
+ draft.json = json;
732
+ }
733
+ return draft;
734
+ }
735
+ makeCase(operation, kind, number, description, expect, violatesSchema, violates, draft, withCheck, accept) {
736
+ const { method, path } = operation.info;
737
+ const request = { method, path: path.replace(/\{([^}]+)\}/g, (_match, name) => encodeURIComponent(String(draft.pathParams[name] ?? ''))) };
738
+ if (Object.keys(draft.query).length)
739
+ request.query = draft.query;
740
+ const headers = { ...draft.headers };
741
+ if (draft.rawBody !== undefined) {
742
+ request.rawBody = draft.rawBody;
743
+ headers['Content-Type'] = draft.contentType ?? 'application/json';
744
+ }
745
+ else if (draft.json !== undefined) {
746
+ request.json = draft.json;
747
+ }
748
+ if (Object.keys(headers).length)
749
+ request.headers = headers;
750
+ if (draft.skipAuth)
751
+ request.skipAuth = true;
752
+ const id = `${method} ${path} ${kind} #${number}`;
753
+ return {
754
+ id, name: `${method} ${path}: ${description}`, kind, method, path, description, expect, violatesSchema, violates, request, accept,
755
+ check: withCheck ? { method, path, pathParams: draft.pathParams, query: draft.query, headers: { ...Object.fromEntries(operation.clientHeaders.map(name => [name, 'supplied-by-the-client'])), ...draft.headers }, json: draft.json, contentType: draft.contentType } : undefined
756
+ };
757
+ }
758
+ /** Picks `limit` of `count` candidates reproducibly (seeded shuffle), keeping their original order. */
759
+ choose(count, limit) {
760
+ const indexes = Array.from({ length: count }, (_, index) => index);
761
+ if (count <= limit)
762
+ return indexes;
763
+ const random = mulberry32(this.options.seed ?? 1);
764
+ for (let i = indexes.length - 1; i > 0; i--) {
765
+ const j = Math.floor(random() * (i + 1));
766
+ [indexes[i], indexes[j]] = [indexes[j], indexes[i]];
767
+ }
768
+ return indexes.slice(0, limit).sort((a, b) => a - b);
769
+ }
770
+ }
771
+ /**
772
+ * Judges a response to a generated case. The message names the case and the rule it broke, and never includes the response body.
773
+ * 'success': 2xx. 'rejected': 4xx (accepting invalid input, or failing with a 5xx, is a defect). 'survives': anything below 500.
774
+ */
775
+ export function assertCaseOutcome(response, testCase) {
776
+ const { status } = response;
777
+ const label = `${testCase.method} ${testCase.path}: ${testCase.description}`;
778
+ const broke = testCase.violates === undefined ? '' : ` (${testCase.violates})`;
779
+ if (testCase.expect === 'success') {
780
+ assert.ok(status >= 200 && status < 300, `${label}: the valid request was refused with HTTP ${status}`);
781
+ }
782
+ else if (testCase.expect === 'rejected') {
783
+ assert.ok(status < 500, `${label}${broke}: the server failed with HTTP ${status} instead of rejecting the input`);
784
+ assert.ok(status >= 400, `${label}${broke}: invalid input was accepted with HTTP ${status}`);
785
+ }
786
+ else if (testCase.expect === 'denied') {
787
+ const accepted = testCase.accept ?? [401, 403];
788
+ assert.ok(status < 500, `${label}${broke}: the server failed with HTTP ${status} instead of refusing the request`);
789
+ assert.ok(status < 200 || status >= 300, `${label}${broke}: access was granted with HTTP ${status} without valid credentials`);
790
+ assert.ok(accepted.includes(status), `${label}${broke}: refused with HTTP ${status}, expected ${accepted.join(' or ')}`);
791
+ }
792
+ else {
793
+ assert.ok(status < 500, `${label}${broke}: the server failed with HTTP ${status} on hostile input`);
794
+ }
795
+ }