@nikhil-qeas/api-core 0.6.0 → 0.8.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.
- package/CHANGELOG.md +67 -0
- package/README.md +216 -5
- package/bin/qe-api.js +3 -0
- package/dist/contracts/assertions.d.ts +11 -0
- package/dist/contracts/assertions.js +31 -0
- package/dist/contracts/openapi.d.ts +28 -1
- package/dist/contracts/openapi.js +113 -0
- package/dist/graphql/graphql.d.ts +86 -0
- package/dist/graphql/graphql.js +312 -0
- package/dist/http/api-client.d.ts +20 -0
- package/dist/http/api-client.js +70 -9
- package/dist/http/cookies.d.ts +32 -0
- package/dist/http/cookies.js +116 -0
- package/dist/http/multipart.d.ts +20 -0
- package/dist/http/multipart.js +48 -0
- package/dist/http/trace.d.ts +26 -0
- package/dist/http/trace.js +43 -0
- package/dist/http/types.d.ts +22 -0
- package/dist/index.d.ts +31 -5
- package/dist/index.js +16 -3
- package/dist/integrations/mocha.d.ts +32 -0
- package/dist/integrations/mocha.js +81 -0
- package/dist/reporting/html-report.d.ts +23 -0
- package/dist/reporting/html-report.js +118 -0
- package/dist/reporting/junit.d.ts +11 -2
- package/dist/reporting/junit.js +9 -3
- package/dist/reporting/redaction.d.ts +10 -0
- package/dist/reporting/redaction.js +36 -2
- package/dist/security/authorization-matrix.d.ts +55 -0
- package/dist/security/authorization-matrix.js +102 -0
- package/dist/security/headers.d.ts +21 -0
- package/dist/security/headers.js +45 -0
- package/dist/security/policy.js +3 -2
- package/dist/security/sensitive-data.d.ts +22 -0
- package/dist/security/sensitive-data.js +76 -0
- package/dist/testing/json-path.d.ts +6 -0
- package/dist/testing/json-path.js +97 -0
- package/dist/testing/load.d.ts +85 -0
- package/dist/testing/load.js +134 -0
- package/dist/testing/matchers.d.ts +63 -0
- package/dist/testing/matchers.js +164 -0
- package/dist/testing/spec-cases.d.ts +136 -0
- package/dist/testing/spec-cases.js +1065 -0
- package/dist/testing/wait-for.d.ts +40 -0
- package/dist/testing/wait-for.js +82 -0
- package/package.json +1 -1
- package/templates/project/README.md +80 -5
- package/templates/project/__dot__env.example +4 -0
- package/templates/project/__dot__gitlab-ci.yml +1 -0
- package/templates/project/openapi/openapi.json +476 -19
- package/templates/project/src/clients/api.ts +4 -2
- package/templates/project/src/environment.ts +8 -0
- package/templates/project/src/observability.ts +15 -1
- package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
- package/templates/project/tests/performance/health.spec.ts +22 -0
- package/templates/project/tests/security/authentication.spec.ts +3 -1
- package/templates/project/tests/security/authorization.spec.ts +29 -0
- package/templates/project/tests/security/hygiene.spec.ts +37 -0
- package/templates/project/tests/security/spec-cases.spec.ts +61 -0
- package/templates/project/tests/security/write-protection.spec.ts +2 -2
- package/templates/project/tests/setup/hooks.ts +32 -5
- package/templates/project/tests/smoke/health.spec.ts +3 -3
- package/templates/project/tests/smoke/tracing.spec.ts +48 -0
- package/templates/project/tests/support/approved-writes.ts +27 -0
- package/templates/project/tests/support/identities.ts +24 -0
- package/templates/project/tests/support/mock-api.ts +166 -3
|
@@ -0,0 +1,1065 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { encodeForm } from '../http/api-client.js';
|
|
3
|
+
import { encodeMultipart } from '../http/multipart.js';
|
|
4
|
+
import { keyWords } from '../reporting/redaction.js';
|
|
5
|
+
const METHODS = ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH'];
|
|
6
|
+
const SCHEMA_PREFIX = '#/components/schemas/';
|
|
7
|
+
const MAX_SAMPLE_DEPTH = 6;
|
|
8
|
+
const MAX_MUTATION_DEPTH = 3;
|
|
9
|
+
/** The longest string or array a "too long" case builds; a limit beyond this is not probed. */
|
|
10
|
+
const MAX_REPEAT = 10_000;
|
|
11
|
+
const RESERVED_HEADERS = new Set(['authorization', 'content-type', 'accept']);
|
|
12
|
+
// ---------------------------------------------------------------- small helpers
|
|
13
|
+
function isObject(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
|
|
14
|
+
function isString(value) { return typeof value === 'string'; }
|
|
15
|
+
function isContainer(value) { return typeof value === 'object' && value !== null; }
|
|
16
|
+
function num(value) { return typeof value === 'number' && Number.isFinite(value) ? value : undefined; }
|
|
17
|
+
function list(value) { return Array.isArray(value) ? value : []; }
|
|
18
|
+
function unescapeToken(token) { return token.replace(/~1/g, '/').replace(/~0/g, '~'); }
|
|
19
|
+
function clone(value) { return structuredClone(value); }
|
|
20
|
+
function sameJson(a, b) { return JSON.stringify(a) === JSON.stringify(b); }
|
|
21
|
+
function safeRegExp(pattern) {
|
|
22
|
+
try {
|
|
23
|
+
return new RegExp(pattern, 'u');
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function where(path, root = 'body') {
|
|
30
|
+
return path.reduce((text, segment) => typeof segment === 'number' ? `${text}[${segment}]` : `${text}.${segment}`, root);
|
|
31
|
+
}
|
|
32
|
+
function setAt(body, path, value) {
|
|
33
|
+
if (!path.length)
|
|
34
|
+
return value;
|
|
35
|
+
let cursor = body;
|
|
36
|
+
for (const segment of path.slice(0, -1))
|
|
37
|
+
cursor = isContainer(cursor) ? cursor[segment] : undefined;
|
|
38
|
+
const last = path[path.length - 1];
|
|
39
|
+
if (isContainer(cursor) && last !== undefined)
|
|
40
|
+
cursor[last] = value;
|
|
41
|
+
return body;
|
|
42
|
+
}
|
|
43
|
+
function removeAt(body, path) {
|
|
44
|
+
let cursor = body;
|
|
45
|
+
for (const segment of path.slice(0, -1))
|
|
46
|
+
cursor = isContainer(cursor) ? cursor[segment] : undefined;
|
|
47
|
+
const last = path[path.length - 1];
|
|
48
|
+
if (isContainer(cursor) && last !== undefined)
|
|
49
|
+
delete cursor[last];
|
|
50
|
+
return body;
|
|
51
|
+
}
|
|
52
|
+
function mulberry32(seed) {
|
|
53
|
+
let state = seed >>> 0;
|
|
54
|
+
return () => {
|
|
55
|
+
state = (state + 0x6D2B79F5) >>> 0;
|
|
56
|
+
let t = state;
|
|
57
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
58
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
59
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function mergeSchemas(base, extra) {
|
|
63
|
+
const merged = { ...extra, ...base };
|
|
64
|
+
const properties = { ...(isObject(extra.properties) ? extra.properties : {}), ...(isObject(base.properties) ? base.properties : {}) };
|
|
65
|
+
if (Object.keys(properties).length)
|
|
66
|
+
merged.properties = properties;
|
|
67
|
+
const required = [...new Set([...list(extra.required), ...list(base.required)])];
|
|
68
|
+
if (required.length)
|
|
69
|
+
merged.required = required;
|
|
70
|
+
if (extra.additionalProperties === false || base.additionalProperties === false)
|
|
71
|
+
merged.additionalProperties = false;
|
|
72
|
+
return merged;
|
|
73
|
+
}
|
|
74
|
+
/** Follows local `$ref`s, merges `allOf`, and picks the first `oneOf`/`anyOf` alternative. Undefined when the schema cannot be resolved (remote or cyclic reference). */
|
|
75
|
+
function resolveSchema(doc, raw, depth = 0) {
|
|
76
|
+
if (!isObject(raw) || depth > 30)
|
|
77
|
+
return undefined;
|
|
78
|
+
if (typeof raw.$ref === 'string') {
|
|
79
|
+
if (!raw.$ref.startsWith(SCHEMA_PREFIX))
|
|
80
|
+
return undefined;
|
|
81
|
+
return resolveSchema(doc, doc.components?.schemas?.[unescapeToken(raw.$ref.slice(SCHEMA_PREFIX.length))], depth + 1);
|
|
82
|
+
}
|
|
83
|
+
let schema = { ...raw };
|
|
84
|
+
let ambiguous = false;
|
|
85
|
+
if (Array.isArray(raw.allOf)) {
|
|
86
|
+
for (const part of raw.allOf) {
|
|
87
|
+
const resolved = resolveSchema(doc, part, depth + 1);
|
|
88
|
+
if (!resolved)
|
|
89
|
+
continue;
|
|
90
|
+
schema = mergeSchemas(schema, resolved.schema);
|
|
91
|
+
ambiguous ||= resolved.ambiguous;
|
|
92
|
+
}
|
|
93
|
+
delete schema.allOf;
|
|
94
|
+
}
|
|
95
|
+
for (const key of ['oneOf', 'anyOf']) {
|
|
96
|
+
const alternatives = list(raw[key]);
|
|
97
|
+
if (!alternatives.length)
|
|
98
|
+
continue;
|
|
99
|
+
ambiguous = true;
|
|
100
|
+
const first = resolveSchema(doc, alternatives[0], depth + 1);
|
|
101
|
+
if (first)
|
|
102
|
+
schema = mergeSchemas(schema, first.schema);
|
|
103
|
+
delete schema[key];
|
|
104
|
+
}
|
|
105
|
+
return { schema, ambiguous };
|
|
106
|
+
}
|
|
107
|
+
function typesOf(schema) {
|
|
108
|
+
const declared = Array.isArray(schema.type) ? schema.type.filter(isString) : isString(schema.type) ? [schema.type] : [];
|
|
109
|
+
return schema.nullable === true && !declared.includes('null') ? [...declared, 'null'] : declared; // OpenAPI 3.0 nullable
|
|
110
|
+
}
|
|
111
|
+
function isNullable(schema) { return typesOf(schema).includes('null'); }
|
|
112
|
+
function primaryType(schema) {
|
|
113
|
+
const type = typesOf(schema).find(candidate => candidate !== 'null');
|
|
114
|
+
if (type)
|
|
115
|
+
return type;
|
|
116
|
+
if (isObject(schema.properties))
|
|
117
|
+
return 'object';
|
|
118
|
+
if (schema.items !== undefined)
|
|
119
|
+
return 'array';
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
/** Numeric limits from both dialects: 3.0 uses a boolean `exclusiveMinimum` beside `minimum`, 3.1 a numeric one. */
|
|
123
|
+
function boundsOf(schema) {
|
|
124
|
+
const bounds = { minExclusive: false, maxExclusive: false };
|
|
125
|
+
const minimum = num(schema.minimum);
|
|
126
|
+
const maximum = num(schema.maximum);
|
|
127
|
+
if (minimum !== undefined)
|
|
128
|
+
bounds.min = minimum;
|
|
129
|
+
if (maximum !== undefined)
|
|
130
|
+
bounds.max = maximum;
|
|
131
|
+
if (schema.exclusiveMinimum === true)
|
|
132
|
+
bounds.minExclusive = true;
|
|
133
|
+
const exclusiveMinimum = num(schema.exclusiveMinimum);
|
|
134
|
+
if (exclusiveMinimum !== undefined && (bounds.min === undefined || exclusiveMinimum >= bounds.min)) {
|
|
135
|
+
bounds.min = exclusiveMinimum;
|
|
136
|
+
bounds.minExclusive = true;
|
|
137
|
+
}
|
|
138
|
+
if (schema.exclusiveMaximum === true)
|
|
139
|
+
bounds.maxExclusive = true;
|
|
140
|
+
const exclusiveMaximum = num(schema.exclusiveMaximum);
|
|
141
|
+
if (exclusiveMaximum !== undefined && (bounds.max === undefined || exclusiveMaximum <= bounds.max)) {
|
|
142
|
+
bounds.max = exclusiveMaximum;
|
|
143
|
+
bounds.maxExclusive = true;
|
|
144
|
+
}
|
|
145
|
+
return bounds;
|
|
146
|
+
}
|
|
147
|
+
// ---------------------------------------------------------------- valid samples
|
|
148
|
+
const FORMAT_SAMPLES = {
|
|
149
|
+
uuid: '3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6b', 'date-time': '2026-01-01T00:00:00Z', date: '2026-01-01', time: '12:00:00Z',
|
|
150
|
+
email: 'qa@example.invalid', uri: 'https://example.invalid/', url: 'https://example.invalid/', hostname: 'example.invalid',
|
|
151
|
+
ipv4: '192.0.2.1', ipv6: '2001:db8::1', byte: 'c2FtcGxl'
|
|
152
|
+
};
|
|
153
|
+
const PATTERN_CANDIDATES = ['sample', 'A1', 'a', '1', 'abc123', 'ABC', 'test-1', '12345', 'user@example.invalid'];
|
|
154
|
+
function sampleString(schema, variant) {
|
|
155
|
+
const format = isString(schema.format) ? schema.format : undefined;
|
|
156
|
+
const known = format === undefined ? undefined : FORMAT_SAMPLES[format];
|
|
157
|
+
let value = known ?? (variant > 0 ? `sample-${variant}` : 'sample');
|
|
158
|
+
if (isString(schema.pattern)) {
|
|
159
|
+
const pattern = safeRegExp(schema.pattern);
|
|
160
|
+
if (pattern && !pattern.test(value))
|
|
161
|
+
value = PATTERN_CANDIDATES.find(candidate => pattern.test(candidate)) ?? value;
|
|
162
|
+
}
|
|
163
|
+
const min = num(schema.minLength);
|
|
164
|
+
const max = num(schema.maxLength);
|
|
165
|
+
if (known === undefined) {
|
|
166
|
+
while (min !== undefined && value.length < min && value.length < MAX_REPEAT)
|
|
167
|
+
value += 'a';
|
|
168
|
+
if (max !== undefined && value.length > max)
|
|
169
|
+
value = value.slice(0, Math.max(0, max));
|
|
170
|
+
}
|
|
171
|
+
return value;
|
|
172
|
+
}
|
|
173
|
+
function sampleNumber(schema, integer, variant) {
|
|
174
|
+
const bounds = boundsOf(schema);
|
|
175
|
+
const step = integer ? 1 : 0.5;
|
|
176
|
+
let value = 1;
|
|
177
|
+
if (bounds.min !== undefined)
|
|
178
|
+
value = bounds.minExclusive ? bounds.min + step : bounds.min;
|
|
179
|
+
else if (bounds.max !== undefined && bounds.max < 1)
|
|
180
|
+
value = bounds.maxExclusive ? bounds.max - step : bounds.max;
|
|
181
|
+
const multiple = num(schema.multipleOf);
|
|
182
|
+
if (multiple !== undefined && multiple > 0)
|
|
183
|
+
value = Math.ceil(value / multiple) * multiple;
|
|
184
|
+
return value + variant;
|
|
185
|
+
}
|
|
186
|
+
/** 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`. */
|
|
187
|
+
function sample(doc, raw, variant = 0, depth = 0) {
|
|
188
|
+
const resolved = resolveSchema(doc, raw);
|
|
189
|
+
if (!resolved || depth > MAX_SAMPLE_DEPTH)
|
|
190
|
+
return undefined;
|
|
191
|
+
const { schema } = resolved;
|
|
192
|
+
if ('const' in schema)
|
|
193
|
+
return clone(schema.const);
|
|
194
|
+
if (schema.example !== undefined)
|
|
195
|
+
return clone(schema.example);
|
|
196
|
+
const examples = list(schema.examples);
|
|
197
|
+
if (examples.length)
|
|
198
|
+
return clone(examples[0]);
|
|
199
|
+
if (schema.default !== undefined)
|
|
200
|
+
return clone(schema.default);
|
|
201
|
+
const allowed = list(schema.enum);
|
|
202
|
+
if (allowed.length)
|
|
203
|
+
return clone(allowed[0]);
|
|
204
|
+
switch (primaryType(schema)) {
|
|
205
|
+
case 'string': return sampleString(schema, variant);
|
|
206
|
+
case 'integer': return sampleNumber(schema, true, variant);
|
|
207
|
+
case 'number': return sampleNumber(schema, false, variant);
|
|
208
|
+
case 'boolean': return true;
|
|
209
|
+
case 'null': return null;
|
|
210
|
+
case 'array': {
|
|
211
|
+
const min = num(schema.minItems) ?? 1;
|
|
212
|
+
const max = num(schema.maxItems);
|
|
213
|
+
const count = Math.min(Math.max(min, 1), max ?? Number.POSITIVE_INFINITY, 20);
|
|
214
|
+
return Array.from({ length: count }, (_, index) => sample(doc, schema.items, index, depth + 1)).filter(item => item !== undefined);
|
|
215
|
+
}
|
|
216
|
+
case 'object': {
|
|
217
|
+
const properties = isObject(schema.properties) ? schema.properties : {};
|
|
218
|
+
const required = new Set(list(schema.required).filter(isString));
|
|
219
|
+
const out = {};
|
|
220
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
221
|
+
const resolvedProperty = resolveSchema(doc, property);
|
|
222
|
+
if (!resolvedProperty || resolvedProperty.schema.readOnly === true)
|
|
223
|
+
continue; // readOnly values are never sent
|
|
224
|
+
const hinted = resolvedProperty.schema.example !== undefined || resolvedProperty.schema.default !== undefined;
|
|
225
|
+
if (!required.has(name) && !hinted)
|
|
226
|
+
continue;
|
|
227
|
+
const value = sample(doc, property, 0, depth + 1);
|
|
228
|
+
if (value !== undefined)
|
|
229
|
+
out[name] = value;
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
default: return undefined;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
// ---------------------------------------------------------------- invalid values
|
|
237
|
+
const INVALID_FORMAT = {
|
|
238
|
+
uuid: 'not-a-uuid', 'date-time': 'yesterday', date: '2026-13-45', time: '25:61:61', email: 'not-an-email', uri: 'not a uri',
|
|
239
|
+
url: 'not a uri', hostname: '-not a hostname-', ipv4: '999.999.999.999', ipv6: 'not:an:ipv6', byte: '***'
|
|
240
|
+
};
|
|
241
|
+
const PATTERN_BREAKERS = ['', '!', '\u0000', ' ', '~~~', 'ZZZ-###'];
|
|
242
|
+
/**
|
|
243
|
+
* Replacement values that break the schema, each tied to the rule it breaks. Parameters arrive as text, so for them a number or
|
|
244
|
+
* null is not a type violation of a string, and only values that cannot be read as the declared type count.
|
|
245
|
+
*/
|
|
246
|
+
function badValues(schema, baseline, forParameter) {
|
|
247
|
+
const out = [];
|
|
248
|
+
const add = (description, violates, value) => { out.push({ description, violates, value }); };
|
|
249
|
+
const type = primaryType(schema);
|
|
250
|
+
if (type === 'string') {
|
|
251
|
+
if (!forParameter)
|
|
252
|
+
add('is a number instead of a string', 'type', 12345);
|
|
253
|
+
const min = num(schema.minLength);
|
|
254
|
+
if (min !== undefined && min > 0 && min <= MAX_REPEAT)
|
|
255
|
+
add(`is shorter than minLength ${min}`, 'minLength', 'a'.repeat(min - 1));
|
|
256
|
+
const max = num(schema.maxLength);
|
|
257
|
+
if (max !== undefined && max >= 0 && max < MAX_REPEAT)
|
|
258
|
+
add(`is longer than maxLength ${max}`, 'maxLength', 'a'.repeat(max + 1));
|
|
259
|
+
if (isString(schema.pattern)) {
|
|
260
|
+
const pattern = safeRegExp(schema.pattern);
|
|
261
|
+
const breaker = pattern ? PATTERN_BREAKERS.find(candidate => !pattern.test(candidate)) : undefined;
|
|
262
|
+
if (breaker !== undefined)
|
|
263
|
+
add('does not match its pattern', 'pattern', breaker);
|
|
264
|
+
}
|
|
265
|
+
const invalidFormat = isString(schema.format) ? INVALID_FORMAT[schema.format] : undefined;
|
|
266
|
+
if (invalidFormat !== undefined)
|
|
267
|
+
add(`is not a valid ${String(schema.format)}`, 'format', invalidFormat);
|
|
268
|
+
}
|
|
269
|
+
else if (type === 'integer' || type === 'number') {
|
|
270
|
+
add('is text instead of a number', 'type', 'not-a-number');
|
|
271
|
+
if (type === 'integer')
|
|
272
|
+
add('is not a whole number', 'type: integer', 1.5);
|
|
273
|
+
const bounds = boundsOf(schema);
|
|
274
|
+
if (bounds.min !== undefined)
|
|
275
|
+
add(`is below the minimum ${bounds.min}`, 'minimum', bounds.minExclusive ? bounds.min : bounds.min - 1);
|
|
276
|
+
if (bounds.max !== undefined)
|
|
277
|
+
add(`is above the maximum ${bounds.max}`, 'maximum', bounds.maxExclusive ? bounds.max : bounds.max + 1);
|
|
278
|
+
const multiple = num(schema.multipleOf);
|
|
279
|
+
if (multiple !== undefined && Number.isInteger(multiple) && multiple > 1)
|
|
280
|
+
add(`is not a multiple of ${multiple}`, 'multipleOf', multiple + 1);
|
|
281
|
+
}
|
|
282
|
+
else if (type === 'boolean') {
|
|
283
|
+
add('is text instead of a boolean', 'type', 'not-a-boolean');
|
|
284
|
+
}
|
|
285
|
+
else if (type === 'array') {
|
|
286
|
+
if (!forParameter)
|
|
287
|
+
add('is text instead of an array', 'type', 'not-an-array');
|
|
288
|
+
const minItems = num(schema.minItems);
|
|
289
|
+
if (minItems !== undefined && minItems > 0)
|
|
290
|
+
add(`has fewer than ${minItems} items`, 'minItems', (Array.isArray(baseline) ? baseline : []).slice(0, minItems - 1));
|
|
291
|
+
const maxItems = num(schema.maxItems);
|
|
292
|
+
if (maxItems !== undefined && maxItems >= 0 && maxItems < 1000) {
|
|
293
|
+
const item = Array.isArray(baseline) && baseline.length ? baseline[0] : 'item';
|
|
294
|
+
add(`has more than ${maxItems} items`, 'maxItems', Array.from({ length: maxItems + 1 }, () => clone(item)));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
else if (type === 'object' && !forParameter) {
|
|
298
|
+
add('is text instead of an object', 'type', 'not-an-object');
|
|
299
|
+
add('is an array instead of an object', 'type', []);
|
|
300
|
+
}
|
|
301
|
+
if (type !== undefined && !isNullable(schema) && !forParameter)
|
|
302
|
+
add('is null', 'type: null', null);
|
|
303
|
+
const allowed = list(schema.enum);
|
|
304
|
+
if (allowed.length) {
|
|
305
|
+
const outsider = ['not-in-enum', 'NOT_IN_ENUM', -999_999].find(candidate => !allowed.some(entry => sameJson(entry, candidate)));
|
|
306
|
+
if (outsider !== undefined)
|
|
307
|
+
add('is not one of the allowed values', 'enum', outsider);
|
|
308
|
+
}
|
|
309
|
+
return out;
|
|
310
|
+
}
|
|
311
|
+
function walk(doc, node, value, path, depth, out) {
|
|
312
|
+
// An ambiguous node (oneOf/anyOf) has no single set of rules, so nothing is claimed about it.
|
|
313
|
+
if (depth >= MAX_MUTATION_DEPTH || node.ambiguous)
|
|
314
|
+
return;
|
|
315
|
+
const { schema } = node;
|
|
316
|
+
if (isObject(value) && primaryType(schema) === 'object') {
|
|
317
|
+
const properties = isObject(schema.properties) ? schema.properties : {};
|
|
318
|
+
const required = new Set(list(schema.required).filter(isString));
|
|
319
|
+
if (schema.additionalProperties === false) {
|
|
320
|
+
out.push({ description: `${where(path)} has an unexpected extra property`, violates: `${where(path)}: additionalProperties`, apply: body => setAt(body, [...path, '__unexpected__'], 'x') });
|
|
321
|
+
}
|
|
322
|
+
for (const [name, rawProperty] of Object.entries(properties)) {
|
|
323
|
+
const property = resolveSchema(doc, rawProperty);
|
|
324
|
+
if (!property || property.schema.readOnly === true)
|
|
325
|
+
continue;
|
|
326
|
+
const propertyPath = [...path, name];
|
|
327
|
+
const label = where(propertyPath);
|
|
328
|
+
const present = Object.prototype.hasOwnProperty.call(value, name);
|
|
329
|
+
if (present && required.has(name))
|
|
330
|
+
out.push({ description: `${label} is missing`, violates: `${label}: required`, apply: body => removeAt(body, propertyPath) });
|
|
331
|
+
if (!property.ambiguous) {
|
|
332
|
+
for (const bad of badValues(property.schema, value[name], false)) {
|
|
333
|
+
out.push({ description: `${label} ${bad.description}`, violates: `${label}: ${bad.violates}`, apply: body => setAt(body, propertyPath, clone(bad.value)) });
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (present)
|
|
337
|
+
walk(doc, property, value[name], propertyPath, depth + 1, out);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
else if (Array.isArray(value) && value.length && primaryType(schema) === 'array') {
|
|
341
|
+
const items = resolveSchema(doc, schema.items);
|
|
342
|
+
if (!items)
|
|
343
|
+
return;
|
|
344
|
+
const itemPath = [...path, 0];
|
|
345
|
+
if (!items.ambiguous) {
|
|
346
|
+
for (const bad of badValues(items.schema, value[0], false)) {
|
|
347
|
+
out.push({ description: `${where(itemPath)} ${bad.description}`, violates: `${where(itemPath)}: ${bad.violates}`, apply: body => setAt(body, itemPath, clone(bad.value)) });
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
walk(doc, items, value[0], itemPath, depth + 1, out);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
function isFormScalar(value) { return typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)); }
|
|
354
|
+
/** A body a form or multipart request can carry: an object whose properties are text, numbers, booleans or lists of those. */
|
|
355
|
+
function isEncodable(value) {
|
|
356
|
+
return isObject(value) && Object.values(value).every(entry => isFormScalar(entry) || (Array.isArray(entry) && entry.every(isFormScalar)));
|
|
357
|
+
}
|
|
358
|
+
/** The fields of a form body as sent: a list repeats the name, and everything is text. */
|
|
359
|
+
function formEntries(value) {
|
|
360
|
+
if (!isObject(value))
|
|
361
|
+
return [];
|
|
362
|
+
return Object.entries(value).flatMap(([name, entry]) => (Array.isArray(entry) ? entry : [entry])
|
|
363
|
+
.map((item) => [name, isFormScalar(item) ? String(item) : JSON.stringify(item)]));
|
|
364
|
+
}
|
|
365
|
+
/** Multipart parts: a file field (name to content type) becomes a file with the text as its content, every other field a text part. */
|
|
366
|
+
function multipartParts(value, files) {
|
|
367
|
+
return formEntries(value).map(([name, text]) => {
|
|
368
|
+
const contentType = files.get(name);
|
|
369
|
+
return contentType === undefined ? { name, value: text } : { name, filename: 'sample.bin', data: text, contentType };
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* What breaks one rule of a form or multipart body. Every value is text on the wire, so this uses the same text-aware values as
|
|
374
|
+
* parameters: "a string for an integer" is not a violation (the text reads as a number), "text that is not a number" is.
|
|
375
|
+
* Properties that are objects have no plain encoding and are left out.
|
|
376
|
+
*/
|
|
377
|
+
function formMutations(doc, node, value, kind) {
|
|
378
|
+
const out = [];
|
|
379
|
+
if (node.ambiguous || !isObject(value) || primaryType(node.schema) !== 'object')
|
|
380
|
+
return out;
|
|
381
|
+
const noun = kind === 'form' ? 'form field' : 'multipart field';
|
|
382
|
+
const required = new Set(list(node.schema.required).filter(isString));
|
|
383
|
+
if (node.schema.additionalProperties === false) {
|
|
384
|
+
out.push({ description: `the body has an unexpected extra ${noun}`, violates: 'body: additionalProperties', apply: body => setAt(body, ['__unexpected__'], 'x') });
|
|
385
|
+
}
|
|
386
|
+
for (const [name, rawProperty] of Object.entries(isObject(node.schema.properties) ? node.schema.properties : {})) {
|
|
387
|
+
const property = resolveSchema(doc, rawProperty);
|
|
388
|
+
if (!property || property.schema.readOnly === true || primaryType(property.schema) === 'object')
|
|
389
|
+
continue;
|
|
390
|
+
const label = `${noun} "${name}"`;
|
|
391
|
+
const present = Object.prototype.hasOwnProperty.call(value, name);
|
|
392
|
+
if (present && required.has(name))
|
|
393
|
+
out.push({ description: `${label} is missing`, violates: `${label}: required`, apply: body => removeAt(body, [name]) });
|
|
394
|
+
if (property.ambiguous)
|
|
395
|
+
continue;
|
|
396
|
+
for (const bad of badValues(property.schema, value[name], true)) {
|
|
397
|
+
if (Array.isArray(bad.value) && bad.value.length === 0)
|
|
398
|
+
continue; // an empty list sends no entries at all: the same request as one without the field
|
|
399
|
+
out.push({ description: `${label} ${bad.description}`, violates: `${label}: ${bad.violates}`, apply: body => setAt(body, [name], clone(bad.value)) });
|
|
400
|
+
}
|
|
401
|
+
const items = primaryType(property.schema) === 'array' && Array.isArray(value[name]) && value[name].length ? resolveSchema(doc, property.schema.items) : undefined;
|
|
402
|
+
if (items && !items.ambiguous) {
|
|
403
|
+
for (const bad of badValues(items.schema, value[name][0], true)) {
|
|
404
|
+
out.push({ description: `${label} has an item that ${bad.description}`, violates: `${label}: item ${bad.violates}`, apply: body => setAt(body, [name, 0], clone(bad.value)) });
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return out;
|
|
409
|
+
}
|
|
410
|
+
// ---------------------------------------------------------------- fuzz material
|
|
411
|
+
const FUZZ_STRINGS = [
|
|
412
|
+
{ label: 'empty string', value: '', pathSafe: false },
|
|
413
|
+
{ label: 'whitespace only', value: ' ', pathSafe: true },
|
|
414
|
+
{ label: '10,000 characters', value: 'A'.repeat(10_000), pathSafe: false },
|
|
415
|
+
{ label: 'unicode: emoji, accents, CJK', value: '😀 é ñ 漢字', pathSafe: true },
|
|
416
|
+
{ label: 'right-to-left override', value: 'evil', pathSafe: true },
|
|
417
|
+
{ label: 'null byte', value: 'a\u0000b', pathSafe: true },
|
|
418
|
+
{ label: 'CR LF', value: 'a\r\nInjected: header', pathSafe: true },
|
|
419
|
+
{ label: 'SQL injection', value: '\' OR \'1\'=\'1', pathSafe: true },
|
|
420
|
+
{ label: 'SQL drop table', value: '\'; DROP TABLE users; --', pathSafe: true },
|
|
421
|
+
{ label: 'script tag', value: '<script>alert(1)</script>', pathSafe: true },
|
|
422
|
+
{ label: 'path traversal', value: '../../../etc/passwd', pathSafe: false },
|
|
423
|
+
{ label: 'template injection', value: '{{7*7}} ${7*7} #{7*7}', pathSafe: true },
|
|
424
|
+
{ label: 'format string', value: '%s%s%s%n', pathSafe: false },
|
|
425
|
+
{ label: 'NoSQL operator text', value: '{"$ne": null}', pathSafe: true }
|
|
426
|
+
];
|
|
427
|
+
const FUZZ_NUMBERS = [
|
|
428
|
+
{ label: 'zero', value: 0 },
|
|
429
|
+
{ label: 'negative one', value: -1 },
|
|
430
|
+
{ label: 'largest safe integer', value: Number.MAX_SAFE_INTEGER },
|
|
431
|
+
{ label: 'smallest safe integer', value: Number.MIN_SAFE_INTEGER },
|
|
432
|
+
{ label: 'very large number', value: 1e308 },
|
|
433
|
+
{ label: 'tiny fraction', value: 1e-308 },
|
|
434
|
+
{ label: 'fraction that is not exact', value: 0.1 + 0.2 }
|
|
435
|
+
];
|
|
436
|
+
function fuzzTargets(doc, node, value, path, depth, out) {
|
|
437
|
+
if (depth >= MAX_MUTATION_DEPTH || node.ambiguous || !isObject(value) || primaryType(node.schema) !== 'object')
|
|
438
|
+
return;
|
|
439
|
+
for (const [name, rawProperty] of Object.entries(isObject(node.schema.properties) ? node.schema.properties : {})) {
|
|
440
|
+
const property = resolveSchema(doc, rawProperty);
|
|
441
|
+
if (!property || property.schema.readOnly === true || property.ambiguous)
|
|
442
|
+
continue;
|
|
443
|
+
const type = primaryType(property.schema);
|
|
444
|
+
const propertyPath = [...path, name];
|
|
445
|
+
if (type === 'string')
|
|
446
|
+
out.push({ path: propertyPath, kind: 'string' });
|
|
447
|
+
else if (type === 'integer' || type === 'number')
|
|
448
|
+
out.push({ path: propertyPath, kind: 'number' });
|
|
449
|
+
else if (type === 'object' && Object.prototype.hasOwnProperty.call(value, name))
|
|
450
|
+
fuzzTargets(doc, property, value[name], propertyPath, depth + 1, out);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
// ---------------------------------------------------------------- operations and the generator
|
|
454
|
+
// ---------------------------------------------------------------- mass assignment and SSRF
|
|
455
|
+
/** Distinctive values: a server that returns one of them has stored or echoed what it should have ignored. */
|
|
456
|
+
const SENTINEL_NUMBER = 987_654_321;
|
|
457
|
+
const SENTINEL_FORMATS = {
|
|
458
|
+
uuid: '9d1f6c52-7a3e-4b8d-a1c4-5e2f0b7d3c91', 'date-time': '2001-02-03T04:05:06Z', date: '2001-02-03',
|
|
459
|
+
email: 'qe-injected@example.invalid', uri: 'https://qe-injected.example.invalid/', url: 'https://qe-injected.example.invalid/'
|
|
460
|
+
};
|
|
461
|
+
/** Names an API should never let a client set on itself, for specs that do not declare them. */
|
|
462
|
+
const PRIVILEGED_PROPERTIES = ['isAdmin', 'role', 'ownerId', 'userId', 'balance', 'verified'];
|
|
463
|
+
const PRIVILEGED_NUMBERS = new Set(['balance']);
|
|
464
|
+
const URL_FORMATS = new Set(['uri', 'url', 'uri-reference', 'iri', 'iri-reference']);
|
|
465
|
+
const URL_WORDS = new Set(['url', 'uri', 'link', 'callback', 'webhook', 'redirect', 'href', 'endpoint']);
|
|
466
|
+
/** Addresses a server must not be made to contact on a client's behalf. */
|
|
467
|
+
const INTERNAL_ADDRESSES = [
|
|
468
|
+
{ label: 'the cloud metadata service', url: 'http://169.254.169.254/latest/meta-data/' },
|
|
469
|
+
{ label: 'a loopback address', url: 'http://127.0.0.1:22/' },
|
|
470
|
+
{ label: 'localhost', url: 'http://localhost/admin' },
|
|
471
|
+
{ label: 'the IPv6 loopback address', url: 'http://[::1]/' },
|
|
472
|
+
{ label: 'a private network address', url: 'http://10.0.0.1/' },
|
|
473
|
+
{ label: 'a local file', url: 'file:///etc/passwd' }
|
|
474
|
+
];
|
|
475
|
+
function compactName(name) { return keyWords(name).join(''); }
|
|
476
|
+
/** A value of the right type to send for a read-only property, or undefined when none would stand out (booleans, enums, constants). */
|
|
477
|
+
function sentinelFor(name, schema) {
|
|
478
|
+
if ('const' in schema || list(schema.enum).length)
|
|
479
|
+
return undefined;
|
|
480
|
+
const type = primaryType(schema);
|
|
481
|
+
if (type === 'string') {
|
|
482
|
+
const format = isString(schema.format) ? schema.format : undefined;
|
|
483
|
+
const value = (format !== undefined ? SENTINEL_FORMATS[format] : undefined) ?? `qe-injected-${name}`;
|
|
484
|
+
const max = num(schema.maxLength);
|
|
485
|
+
return max !== undefined && value.length > max ? undefined : value;
|
|
486
|
+
}
|
|
487
|
+
if (type === 'integer' || type === 'number') {
|
|
488
|
+
const bounds = boundsOf(schema);
|
|
489
|
+
const multiple = num(schema.multipleOf);
|
|
490
|
+
if ((bounds.max !== undefined && SENTINEL_NUMBER > bounds.max) || (bounds.min !== undefined && SENTINEL_NUMBER < bounds.min))
|
|
491
|
+
return undefined;
|
|
492
|
+
return multiple !== undefined && multiple > 0 && SENTINEL_NUMBER % multiple !== 0 ? undefined : SENTINEL_NUMBER;
|
|
493
|
+
}
|
|
494
|
+
return undefined;
|
|
495
|
+
}
|
|
496
|
+
/** A string field that holds, or is named like it holds, an address the server may fetch or redirect to. */
|
|
497
|
+
function looksLikeUrl(name, schema) {
|
|
498
|
+
const format = isString(schema.format) ? schema.format : undefined;
|
|
499
|
+
return (format !== undefined && URL_FORMATS.has(format)) || keyWords(name).some(word => URL_WORDS.has(word));
|
|
500
|
+
}
|
|
501
|
+
/** The injected properties a response sends back with the value they were sent with, at any depth (a `data` envelope, a list of records). */
|
|
502
|
+
function returnedValues(body, injected, found = new Set(), depth = 0) {
|
|
503
|
+
if (depth > 8)
|
|
504
|
+
return found;
|
|
505
|
+
if (Array.isArray(body)) {
|
|
506
|
+
for (const item of body)
|
|
507
|
+
returnedValues(item, injected, found, depth + 1);
|
|
508
|
+
}
|
|
509
|
+
else if (isObject(body)) {
|
|
510
|
+
for (const [key, value] of Object.entries(body)) {
|
|
511
|
+
for (const property of injected) {
|
|
512
|
+
const same = (typeof value === 'string' || typeof value === 'number') && String(value) === String(property.value);
|
|
513
|
+
if (same && compactName(key) === compactName(property.name))
|
|
514
|
+
found.add(property.name);
|
|
515
|
+
}
|
|
516
|
+
if (isContainer(value))
|
|
517
|
+
returnedValues(value, injected, found, depth + 1);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
return found;
|
|
521
|
+
}
|
|
522
|
+
function resolveComponent(doc, raw, bucket) {
|
|
523
|
+
let current = raw;
|
|
524
|
+
for (let hops = 0; hops < 10; hops++) {
|
|
525
|
+
if (!isObject(current))
|
|
526
|
+
return undefined;
|
|
527
|
+
if (typeof current.$ref !== 'string')
|
|
528
|
+
return current;
|
|
529
|
+
const prefix = `#/components/${bucket}/`;
|
|
530
|
+
if (!current.$ref.startsWith(prefix))
|
|
531
|
+
return undefined;
|
|
532
|
+
current = doc.components?.[bucket]?.[unescapeToken(current.$ref.slice(prefix.length))];
|
|
533
|
+
}
|
|
534
|
+
return undefined;
|
|
535
|
+
}
|
|
536
|
+
function mediaTypeOf(value) { return value.split(';', 1)[0]?.trim().toLowerCase() ?? ''; }
|
|
537
|
+
/**
|
|
538
|
+
* Builds test cases from an OpenAPI document: a valid request per operation, requests that break the spec's rules one at a time
|
|
539
|
+
* (negative), and hostile or extreme values (fuzz). Every negative case names the rule it breaks, and can be confirmed against the
|
|
540
|
+
* spec with `OpenApiValidator.assertRequest(case.check)`. Cases for POST, PUT, PATCH and DELETE send writes: run them only
|
|
541
|
+
* against an environment that may be written to.
|
|
542
|
+
*/
|
|
543
|
+
export class OpenApiCases {
|
|
544
|
+
doc;
|
|
545
|
+
options;
|
|
546
|
+
operationsByKey = new Map();
|
|
547
|
+
constructor(doc, options = {}) {
|
|
548
|
+
this.doc = doc;
|
|
549
|
+
this.options = options;
|
|
550
|
+
if (typeof doc.openapi !== 'string' || !/^3\.[01]\./.test(doc.openapi))
|
|
551
|
+
throw new Error('Expected OpenAPI 3.0 or 3.1 document');
|
|
552
|
+
for (const [path, rawItem] of Object.entries(doc.paths)) {
|
|
553
|
+
if (!path.startsWith('/'))
|
|
554
|
+
continue; // x- extensions
|
|
555
|
+
if (!isObject(rawItem))
|
|
556
|
+
throw new Error(`Invalid OpenAPI path item ${path}`);
|
|
557
|
+
if (typeof rawItem.$ref === 'string')
|
|
558
|
+
throw new Error(`Path item references are not supported (${path})`);
|
|
559
|
+
for (const method of METHODS) {
|
|
560
|
+
const rawOperation = rawItem[method.toLowerCase()];
|
|
561
|
+
if (rawOperation === undefined)
|
|
562
|
+
continue;
|
|
563
|
+
if (!isObject(rawOperation))
|
|
564
|
+
throw new Error(`Invalid OpenAPI operation ${method} ${path}`);
|
|
565
|
+
this.operationsByKey.set(`${method} ${path}`, this.buildOperation(method, path, rawItem, rawOperation));
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
operations(filter = {}) {
|
|
570
|
+
return [...this.operationsByKey.values()].map(operation => operation.info).filter(info => (filter.methods === undefined || filter.methods.includes(info.method)) &&
|
|
571
|
+
(filter.tags === undefined || info.tags.some(tag => filter.tags?.includes(tag))));
|
|
572
|
+
}
|
|
573
|
+
/** One request that satisfies the spec. Expect it to be accepted. */
|
|
574
|
+
valid(reference) {
|
|
575
|
+
const operation = this.find(reference);
|
|
576
|
+
return this.makeCase(operation, 'valid', 1, 'a valid request', 'success', false, undefined, this.baseline(operation), true);
|
|
577
|
+
}
|
|
578
|
+
/** Requests that each break exactly one rule of the spec. Expect a 4xx for every one. */
|
|
579
|
+
negative(reference) {
|
|
580
|
+
const operation = this.find(reference);
|
|
581
|
+
const baseline = this.baseline(operation);
|
|
582
|
+
const cases = [];
|
|
583
|
+
const add = (description, violates, violatesSchema, draft) => {
|
|
584
|
+
cases.push(this.makeCase(operation, 'negative', cases.length + 1, description, 'rejected', violatesSchema, violates, draft, violatesSchema));
|
|
585
|
+
};
|
|
586
|
+
for (const parameter of operation.parameters) {
|
|
587
|
+
const present = parameter.location === 'path' ? baseline.pathParams[parameter.name] : parameter.location === 'query' ? baseline.query[parameter.name] : baseline.headers[parameter.name];
|
|
588
|
+
const label = `${parameter.location} parameter "${parameter.name}"`;
|
|
589
|
+
if (parameter.location !== 'path' && parameter.required && present !== undefined) {
|
|
590
|
+
const draft = clone(baseline);
|
|
591
|
+
if (parameter.location === 'query')
|
|
592
|
+
delete draft.query[parameter.name];
|
|
593
|
+
else
|
|
594
|
+
delete draft.headers[parameter.name];
|
|
595
|
+
add(`${label} is missing`, `${label}: required`, true, draft);
|
|
596
|
+
}
|
|
597
|
+
const resolved = resolveSchema(this.doc, parameter.schema);
|
|
598
|
+
if (!resolved || resolved.ambiguous)
|
|
599
|
+
continue;
|
|
600
|
+
for (const bad of badValues(resolved.schema, present, true)) {
|
|
601
|
+
if (parameter.location === 'path' && bad.value === '')
|
|
602
|
+
continue; // an empty path segment addresses a different route, not an invalid value
|
|
603
|
+
if (parameter.location === 'header' && typeof bad.value !== 'string' && typeof bad.value !== 'number')
|
|
604
|
+
continue;
|
|
605
|
+
const draft = clone(baseline);
|
|
606
|
+
if (parameter.location === 'path')
|
|
607
|
+
draft.pathParams[parameter.name] = bad.value;
|
|
608
|
+
else if (parameter.location === 'query')
|
|
609
|
+
draft.query[parameter.name] = bad.value;
|
|
610
|
+
else
|
|
611
|
+
draft.headers[parameter.name] = String(bad.value);
|
|
612
|
+
add(`${label} ${bad.description}`, `${label}: ${bad.violates}`, true, draft);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
if (operation.bodySchema !== undefined) {
|
|
616
|
+
const root = resolveSchema(this.doc, operation.bodySchema);
|
|
617
|
+
if (operation.bodyRequired && baseline.json !== undefined) {
|
|
618
|
+
const draft = clone(baseline);
|
|
619
|
+
delete draft.json;
|
|
620
|
+
add('the required body is missing', 'body: required', true, draft);
|
|
621
|
+
}
|
|
622
|
+
const bodyKind = operation.info.bodyKind;
|
|
623
|
+
if (root && baseline.json !== undefined) {
|
|
624
|
+
const mutations = [];
|
|
625
|
+
if (bodyKind === 'form' || bodyKind === 'multipart') {
|
|
626
|
+
mutations.push(...formMutations(this.doc, root, baseline.json, bodyKind));
|
|
627
|
+
}
|
|
628
|
+
else {
|
|
629
|
+
if (!root.ambiguous)
|
|
630
|
+
for (const bad of badValues(root.schema, baseline.json, false))
|
|
631
|
+
mutations.push({ description: `body ${bad.description}`, violates: `body: ${bad.violates}`, apply: () => clone(bad.value) });
|
|
632
|
+
walk(this.doc, root, baseline.json, [], 0, mutations);
|
|
633
|
+
}
|
|
634
|
+
for (const mutation of mutations) {
|
|
635
|
+
const draft = clone(baseline);
|
|
636
|
+
draft.json = mutation.apply(draft.json);
|
|
637
|
+
add(mutation.description, mutation.violates, true, draft);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
if (baseline.json !== undefined) {
|
|
641
|
+
const wrongType = (rawBody) => ({ ...clone(baseline), json: undefined, rawBody, contentType: 'text/plain' });
|
|
642
|
+
if (bodyKind === 'form') {
|
|
643
|
+
add('the body has an unsupported content type', 'content-type: text/plain', false, wrongType(encodeForm(formEntries(baseline.json))));
|
|
644
|
+
}
|
|
645
|
+
else if (bodyKind === 'multipart') {
|
|
646
|
+
add('the body has an unsupported content type', 'content-type: text/plain', false, wrongType(new TextDecoder().decode(encodeMultipart(multipartParts(baseline.json, operation.fileFields)).body)));
|
|
647
|
+
}
|
|
648
|
+
else {
|
|
649
|
+
add('the body is not valid JSON', 'body: malformed JSON', false, { ...clone(baseline), json: undefined, rawBody: '{"broken": ' });
|
|
650
|
+
add('the body has an unsupported content type', 'content-type: text/plain', false, wrongType(JSON.stringify(baseline.json)));
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
return cases;
|
|
655
|
+
}
|
|
656
|
+
/** 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. */
|
|
657
|
+
fuzz(reference) {
|
|
658
|
+
const operation = this.find(reference);
|
|
659
|
+
const baseline = this.baseline(operation);
|
|
660
|
+
const candidates = [];
|
|
661
|
+
const addString = (target, apply, pathParameter) => {
|
|
662
|
+
for (const fuzz of FUZZ_STRINGS) {
|
|
663
|
+
if (pathParameter && !fuzz.pathSafe)
|
|
664
|
+
continue;
|
|
665
|
+
const draft = clone(baseline);
|
|
666
|
+
apply(draft, fuzz.value);
|
|
667
|
+
candidates.push({ description: `${target} gets ${fuzz.label}`, violates: `${target}: ${fuzz.label}`, draft });
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
const addNumber = (target, apply) => {
|
|
671
|
+
for (const fuzz of FUZZ_NUMBERS) {
|
|
672
|
+
const draft = clone(baseline);
|
|
673
|
+
apply(draft, fuzz.value);
|
|
674
|
+
candidates.push({ description: `${target} gets ${fuzz.label}`, violates: `${target}: ${fuzz.label}`, draft });
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
for (const parameter of operation.parameters) {
|
|
678
|
+
if (parameter.location === 'header')
|
|
679
|
+
continue; // invalid header values are rejected by the HTTP stack before they reach the API
|
|
680
|
+
const type = primaryType(resolveSchema(this.doc, parameter.schema)?.schema ?? {});
|
|
681
|
+
const label = `${parameter.location} parameter "${parameter.name}"`;
|
|
682
|
+
const set = (draft, value) => {
|
|
683
|
+
if (parameter.location === 'path')
|
|
684
|
+
draft.pathParams[parameter.name] = value;
|
|
685
|
+
else
|
|
686
|
+
draft.query[parameter.name] = value;
|
|
687
|
+
};
|
|
688
|
+
if (type === 'string')
|
|
689
|
+
addString(label, set, parameter.location === 'path');
|
|
690
|
+
else if (type === 'integer' || type === 'number')
|
|
691
|
+
addNumber(label, set);
|
|
692
|
+
}
|
|
693
|
+
if (operation.bodySchema !== undefined && baseline.json !== undefined) {
|
|
694
|
+
const root = resolveSchema(this.doc, operation.bodySchema);
|
|
695
|
+
const targets = [];
|
|
696
|
+
if (root)
|
|
697
|
+
fuzzTargets(this.doc, root, baseline.json, [], 0, targets);
|
|
698
|
+
for (const target of targets) {
|
|
699
|
+
const label = where(target.path);
|
|
700
|
+
if (target.kind === 'string')
|
|
701
|
+
addString(label, (draft, value) => { draft.json = setAt(draft.json, target.path, value); }, false);
|
|
702
|
+
else
|
|
703
|
+
addNumber(label, (draft, value) => { draft.json = setAt(draft.json, target.path, value); });
|
|
704
|
+
}
|
|
705
|
+
if (operation.info.bodyKind === 'form' || operation.info.bodyKind === 'multipart') {
|
|
706
|
+
// Nesting and a __proto__ key are JSON ideas; the form equivalent is a field name that parsers expand into nested objects.
|
|
707
|
+
const polluted = clone(baseline);
|
|
708
|
+
polluted.json = { ...(isObject(baseline.json) ? baseline.json : {}), '__proto__[polluted]': 'true' };
|
|
709
|
+
candidates.push({ description: 'the body carries a __proto__[polluted] field', violates: 'body: prototype pollution', draft: polluted });
|
|
710
|
+
}
|
|
711
|
+
else {
|
|
712
|
+
const nested = clone(baseline);
|
|
713
|
+
nested.json = undefined;
|
|
714
|
+
nested.rawBody = `${'['.repeat(200)}${']'.repeat(200)}`;
|
|
715
|
+
candidates.push({ description: 'the body is nested 200 levels deep', violates: 'body: deep nesting', draft: nested });
|
|
716
|
+
if (isObject(baseline.json)) {
|
|
717
|
+
const inner = JSON.stringify(baseline.json);
|
|
718
|
+
const polluted = clone(baseline);
|
|
719
|
+
polluted.json = undefined;
|
|
720
|
+
polluted.rawBody = `{"__proto__":{"polluted":true}${inner === '{}' ? '' : ','}${inner.slice(1)}`;
|
|
721
|
+
candidates.push({ description: 'the body carries a __proto__ key', violates: 'body: prototype pollution', draft: polluted });
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
const limit = Math.max(0, Math.floor(this.options.maxFuzzCases ?? 60));
|
|
726
|
+
const chosen = this.choose(candidates.length, limit);
|
|
727
|
+
return chosen.map((index, position) => {
|
|
728
|
+
const candidate = candidates[index];
|
|
729
|
+
if (!candidate)
|
|
730
|
+
throw new Error('Internal error: fuzz candidate index out of range');
|
|
731
|
+
return this.makeCase(operation, 'fuzz', position + 1, candidate.description, 'survives', false, candidate.violates, candidate.draft, false);
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Authentication cases for a protected operation: no credentials, invalid credentials of each kind the spec declares (bearer, Basic,
|
|
736
|
+
* 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
|
|
737
|
+
* 403 (a 400 is also accepted for malformed credentials). An operation without a security requirement, or with optional
|
|
738
|
+
* authentication, has none. The requests are sent without the client's own credentials (`skipAuth`).
|
|
739
|
+
*/
|
|
740
|
+
security(reference) {
|
|
741
|
+
const operation = this.find(reference);
|
|
742
|
+
if (!operation.info.protected)
|
|
743
|
+
return [];
|
|
744
|
+
const baseline = this.baseline(operation);
|
|
745
|
+
const cases = [];
|
|
746
|
+
const add = (description, violates, accept, change) => {
|
|
747
|
+
const draft = clone(baseline);
|
|
748
|
+
draft.skipAuth = true;
|
|
749
|
+
for (const place of operation.apiKeyPlaces) {
|
|
750
|
+
// Start from a request that carries no credential at all, wherever the spec says one travels.
|
|
751
|
+
if (place.location === 'query')
|
|
752
|
+
delete draft.query[place.name];
|
|
753
|
+
else
|
|
754
|
+
for (const key of Object.keys(draft.headers))
|
|
755
|
+
if (key.toLowerCase() === (place.location === 'cookie' ? 'cookie' : place.name.toLowerCase()))
|
|
756
|
+
delete draft.headers[key];
|
|
757
|
+
}
|
|
758
|
+
change(draft);
|
|
759
|
+
cases.push(this.makeCase(operation, 'security', cases.length + 1, description, 'denied', false, violates, draft, false, accept));
|
|
760
|
+
};
|
|
761
|
+
add('no credentials are sent', 'credentials: none', [401, 403], () => undefined);
|
|
762
|
+
for (const credential of operation.credentials)
|
|
763
|
+
add(credential.description, credential.violates, credential.accept, credential.apply);
|
|
764
|
+
return cases;
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Mass-assignment cases for a POST, PUT or PATCH with a JSON object body: a client must not be able to set what the server owns.
|
|
768
|
+
* One case per read-only property the spec declares (sent with a distinctive value), plus one that adds privileged names the spec
|
|
769
|
+
* does not declare (`isAdmin`, `role`, ...) unless it forbids extra properties. Expect `assertCaseOutcome` to pass when the API
|
|
770
|
+
* rejects the request, or accepts it without returning the values that were sent; it fails when a value comes back. A response that
|
|
771
|
+
* merely mirrors the request body will be flagged. Booleans, enums and constants are not tried: no value would stand out.
|
|
772
|
+
*/
|
|
773
|
+
massAssignment(reference) {
|
|
774
|
+
const operation = this.find(reference);
|
|
775
|
+
const { method } = operation.info;
|
|
776
|
+
if ((method !== 'POST' && method !== 'PUT' && method !== 'PATCH') || operation.bodySchema === undefined)
|
|
777
|
+
return [];
|
|
778
|
+
const baseline = this.baseline(operation);
|
|
779
|
+
const body = baseline.json;
|
|
780
|
+
const root = resolveSchema(this.doc, operation.bodySchema);
|
|
781
|
+
if (!root || root.ambiguous || !isObject(body) || primaryType(root.schema) !== 'object')
|
|
782
|
+
return [];
|
|
783
|
+
const properties = isObject(root.schema.properties) ? root.schema.properties : {};
|
|
784
|
+
const cases = [];
|
|
785
|
+
const add = (description, violates, injected) => {
|
|
786
|
+
const draft = clone(baseline);
|
|
787
|
+
draft.json = { ...body, ...Object.fromEntries(injected.map(property => [property.name, property.value])) };
|
|
788
|
+
cases.push({ ...this.makeCase(operation, 'mass-assignment', cases.length + 1, description, 'not-applied', false, violates, draft, false), injected });
|
|
789
|
+
};
|
|
790
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
791
|
+
const resolved = resolveSchema(this.doc, property);
|
|
792
|
+
if (resolved?.schema.readOnly !== true)
|
|
793
|
+
continue;
|
|
794
|
+
const value = sentinelFor(name, resolved.schema);
|
|
795
|
+
if (value !== undefined)
|
|
796
|
+
add(`the read-only property "${name}" is sent`, `body.${name}: readOnly property sent`, [{ name, value }]);
|
|
797
|
+
}
|
|
798
|
+
if (root.schema.additionalProperties !== false) {
|
|
799
|
+
const declared = new Set(Object.keys(properties).map(compactName));
|
|
800
|
+
const extras = PRIVILEGED_PROPERTIES.filter(name => !declared.has(compactName(name)))
|
|
801
|
+
.map((name) => ({ name, value: PRIVILEGED_NUMBERS.has(name) ? SENTINEL_NUMBER : `qe-injected-${name}` }));
|
|
802
|
+
if (extras.length) {
|
|
803
|
+
const names = extras.map(property => property.name).join(', ');
|
|
804
|
+
add(`privileged properties the spec does not declare are sent (${names})`, `body: undeclared properties ${names}`, extras);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
return cases;
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Server-side request forgery cases: every string field that looks like an address the server may fetch or redirect to (a query
|
|
811
|
+
* parameter or top-level body property with a URI format, or named like url, uri, link, callback, webhook, redirect, href or
|
|
812
|
+
* endpoint) is sent, one at a time, the cloud metadata address, loopback and private addresses, and a local file. Expect a 4xx.
|
|
813
|
+
* An API that deliberately checks addresses only when it fetches them will fail these cases; skip them for such an API. If the API
|
|
814
|
+
* is vulnerable, the server really does contact these addresses, so run them only against an environment that may be probed.
|
|
815
|
+
*/
|
|
816
|
+
ssrf(reference) {
|
|
817
|
+
const operation = this.find(reference);
|
|
818
|
+
const baseline = this.baseline(operation);
|
|
819
|
+
const targets = [];
|
|
820
|
+
for (const parameter of operation.parameters) {
|
|
821
|
+
if (parameter.location !== 'query')
|
|
822
|
+
continue;
|
|
823
|
+
const resolved = resolveSchema(this.doc, parameter.schema);
|
|
824
|
+
if (resolved && !list(resolved.schema.enum).length && primaryType(resolved.schema) === 'string' && looksLikeUrl(parameter.name, resolved.schema))
|
|
825
|
+
targets.push({ name: parameter.name, location: 'query' });
|
|
826
|
+
}
|
|
827
|
+
const body = baseline.json;
|
|
828
|
+
const root = operation.bodySchema === undefined ? undefined : resolveSchema(this.doc, operation.bodySchema);
|
|
829
|
+
if (root && !root.ambiguous && isObject(body) && primaryType(root.schema) === 'object' && isObject(root.schema.properties)) {
|
|
830
|
+
for (const [name, property] of Object.entries(root.schema.properties)) {
|
|
831
|
+
const resolved = resolveSchema(this.doc, property);
|
|
832
|
+
if (resolved && resolved.schema.readOnly !== true && !list(resolved.schema.enum).length && primaryType(resolved.schema) === 'string' && looksLikeUrl(name, resolved.schema))
|
|
833
|
+
targets.push({ name, location: 'body' });
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
const cases = [];
|
|
837
|
+
for (const target of targets) {
|
|
838
|
+
const field = target.location === 'query' ? `query parameter "${target.name}"` : `body.${target.name}`;
|
|
839
|
+
for (const address of INTERNAL_ADDRESSES) {
|
|
840
|
+
const draft = clone(baseline);
|
|
841
|
+
if (target.location === 'query')
|
|
842
|
+
draft.query[target.name] = address.url;
|
|
843
|
+
else
|
|
844
|
+
draft.json = { ...(isObject(body) ? body : {}), [target.name]: address.url };
|
|
845
|
+
cases.push(this.makeCase(operation, 'ssrf', cases.length + 1, `${field} is ${address.label} (${address.url})`, 'rejected', false, `${field}: internal address ${address.url}`, draft, false));
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
return cases;
|
|
849
|
+
}
|
|
850
|
+
// -------------------------------------------------------------- internals
|
|
851
|
+
buildOperation(method, path, item, operation) {
|
|
852
|
+
const declared = new Map(); // an operation parameter overrides a path-level one of the same name
|
|
853
|
+
const clientHeaders = new Set();
|
|
854
|
+
for (const raw of [...list(item.parameters), ...list(operation.parameters)]) {
|
|
855
|
+
const parameter = resolveComponent(this.doc, raw, 'parameters');
|
|
856
|
+
if (!parameter || !isString(parameter.name))
|
|
857
|
+
continue;
|
|
858
|
+
const location = parameter.in;
|
|
859
|
+
if (location !== 'path' && location !== 'query' && location !== 'header')
|
|
860
|
+
continue; // cookies are not generated
|
|
861
|
+
if (location === 'header' && RESERVED_HEADERS.has(parameter.name.toLowerCase())) {
|
|
862
|
+
if (parameter.required === true)
|
|
863
|
+
clientHeaders.add(parameter.name);
|
|
864
|
+
continue;
|
|
865
|
+
}
|
|
866
|
+
declared.set(`${location}:${parameter.name}`, { name: parameter.name, location, required: parameter.required === true || location === 'path', schema: parameter.schema });
|
|
867
|
+
}
|
|
868
|
+
const body = operation.requestBody === undefined ? undefined : resolveComponent(this.doc, operation.requestBody, 'requestBodies');
|
|
869
|
+
const content = body && isObject(body.content) ? body.content : {};
|
|
870
|
+
const jsonType = Object.keys(content).find(type => mediaTypeOf(type) === 'application/json' || mediaTypeOf(type).endsWith('+json'));
|
|
871
|
+
const formType = Object.keys(content).find(type => mediaTypeOf(type) === 'application/x-www-form-urlencoded');
|
|
872
|
+
const multipartType = Object.keys(content).find(type => mediaTypeOf(type) === 'multipart/form-data');
|
|
873
|
+
const bodyType = jsonType ?? formType ?? multipartType; // one kind of body is generated: JSON first, then form, then multipart
|
|
874
|
+
const bodyKind = bodyType === undefined ? undefined : bodyType === jsonType ? 'json' : bodyType === formType ? 'form' : 'multipart';
|
|
875
|
+
const media = bodyType === undefined ? undefined : content[bodyType];
|
|
876
|
+
const files = new Map(); // multipart file fields and the content type their part gets
|
|
877
|
+
if (bodyKind === 'multipart' && isObject(media)) {
|
|
878
|
+
const root = resolveSchema(this.doc, media.schema);
|
|
879
|
+
const encoding = isObject(media.encoding) ? media.encoding : {};
|
|
880
|
+
for (const [name, rawProperty] of Object.entries(root && isObject(root.schema.properties) ? root.schema.properties : {})) {
|
|
881
|
+
const property = resolveSchema(this.doc, rawProperty);
|
|
882
|
+
if (!property || primaryType(property.schema) !== 'string' || (property.schema.format !== 'binary' && !isString(property.schema.contentMediaType)))
|
|
883
|
+
continue;
|
|
884
|
+
const declaredType = isObject(encoding[name]) && isString(encoding[name].contentType) ? encoding[name].contentType.split(',')[0]?.trim() : undefined;
|
|
885
|
+
files.set(name, declaredType || (isString(property.schema.contentMediaType) ? property.schema.contentMediaType : 'application/octet-stream'));
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
const requirements = list(operation.security !== undefined ? operation.security : this.doc.security).filter(isObject);
|
|
889
|
+
const isProtected = requirements.length > 0 && !requirements.some(requirement => Object.keys(requirement).length === 0); // an empty requirement means authentication is optional
|
|
890
|
+
const { credentials, places } = isProtected ? this.credentialsFor(requirements) : { credentials: [], places: [] };
|
|
891
|
+
return {
|
|
892
|
+
info: {
|
|
893
|
+
method, path, operationId: isString(operation.operationId) ? operation.operationId : undefined,
|
|
894
|
+
tags: list(operation.tags).filter(isString), jsonBody: jsonType !== undefined, bodyKind, protected: isProtected,
|
|
895
|
+
unsupportedBody: Object.keys(content).filter(type => type !== bodyType)
|
|
896
|
+
},
|
|
897
|
+
parameters: [...declared.values()],
|
|
898
|
+
clientHeaders: [...clientHeaders],
|
|
899
|
+
bodySchema: isObject(media) ? media.schema : undefined,
|
|
900
|
+
fileFields: files,
|
|
901
|
+
bodyRequired: body?.required === true,
|
|
902
|
+
credentials,
|
|
903
|
+
apiKeyPlaces: places
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
/** The wrong credentials worth trying for the schemes the requirements name. */
|
|
907
|
+
credentialsFor(requirements) {
|
|
908
|
+
const schemes = new Map();
|
|
909
|
+
for (const requirement of requirements) {
|
|
910
|
+
for (const name of Object.keys(requirement)) {
|
|
911
|
+
const scheme = this.doc.components?.securitySchemes?.[name];
|
|
912
|
+
if (isObject(scheme))
|
|
913
|
+
schemes.set(name, scheme);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
const credentials = [];
|
|
917
|
+
const places = [];
|
|
918
|
+
let bearer = false;
|
|
919
|
+
let basic = false;
|
|
920
|
+
for (const scheme of schemes.values()) {
|
|
921
|
+
const httpScheme = isString(scheme.scheme) ? scheme.scheme.toLowerCase() : '';
|
|
922
|
+
const where = scheme.in;
|
|
923
|
+
if ((scheme.type === 'http' && httpScheme === 'bearer') || scheme.type === 'oauth2' || scheme.type === 'openIdConnect')
|
|
924
|
+
bearer = true;
|
|
925
|
+
else if (scheme.type === 'http' && httpScheme === 'basic')
|
|
926
|
+
basic = true;
|
|
927
|
+
else if (scheme.type === 'apiKey' && isString(scheme.name) && (where === 'header' || where === 'query' || where === 'cookie')) {
|
|
928
|
+
const place = { location: where, name: scheme.name };
|
|
929
|
+
places.push(place);
|
|
930
|
+
credentials.push({
|
|
931
|
+
description: `an invalid API key is sent in the ${where} "${place.name}"`, violates: `credentials: invalid API key (${where})`, accept: [401, 403],
|
|
932
|
+
apply: draft => {
|
|
933
|
+
if (place.location === 'query')
|
|
934
|
+
draft.query[place.name] = 'invalid-api-key';
|
|
935
|
+
else if (place.location === 'cookie')
|
|
936
|
+
draft.headers.Cookie = `${place.name}=invalid-api-key`;
|
|
937
|
+
else
|
|
938
|
+
draft.headers[place.name] = 'invalid-api-key';
|
|
939
|
+
}
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
if (bearer) {
|
|
944
|
+
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'; } });
|
|
945
|
+
}
|
|
946
|
+
if (basic)
|
|
947
|
+
credentials.push({ description: 'invalid Basic credentials are sent', violates: 'credentials: invalid Basic credentials', accept: [401, 403], apply: draft => { draft.headers.Authorization = 'Basic aW52YWxpZDppbnZhbGlk'; } });
|
|
948
|
+
if (bearer && !basic) {
|
|
949
|
+
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'; } });
|
|
950
|
+
}
|
|
951
|
+
return { credentials, places };
|
|
952
|
+
}
|
|
953
|
+
find(reference) {
|
|
954
|
+
const operation = this.operationsByKey.get(`${reference.method} ${reference.path}`);
|
|
955
|
+
if (!operation)
|
|
956
|
+
throw new Error(`Operation not found in the OpenAPI document: ${reference.method} ${reference.path}`);
|
|
957
|
+
return operation;
|
|
958
|
+
}
|
|
959
|
+
/** A request that satisfies the spec: required parameters, an example or sampled body, and any known-good values the caller supplied. */
|
|
960
|
+
baseline(operation) {
|
|
961
|
+
const override = this.options.baselines?.[`${operation.info.method} ${operation.info.path}`];
|
|
962
|
+
const draft = { pathParams: { ...override?.pathParams }, query: { ...override?.query }, headers: { ...override?.headers } };
|
|
963
|
+
for (const parameter of operation.parameters) {
|
|
964
|
+
const supplied = parameter.location === 'path' ? draft.pathParams[parameter.name] : parameter.location === 'query' ? draft.query[parameter.name] : draft.headers[parameter.name];
|
|
965
|
+
if (supplied !== undefined)
|
|
966
|
+
continue;
|
|
967
|
+
const resolved = resolveSchema(this.doc, parameter.schema);
|
|
968
|
+
const hinted = resolved !== undefined && (resolved.schema.example !== undefined || resolved.schema.default !== undefined);
|
|
969
|
+
if (!parameter.required && !hinted)
|
|
970
|
+
continue;
|
|
971
|
+
const value = sample(this.doc, parameter.schema);
|
|
972
|
+
if (value === undefined)
|
|
973
|
+
continue;
|
|
974
|
+
if (parameter.location === 'path')
|
|
975
|
+
draft.pathParams[parameter.name] = value;
|
|
976
|
+
else if (parameter.location === 'query')
|
|
977
|
+
draft.query[parameter.name] = value;
|
|
978
|
+
else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
|
|
979
|
+
draft.headers[parameter.name] = String(value);
|
|
980
|
+
}
|
|
981
|
+
if (operation.bodySchema !== undefined) {
|
|
982
|
+
const json = override?.json !== undefined ? clone(override.json) : sample(this.doc, operation.bodySchema);
|
|
983
|
+
// A form or multipart body can only carry text, numbers, booleans and lists of those: otherwise no body cases are built.
|
|
984
|
+
if (json !== undefined && (operation.info.bodyKind === 'json' || isEncodable(json)))
|
|
985
|
+
draft.json = json;
|
|
986
|
+
}
|
|
987
|
+
return draft;
|
|
988
|
+
}
|
|
989
|
+
makeCase(operation, kind, number, description, expect, violatesSchema, violates, draft, withCheck, accept) {
|
|
990
|
+
const { method, path } = operation.info;
|
|
991
|
+
const request = { method, path: path.replace(/\{([^}]+)\}/g, (_match, name) => encodeURIComponent(String(draft.pathParams[name] ?? ''))) };
|
|
992
|
+
if (Object.keys(draft.query).length)
|
|
993
|
+
request.query = draft.query;
|
|
994
|
+
const headers = { ...draft.headers };
|
|
995
|
+
if (draft.rawBody !== undefined) {
|
|
996
|
+
request.rawBody = draft.rawBody;
|
|
997
|
+
headers['Content-Type'] = draft.contentType ?? 'application/json';
|
|
998
|
+
}
|
|
999
|
+
else if (draft.json !== undefined) {
|
|
1000
|
+
if (operation.info.bodyKind === 'form')
|
|
1001
|
+
request.form = formEntries(draft.json);
|
|
1002
|
+
else if (operation.info.bodyKind === 'multipart')
|
|
1003
|
+
request.multipart = multipartParts(draft.json, operation.fileFields);
|
|
1004
|
+
else
|
|
1005
|
+
request.json = draft.json;
|
|
1006
|
+
}
|
|
1007
|
+
if (Object.keys(headers).length)
|
|
1008
|
+
request.headers = headers;
|
|
1009
|
+
if (draft.skipAuth)
|
|
1010
|
+
request.skipAuth = true;
|
|
1011
|
+
const id = `${method} ${path} ${kind} #${number}`;
|
|
1012
|
+
return {
|
|
1013
|
+
id, name: `${method} ${path}: ${description}`, kind, method, path, description, expect, violatesSchema, violates, request, accept,
|
|
1014
|
+
check: withCheck && (operation.info.bodyKind === 'json' || operation.info.bodyKind === undefined) ? { 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
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
/** Picks `limit` of `count` candidates reproducibly (seeded shuffle), keeping their original order. */
|
|
1018
|
+
choose(count, limit) {
|
|
1019
|
+
const indexes = Array.from({ length: count }, (_, index) => index);
|
|
1020
|
+
if (count <= limit)
|
|
1021
|
+
return indexes;
|
|
1022
|
+
const random = mulberry32(this.options.seed ?? 1);
|
|
1023
|
+
for (let i = indexes.length - 1; i > 0; i--) {
|
|
1024
|
+
const j = Math.floor(random() * (i + 1));
|
|
1025
|
+
[indexes[i], indexes[j]] = [indexes[j], indexes[i]];
|
|
1026
|
+
}
|
|
1027
|
+
return indexes.slice(0, limit).sort((a, b) => a - b);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Judges a response to a generated case. The message names the case and the rule it broke, and never includes the response body.
|
|
1032
|
+
* 'success': 2xx. 'rejected': 4xx (accepting invalid input, or failing with a 5xx, is a defect). 'survives': anything below 500.
|
|
1033
|
+
* 'denied': a refusal of the credentials. 'not-applied': a 4xx, or a 2xx whose body does not return the values that were sent
|
|
1034
|
+
* (this one needs the whole response, because it reads the body; the message names the properties, never their values).
|
|
1035
|
+
*/
|
|
1036
|
+
export function assertCaseOutcome(response, testCase) {
|
|
1037
|
+
const { status } = response;
|
|
1038
|
+
const label = `${testCase.method} ${testCase.path}: ${testCase.description}`;
|
|
1039
|
+
const broke = testCase.violates === undefined ? '' : ` (${testCase.violates})`;
|
|
1040
|
+
if (testCase.expect === 'success') {
|
|
1041
|
+
assert.ok(status >= 200 && status < 300, `${label}: the valid request was refused with HTTP ${status}`);
|
|
1042
|
+
}
|
|
1043
|
+
else if (testCase.expect === 'rejected') {
|
|
1044
|
+
assert.ok(status < 500, `${label}${broke}: the server failed with HTTP ${status} instead of rejecting the input`);
|
|
1045
|
+
assert.ok(status >= 400, `${label}${broke}: invalid input was accepted with HTTP ${status}`);
|
|
1046
|
+
}
|
|
1047
|
+
else if (testCase.expect === 'denied') {
|
|
1048
|
+
const accepted = testCase.accept ?? [401, 403];
|
|
1049
|
+
assert.ok(status < 500, `${label}${broke}: the server failed with HTTP ${status} instead of refusing the request`);
|
|
1050
|
+
assert.ok(status < 200 || status >= 300, `${label}${broke}: access was granted with HTTP ${status} without valid credentials`);
|
|
1051
|
+
assert.ok(accepted.includes(status), `${label}${broke}: refused with HTTP ${status}, expected ${accepted.join(' or ')}`);
|
|
1052
|
+
}
|
|
1053
|
+
else if (testCase.expect === 'not-applied') {
|
|
1054
|
+
assert.ok(status < 500, `${label}${broke}: the server failed with HTTP ${status} on the added properties`);
|
|
1055
|
+
if (status >= 200 && status < 300) {
|
|
1056
|
+
assert.ok('body' in response, `${label}: this case is judged on the response body: pass the whole response, not only its status`);
|
|
1057
|
+
const returned = [...returnedValues(response.body, testCase.injected ?? [])];
|
|
1058
|
+
const plural = returned.length > 1;
|
|
1059
|
+
assert.ok(!returned.length, `${label}${broke}: the server accepted the propert${plural ? 'ies' : 'y'} ${returned.map(name => `"${name}"`).join(', ')} and returned the value${plural ? 's' : ''} that ${plural ? 'were' : 'was'} sent`);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
else {
|
|
1063
|
+
assert.ok(status < 500, `${label}${broke}: the server failed with HTTP ${status} on hostile input`);
|
|
1064
|
+
}
|
|
1065
|
+
}
|