@nikhil-qeas/api-core 0.7.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +82 -7
  3. package/bin/qe-api.js +1 -0
  4. package/dist/http/api-client.d.ts +15 -0
  5. package/dist/http/api-client.js +41 -4
  6. package/dist/http/trace.d.ts +26 -0
  7. package/dist/http/trace.js +43 -0
  8. package/dist/http/types.d.ts +6 -0
  9. package/dist/index.d.ts +11 -4
  10. package/dist/index.js +5 -2
  11. package/dist/integrations/mocha.d.ts +32 -0
  12. package/dist/integrations/mocha.js +81 -0
  13. package/dist/reporting/html-report.d.ts +23 -0
  14. package/dist/reporting/html-report.js +118 -0
  15. package/dist/reporting/junit.d.ts +11 -2
  16. package/dist/reporting/junit.js +9 -3
  17. package/dist/reporting/redaction.d.ts +6 -0
  18. package/dist/reporting/redaction.js +10 -0
  19. package/dist/testing/load.d.ts +85 -0
  20. package/dist/testing/load.js +134 -0
  21. package/dist/testing/spec-cases.d.ts +46 -8
  22. package/dist/testing/spec-cases.js +292 -22
  23. package/package.json +1 -1
  24. package/templates/project/README.md +39 -6
  25. package/templates/project/__dot__env.example +4 -0
  26. package/templates/project/__dot__gitlab-ci.yml +1 -0
  27. package/templates/project/openapi/openapi.json +233 -0
  28. package/templates/project/src/clients/api.ts +4 -2
  29. package/templates/project/src/environment.ts +8 -0
  30. package/templates/project/src/observability.ts +15 -1
  31. package/templates/project/tests/performance/health.spec.ts +22 -0
  32. package/templates/project/tests/security/authentication.spec.ts +3 -1
  33. package/templates/project/tests/security/spec-cases.spec.ts +40 -3
  34. package/templates/project/tests/setup/hooks.ts +32 -5
  35. package/templates/project/tests/smoke/tracing.spec.ts +48 -0
  36. package/templates/project/tests/support/mock-api.ts +114 -5
@@ -1,4 +1,7 @@
1
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';
2
5
  const METHODS = ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH'];
3
6
  const SCHEMA_PREFIX = '#/components/schemas/';
4
7
  const MAX_SAMPLE_DEPTH = 6;
@@ -347,6 +350,63 @@ function walk(doc, node, value, path, depth, out) {
347
350
  walk(doc, items, value[0], itemPath, depth + 1, out);
348
351
  }
349
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
+ }
350
410
  // ---------------------------------------------------------------- fuzz material
351
411
  const FUZZ_STRINGS = [
352
412
  { label: 'empty string', value: '', pathSafe: false },
@@ -390,6 +450,75 @@ function fuzzTargets(doc, node, value, path, depth, out) {
390
450
  fuzzTargets(doc, property, value[name], propertyPath, depth + 1, out);
391
451
  }
392
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
+ }
393
522
  function resolveComponent(doc, raw, bucket) {
394
523
  let current = raw;
395
524
  for (let hops = 0; hops < 10; hops++) {
@@ -490,12 +619,18 @@ export class OpenApiCases {
490
619
  delete draft.json;
491
620
  add('the required body is missing', 'body: required', true, draft);
492
621
  }
622
+ const bodyKind = operation.info.bodyKind;
493
623
  if (root && baseline.json !== undefined) {
494
624
  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);
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
+ }
499
634
  for (const mutation of mutations) {
500
635
  const draft = clone(baseline);
501
636
  draft.json = mutation.apply(draft.json);
@@ -503,8 +638,17 @@ export class OpenApiCases {
503
638
  }
504
639
  }
505
640
  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' });
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
+ }
508
652
  }
509
653
  }
510
654
  return cases;
@@ -558,16 +702,24 @@ export class OpenApiCases {
558
702
  else
559
703
  addNumber(label, (draft, value) => { draft.json = setAt(draft.json, target.path, value); });
560
704
  }
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);
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.
567
707
  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 });
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
+ }
571
723
  }
572
724
  }
573
725
  const limit = Math.max(0, Math.floor(this.options.maxFuzzCases ?? 60));
@@ -611,6 +763,90 @@ export class OpenApiCases {
611
763
  add(credential.description, credential.violates, credential.accept, credential.apply);
612
764
  return cases;
613
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
+ }
614
850
  // -------------------------------------------------------------- internals
615
851
  buildOperation(method, path, item, operation) {
616
852
  const declared = new Map(); // an operation parameter overrides a path-level one of the same name
@@ -632,19 +868,36 @@ export class OpenApiCases {
632
868
  const body = operation.requestBody === undefined ? undefined : resolveComponent(this.doc, operation.requestBody, 'requestBodies');
633
869
  const content = body && isObject(body.content) ? body.content : {};
634
870
  const jsonType = Object.keys(content).find(type => mediaTypeOf(type) === 'application/json' || mediaTypeOf(type).endsWith('+json'));
635
- const jsonMedia = jsonType === undefined ? undefined : content[jsonType];
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
+ }
636
888
  const requirements = list(operation.security !== undefined ? operation.security : this.doc.security).filter(isObject);
637
889
  const isProtected = requirements.length > 0 && !requirements.some(requirement => Object.keys(requirement).length === 0); // an empty requirement means authentication is optional
638
890
  const { credentials, places } = isProtected ? this.credentialsFor(requirements) : { credentials: [], places: [] };
639
891
  return {
640
892
  info: {
641
893
  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)
894
+ tags: list(operation.tags).filter(isString), jsonBody: jsonType !== undefined, bodyKind, protected: isProtected,
895
+ unsupportedBody: Object.keys(content).filter(type => type !== bodyType)
644
896
  },
645
897
  parameters: [...declared.values()],
646
898
  clientHeaders: [...clientHeaders],
647
- bodySchema: isObject(jsonMedia) ? jsonMedia.schema : undefined,
899
+ bodySchema: isObject(media) ? media.schema : undefined,
900
+ fileFields: files,
648
901
  bodyRequired: body?.required === true,
649
902
  credentials,
650
903
  apiKeyPlaces: places
@@ -727,7 +980,8 @@ export class OpenApiCases {
727
980
  }
728
981
  if (operation.bodySchema !== undefined) {
729
982
  const json = override?.json !== undefined ? clone(override.json) : sample(this.doc, operation.bodySchema);
730
- if (json !== undefined)
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)))
731
985
  draft.json = json;
732
986
  }
733
987
  return draft;
@@ -743,7 +997,12 @@ export class OpenApiCases {
743
997
  headers['Content-Type'] = draft.contentType ?? 'application/json';
744
998
  }
745
999
  else if (draft.json !== undefined) {
746
- request.json = draft.json;
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;
747
1006
  }
748
1007
  if (Object.keys(headers).length)
749
1008
  request.headers = headers;
@@ -752,7 +1011,7 @@ export class OpenApiCases {
752
1011
  const id = `${method} ${path} ${kind} #${number}`;
753
1012
  return {
754
1013
  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
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
756
1015
  };
757
1016
  }
758
1017
  /** Picks `limit` of `count` candidates reproducibly (seeded shuffle), keeping their original order. */
@@ -771,6 +1030,8 @@ export class OpenApiCases {
771
1030
  /**
772
1031
  * Judges a response to a generated case. The message names the case and the rule it broke, and never includes the response body.
773
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).
774
1035
  */
775
1036
  export function assertCaseOutcome(response, testCase) {
776
1037
  const { status } = response;
@@ -789,6 +1050,15 @@ export function assertCaseOutcome(response, testCase) {
789
1050
  assert.ok(status < 200 || status >= 300, `${label}${broke}: access was granted with HTTP ${status} without valid credentials`);
790
1051
  assert.ok(accepted.includes(status), `${label}${broke}: refused with HTTP ${status}, expected ${accepted.join(' or ')}`);
791
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
+ }
792
1062
  else {
793
1063
  assert.ok(status < 500, `${label}${broke}: the server failed with HTTP ${status} on hostile input`);
794
1064
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nikhil-qeas/api-core",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Reusable TypeScript API automation core with HTTP, auth, OpenAPI adapter, test isolation, reporting and CI",
5
5
  "private": false,
6
6
  "type": "module",
@@ -17,11 +17,11 @@ The sample tests start a local mock API (`tests/support/mock-api.ts`) and need n
17
17
  |---|---|
18
18
  | `openapi/openapi.json` | The API's OpenAPI document. **Replace it with your API's spec**: contract checks and coverage both read it. |
19
19
  | `src/clients/api.ts` | `createApiClient()`: read-only unless writes are approved, retries with backoff and `Retry-After`, OAuth2 when `OAUTH_*` is set, metrics and coverage hooks. |
20
- | `src/environment.ts` | Reads `API_BASE_URL`, the optional `OAUTH_*` settings, and the write-protection policy (`QE_ENV`, `QE_ALLOW_MUTATIONS`, `QE_APPROVAL`). |
20
+ | `src/environment.ts` | Reads `API_BASE_URL`, the optional `OAUTH_*` settings, the write-protection policy (`QE_ENV`, `QE_ALLOW_MUTATIONS`, `QE_APPROVAL`) and `QE_TRACE`. |
21
21
  | `src/openapi.ts` | Loads the spec and builds the Ajv-backed contract validator. |
22
- | `src/observability.ts` | Run-wide metrics and OpenAPI coverage collectors. |
23
- | `tests/smoke`, `contract`, `security`, `negative` | Working samples. Any `tests/**/*.spec.ts` is picked up, so add folders such as `tests/regression` or `tests/negative` when you need them. |
24
- | `tests/setup/hooks.ts` | After the run: writes `reports/coverage/api.md` and `api.json` and can enforce a minimum. |
22
+ | `src/observability.ts` | Run-wide metrics and OpenAPI coverage collectors, and the trace id of the running test. |
23
+ | `tests/smoke`, `contract`, `security`, `negative`, `performance` | Working samples. Any `tests/**/*.spec.ts` is picked up, so add folders such as `tests/regression` or `tests/negative` when you need them. |
24
+ | `tests/setup/hooks.ts` | Mocha root hooks: a trace per test, each test's outcome for the HTML report, and after the run `reports/html/index.html`, `reports/coverage/api.md` and `api.json` (and a minimum, if you set one). |
25
25
  | `tests/support/mock-api.ts` | The local mock API and token endpoint the samples use. Delete it once you test a real environment. |
26
26
  | `tests/support/approved-writes.ts`, `identities.ts` | Helpers for the generated suites: run a suite with writes approved for the mock, and send requests as one test identity (or as nobody). |
27
27
  | `.mocharc.json` | Mocha settings: TypeScript specs under `tests/`, the setup hooks, a 30 second timeout. |
@@ -34,11 +34,27 @@ The sample tests start a local mock API (`tests/support/mock-api.ts`) and need n
34
34
  | Command | What it does |
35
35
  |---|---|
36
36
  | `npm test` | Every test. |
37
- | `npm run test:smoke` / `test:contract` / `test:security` / `test:negative` / `test:fuzz` | Tests whose title contains `@smoke` / `@contract` / `@security` / `@negative` / `@fuzz`. Tag your own `describe` titles the same way. |
37
+ | `npm run test:smoke` / `test:contract` / `test:security` / `test:negative` / `test:fuzz` / `test:performance` | Tests whose title contains `@smoke` / `@contract` / `@security` / `@negative` / `@fuzz` / `@performance`. Tag your own `describe` titles the same way. |
38
38
  | `npm run test:ci` | Everything, with JUnit XML in `reports/junit/results.xml` for the pipeline. |
39
39
  | `npm run lint` | ESLint with type-aware rules: an unawaited request is a check that silently never runs. |
40
40
  | `npm run audit:security` | `npm audit` for high-severity advisories. |
41
41
 
42
+ ## Reports
43
+
44
+ Every run writes these (`reports/` is created by the run and is git-ignored; the pipeline keeps it as a job artifact):
45
+
46
+ | File | What it is |
47
+ |---|---|
48
+ | `reports/html/index.html` | One page to open in a browser: the verdict, failures first (with the message, and the trace id when `QE_TRACE=true`), tests that only passed after retries, the slowest tests, every test by suite, and the API coverage and request figures. It is self-contained: no scripts, nothing loaded from anywhere. |
49
+ | `reports/junit/results.xml` | `npm run test:ci` only: JUnit XML for the pipeline's test report. |
50
+ | `reports/coverage/api.md`, `api.json` | Which operations and documented responses of the spec the run exercised. |
51
+
52
+ **Retries and flaky tests.** `npm run test:ci -- --retries 2` runs a failing test again, up to twice (Mocha reads `--retries` from its configuration; setting it from a hook does nothing). A test that fails and then passes is not hidden: the HTML report lists it under "Passed only after retries" with the number of retries it needed. That is a flaky test to fix, not a pass to trust.
53
+
54
+ **A failed hook is not a test.** If a `before` or `after` hook fails, the tests it guards never run and have no entry, so the report names the failed hooks and says FAILED, whatever the listed tests did. Tests marked `it.skip` are not listed either (Mocha runs no hook for them).
55
+
56
+ **What a failure message can contain.** Messages are scrubbed of credentials and cut to 40 lines and 2000 characters, but an assertion that compares two bodies prints both, so a message can still quote data. The console and the JUnit report show the same text. To leave messages out of the HTML report, remove `messages: true` in `tests/setup/hooks.ts`.
57
+
42
58
  ## Contract checks and coverage
43
59
 
44
60
  ```ts
@@ -71,7 +87,7 @@ const done = await waitFor(() => api.request({ method: 'GET', path: `/jobs/${id}
71
87
  - **`@negative`**: requests that each break exactly one rule of the spec (a missing required field, the wrong type, a string too long, a bad format or enum value, a number out of range, a missing parameter, malformed JSON, an unsupported content type). Every one must be rejected with a 4xx, and a valid request must be accepted. The failure message names the rule: `body.name is shorter than minLength 1 (body.name: minLength): invalid input was accepted with HTTP 201`.
72
88
  - **`@fuzz`**: hostile and extreme values in every string and number field (injection strings, null bytes, unicode tricks, huge and odd numbers, 200-level nesting, a `__proto__` key). The API must answer without failing; 2xx and 4xx are both fine, a 5xx is a defect. The choice of cases is reproducible (seeded) and capped per operation.
73
89
 
74
- If the generator cannot invent a valid value (a business rule, a complex pattern), supply known-good ones: `new OpenApiCases(loadSpec(), { baselines: { 'POST /accounts': { json: { name: 'Savings', currency: 'EUR' } } } })`. Operations with multipart, form or XML bodies get parameter cases only.
90
+ If the generator cannot invent a valid value (a business rule, a complex pattern), supply known-good ones: `new OpenApiCases(loadSpec(), { baselines: { 'POST /accounts': { json: { name: 'Savings', currency: 'EUR' } } } })`. Form (`application/x-www-form-urlencoded`) and multipart bodies get cases too, built from text-aware values: the sample's `POST /oauth/token` is a form and `POST /accounts/{id}/documents` is a multipart upload with a file. XML bodies, and form or multipart bodies with a required nested object, get parameter cases only.
75
91
 
76
92
  **These cases send writes and hostile payloads.** The sample suite approves writes for itself because it runs against the local mock. Against a real environment, approve writes (`QE_ALLOW_MUTATIONS=true` and `QE_APPROVAL=approved`) in the shell or CI job, only for an environment where that is acceptable, and never in production.
77
93
 
@@ -80,11 +96,28 @@ If the generator cannot invent a valid value (a business rule, a complex pattern
80
96
  Everything under `tests/security` is tagged `@security` (`npm run test:security`):
81
97
 
82
98
  - **`spec-cases.spec.ts`: authentication, generated from the spec.** Every operation the spec protects (`security` on the operation, or on the document and not overridden with `security: []`) must refuse a request with no credentials, an invalid bearer token or API key (in the header, query or cookie the spec names), an empty token, and credentials of the wrong type, using 401 or 403. A server that only checks that an `Authorization` header exists fails. Declare the schemes under `components.securitySchemes`.
99
+ - **`spec-cases.spec.ts`: mass assignment, generated from the spec.** A client must not be able to set what the server owns. The suite sends each read-only property the spec declares (`accountNumber` in the sample) with a distinctive value, and, unless the spec forbids extra properties, privileged names such as `isAdmin`, `role` and `ownerId`. The API must reject the request or ignore the properties; the test fails when a response returns a value that was sent, and says which property. A response that merely mirrors the request body is flagged too.
100
+ - **`spec-cases.spec.ts`: server-side request forgery, generated from the spec.** Every field that holds an address (a `uri` format, or a name such as `url`, `callback`, `webhook` or `redirect`; `webhookUrl` in the sample) is sent the cloud metadata address, loopback and private addresses, and a local file. The API must answer with a 4xx. If an API deliberately checks addresses only when it fetches them, these cases will fail: skip that suite. Against a vulnerable API the server really contacts those addresses, so run them only against an environment that may be probed.
83
101
  - **`authorization.spec.ts`: who may do what.** `AuthorizationMatrix` sends each rule's request as each identity and compares the status, covering function-level checks (a normal user calling an admin operation) and object-level checks (user B reading user A's data; add `deniedStatuses: [403, 404]` when the API hides what exists). Refusals are checked first, and a failure prints a table of statuses.
84
102
  - **`hygiene.spec.ts`: what a response gives away.** `expectSecurityHeaders` checks `X-Content-Type-Options`, `Strict-Transport-Security` (with `https: true`), `Cache-Control: no-store` (with `sensitive: true`), version leaks in `Server` and `X-Powered-By`, and wildcard CORS. `expectNoSensitiveData` finds properties named like secrets that carry a value, and values that look like JWTs, private keys, cloud keys or card numbers (`allowKeys` for what belongs, such as `access_token` on a login response). Failures name the header or path, never its value.
85
103
 
86
104
  The mock API's test identities (`tests/support/identities.ts`) stand in for the test accounts of your environment. Like the negative cases, these send requests an API should refuse, so run them only against environments where that is acceptable.
87
105
 
106
+ ## Performance smoke tests
107
+
108
+ `tests/performance/health.spec.ts` sends 50 requests, 5 at a time, and fails when the 95th percentile is above a budget or any request fails:
109
+
110
+ ```ts
111
+ const report = await runLoad(() => api.request({ method: 'GET', path: '/accounts/42' }), { requests: 50, concurrency: 5 });
112
+ expectLoad(report, { p95Ms: 300, maxErrorRate: 0.02 });
113
+ ```
114
+
115
+ A few warm-up requests go first and are left out of the figures. Failures are counted by status and error name, never by body, and the run stops early after 25 failures so a broken endpoint is not hammered. Because the requests go through `createApiClient()`, the read-only default applies: a write load is refused before anything is sent. This is a smoke test, capped at 1000 requests and 50 at a time; use k6 or Gatling for real load, and keep even this to test environments. Run it with `npm run test:performance`. The sample's limits are generous so it passes anywhere: set yours from what the API promises.
116
+
117
+ ## Tracing
118
+
119
+ Set `QE_TRACE=true` and every request carries a W3C `traceparent` header. Each test gets its own trace id (a root hook in `tests/setup/hooks.ts` starts one before every test), every request of that test joins it, and each attempt of a retried request is its own span of the same trace. When a test fails, its trace id is printed right after it: search for that id in the API's tracing backend (Jaeger, Tempo, Datadog, ...) to see what the server did. `tests/smoke/tracing.spec.ts` shows it against the mock API. This propagates trace context so the server side can correlate; it does not export spans, and it only helps if the API under test joins incoming traces. It is off by default because it adds a header to every request. To correlate with logs instead, `createApiClient` accepts `requestIdHeader: 'X-Request-Id'`, which sends each request's id (`result.requestId`) in that header.
120
+
88
121
  ## GraphQL
89
122
 
90
123
  `GraphQLClient` wraps the generated client: `new GraphQLClient(createApiClient()).execute({ query, variables })`, then `expectGraphQLSuccess(result)` or `expectGraphQLError(result, { code: 'FORBIDDEN' })`. A GraphQL query is a POST, but the client proves from the document that it is a query, so it is allowed in the default read-only run. A mutation is refused before it is sent, with the same read-only error as any other write, until you approve writes (see Safety below). `result.errors` matters as much as the status: a failed request is often HTTP 200. GraphQL APIs have no OpenAPI document, so their requests are listed as matching no operation in `reports/coverage/api.md`; that does not fail a run. The package README documents the details.
@@ -15,5 +15,9 @@ QE_ALLOW_MUTATIONS=false
15
15
  # OAUTH_CLIENT_SECRET=
16
16
  # OAUTH_SCOPE=
17
17
 
18
+ # Send a W3C traceparent header with every request, one trace per test, so a failed test can be found in the API's tracing backend.
19
+ # The trace id of a failed test is printed right after it. Off by default.
20
+ # QE_TRACE=true
21
+
18
22
  # Fail the run when fewer than this percentage of OpenAPI operations were exercised (use on full runs only).
19
23
  # QE_COVERAGE_MIN_OPERATIONS=80
@@ -23,3 +23,4 @@ test:
23
23
  paths:
24
24
  - reports/junit/
25
25
  - reports/coverage/
26
+ - reports/html/