@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.
Files changed (66) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +216 -5
  3. package/bin/qe-api.js +3 -0
  4. package/dist/contracts/assertions.d.ts +11 -0
  5. package/dist/contracts/assertions.js +31 -0
  6. package/dist/contracts/openapi.d.ts +28 -1
  7. package/dist/contracts/openapi.js +113 -0
  8. package/dist/graphql/graphql.d.ts +86 -0
  9. package/dist/graphql/graphql.js +312 -0
  10. package/dist/http/api-client.d.ts +20 -0
  11. package/dist/http/api-client.js +70 -9
  12. package/dist/http/cookies.d.ts +32 -0
  13. package/dist/http/cookies.js +116 -0
  14. package/dist/http/multipart.d.ts +20 -0
  15. package/dist/http/multipart.js +48 -0
  16. package/dist/http/trace.d.ts +26 -0
  17. package/dist/http/trace.js +43 -0
  18. package/dist/http/types.d.ts +22 -0
  19. package/dist/index.d.ts +31 -5
  20. package/dist/index.js +16 -3
  21. package/dist/integrations/mocha.d.ts +32 -0
  22. package/dist/integrations/mocha.js +81 -0
  23. package/dist/reporting/html-report.d.ts +23 -0
  24. package/dist/reporting/html-report.js +118 -0
  25. package/dist/reporting/junit.d.ts +11 -2
  26. package/dist/reporting/junit.js +9 -3
  27. package/dist/reporting/redaction.d.ts +10 -0
  28. package/dist/reporting/redaction.js +36 -2
  29. package/dist/security/authorization-matrix.d.ts +55 -0
  30. package/dist/security/authorization-matrix.js +102 -0
  31. package/dist/security/headers.d.ts +21 -0
  32. package/dist/security/headers.js +45 -0
  33. package/dist/security/policy.js +3 -2
  34. package/dist/security/sensitive-data.d.ts +22 -0
  35. package/dist/security/sensitive-data.js +76 -0
  36. package/dist/testing/json-path.d.ts +6 -0
  37. package/dist/testing/json-path.js +97 -0
  38. package/dist/testing/load.d.ts +85 -0
  39. package/dist/testing/load.js +134 -0
  40. package/dist/testing/matchers.d.ts +63 -0
  41. package/dist/testing/matchers.js +164 -0
  42. package/dist/testing/spec-cases.d.ts +136 -0
  43. package/dist/testing/spec-cases.js +1065 -0
  44. package/dist/testing/wait-for.d.ts +40 -0
  45. package/dist/testing/wait-for.js +82 -0
  46. package/package.json +1 -1
  47. package/templates/project/README.md +80 -5
  48. package/templates/project/__dot__env.example +4 -0
  49. package/templates/project/__dot__gitlab-ci.yml +1 -0
  50. package/templates/project/openapi/openapi.json +476 -19
  51. package/templates/project/src/clients/api.ts +4 -2
  52. package/templates/project/src/environment.ts +8 -0
  53. package/templates/project/src/observability.ts +15 -1
  54. package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
  55. package/templates/project/tests/performance/health.spec.ts +22 -0
  56. package/templates/project/tests/security/authentication.spec.ts +3 -1
  57. package/templates/project/tests/security/authorization.spec.ts +29 -0
  58. package/templates/project/tests/security/hygiene.spec.ts +37 -0
  59. package/templates/project/tests/security/spec-cases.spec.ts +61 -0
  60. package/templates/project/tests/security/write-protection.spec.ts +2 -2
  61. package/templates/project/tests/setup/hooks.ts +32 -5
  62. package/templates/project/tests/smoke/health.spec.ts +3 -3
  63. package/templates/project/tests/smoke/tracing.spec.ts +48 -0
  64. package/templates/project/tests/support/approved-writes.ts +27 -0
  65. package/templates/project/tests/support/identities.ts +24 -0
  66. package/templates/project/tests/support/mock-api.ts +166 -3
@@ -0,0 +1,164 @@
1
+ import assert from 'node:assert/strict';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ /** An expectation that is more than equality. Build one with `match.*`; plain values and objects can be mixed with them. */
4
+ export class Matcher {
5
+ description;
6
+ check;
7
+ absent;
8
+ constructor(description, check, absent = false) {
9
+ this.description = description;
10
+ this.check = check;
11
+ this.absent = absent;
12
+ }
13
+ }
14
+ function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
15
+ function hasOwn(value, key) { return Object.prototype.hasOwnProperty.call(value, key); }
16
+ function kindOf(value) {
17
+ if (value === null)
18
+ return 'null';
19
+ if (Array.isArray(value))
20
+ return 'array';
21
+ return typeof value;
22
+ }
23
+ function describeActual(value, context) {
24
+ if (context.showValues) {
25
+ try {
26
+ const text = JSON.stringify(value) ?? String(value);
27
+ return text.length > 80 ? `${text.slice(0, 77)}...` : text;
28
+ }
29
+ catch {
30
+ return '[not serializable]';
31
+ }
32
+ }
33
+ if (value === null)
34
+ return 'null';
35
+ if (Array.isArray(value))
36
+ return `an array of ${value.length} item${value.length === 1 ? '' : 's'}`;
37
+ const kind = typeof value;
38
+ return kind === 'object' ? 'an object' : kind === 'undefined' ? 'nothing' : `a ${kind}`;
39
+ }
40
+ function describeExpected(expected) {
41
+ if (expected instanceof Matcher)
42
+ return expected.description;
43
+ const text = JSON.stringify(expected) ?? String(expected);
44
+ return text.length > 80 ? `${text.slice(0, 77)}...` : text;
45
+ }
46
+ function isType(value, type) {
47
+ if (type === 'integer')
48
+ return typeof value === 'number' && Number.isInteger(value);
49
+ if (type === 'object')
50
+ return isRecord(value);
51
+ return kindOf(value) === type;
52
+ }
53
+ function matchValue(actual, expected, path, context) {
54
+ if (expected instanceof Matcher)
55
+ return expected.check(actual, path, context);
56
+ if (Array.isArray(expected)) {
57
+ if (!Array.isArray(actual))
58
+ return [`${path}: expected an array but got ${describeActual(actual, context)}`];
59
+ if (actual.length !== expected.length)
60
+ return [`${path}: expected ${expected.length} item${expected.length === 1 ? '' : 's'} but got ${actual.length}`];
61
+ return expected.flatMap((item, index) => matchValue(actual[index], item, `${path}[${index}]`, context));
62
+ }
63
+ if (isRecord(expected)) {
64
+ if (!isRecord(actual))
65
+ return [`${path}: expected an object but got ${describeActual(actual, context)}`];
66
+ const problems = [];
67
+ for (const [key, value] of Object.entries(expected)) {
68
+ const at = `${path}.${key}`;
69
+ const present = hasOwn(actual, key);
70
+ if (value instanceof Matcher && value.absent) {
71
+ if (present)
72
+ problems.push(`${at}: should be absent`);
73
+ continue;
74
+ }
75
+ if (!present) {
76
+ problems.push(`${at}: is missing`);
77
+ continue;
78
+ }
79
+ problems.push(...matchValue(actual[key], value, at, context));
80
+ }
81
+ return problems;
82
+ }
83
+ if (Object.is(actual, expected) || actual === expected)
84
+ return [];
85
+ const sameKind = kindOf(actual) === kindOf(expected);
86
+ return [`${path}: expected ${describeExpected(expected)} but got ${context.showValues || !sameKind ? describeActual(actual, context) : `a different ${kindOf(actual)}`}`];
87
+ }
88
+ /** Matchers for the parts of a response that are not fixed values. */
89
+ export const match = {
90
+ /** Any value, as long as the property is present. */
91
+ anything: () => new Matcher('anything', () => []),
92
+ any: (type) => new Matcher(`any ${type}`, (actual, path, context) => isType(actual, type) ? [] : [`${path}: expected a ${type} but got ${describeActual(actual, context)}`]),
93
+ /** A string, optionally matching a pattern. */
94
+ string: (pattern) => {
95
+ const safe = pattern === undefined ? undefined : new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
96
+ return new Matcher(safe ? `a string matching ${String(pattern)}` : 'any string', (actual, path, context) => {
97
+ if (typeof actual !== 'string')
98
+ return [`${path}: expected a string but got ${describeActual(actual, context)}`];
99
+ return safe && !safe.test(actual) ? [`${path}: expected a string matching ${String(pattern)} but it does not`] : [];
100
+ });
101
+ },
102
+ /** A number, optionally within a range (inclusive). */
103
+ number: (range = {}) => new Matcher('a number in range', (actual, path, context) => {
104
+ if (typeof actual !== 'number')
105
+ return [`${path}: expected a number but got ${describeActual(actual, context)}`];
106
+ if (range.min !== undefined && actual < range.min)
107
+ return [`${path}: expected at least ${range.min} but it is below`];
108
+ if (range.max !== undefined && actual > range.max)
109
+ return [`${path}: expected at most ${range.max} but it is above`];
110
+ return [];
111
+ }),
112
+ oneOf: (...values) => new Matcher(`one of ${describeExpected(values)}`, (actual, path, context) => values.some(value => isDeepStrictEqual(actual, value)) ? [] : [`${path}: expected one of ${describeExpected(values)} but got ${describeActual(actual, context)}`]),
113
+ /** An array whose every item matches. */
114
+ arrayOf: (expected, options = {}) => new Matcher(`an array of ${describeExpected(expected)}`, (actual, path, context) => {
115
+ if (!Array.isArray(actual))
116
+ return [`${path}: expected an array but got ${describeActual(actual, context)}`];
117
+ const problems = options.minLength !== undefined && actual.length < options.minLength ? [`${path}: expected at least ${options.minLength} items but got ${actual.length}`] : [];
118
+ return [...problems, ...actual.flatMap((item, index) => matchValue(item, expected, `${path}[${index}]`, context))];
119
+ }),
120
+ /** An array that holds, in any order and among others, an item matching each of these. */
121
+ arrayContaining: (...expected) => new Matcher(`an array containing ${describeExpected(expected)}`, (actual, path, context) => {
122
+ if (!Array.isArray(actual))
123
+ return [`${path}: expected an array but got ${describeActual(actual, context)}`];
124
+ return expected.filter(item => !actual.some(candidate => matchValue(candidate, item, path, context).length === 0)).map(item => `${path}: no item matches ${describeExpected(item)}`);
125
+ }),
126
+ /** A string or array of this length, or within these limits. */
127
+ length: (expected) => new Matcher('a given length', (actual, path, context) => {
128
+ if (typeof actual !== 'string' && !Array.isArray(actual))
129
+ return [`${path}: expected a string or array but got ${describeActual(actual, context)}`];
130
+ const range = typeof expected === 'number' ? { min: expected, max: expected } : expected;
131
+ if (range.min !== undefined && actual.length < range.min)
132
+ return [`${path}: expected a length of at least ${range.min} but got ${actual.length}`];
133
+ if (range.max !== undefined && actual.length > range.max)
134
+ return [`${path}: expected a length of at most ${range.max} but got ${actual.length}`];
135
+ return [];
136
+ }),
137
+ /** Deep equality with no extra properties allowed, unlike a plain object which only has to be contained. */
138
+ exactly: (expected) => new Matcher(`exactly ${describeExpected(expected)}`, (actual, path, context) => isDeepStrictEqual(actual, expected) ? [] : [`${path}: expected exactly ${describeExpected(expected)} but got ${describeActual(actual, context)}`]),
139
+ not: (expected) => new Matcher(`not ${describeExpected(expected)}`, (actual, path, context) => matchValue(actual, expected, path, context).length === 0 ? [`${path}: should not match ${describeExpected(expected)}`] : []),
140
+ /** The property must not be present. */
141
+ absent: () => new Matcher('absent', () => [], true),
142
+ uuid: () => match.string(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
143
+ /** An ISO 8601 date-time with a timezone, such as 2026-01-02T03:04:05Z. */
144
+ dateTime: () => new Matcher('an ISO 8601 date-time', (actual, path, context) => typeof actual === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(actual) && !Number.isNaN(Date.parse(actual))
145
+ ? [] : [`${path}: expected an ISO 8601 date-time but got ${describeActual(actual, context)}`])
146
+ };
147
+ /**
148
+ * Compares a value with an expectation. Objects only have to contain the expected properties; arrays must have the same length
149
+ * item for item; use `match.*` for anything flexible. Problems carry their path, e.g. `$.accounts[0].status`.
150
+ */
151
+ export function matches(actual, expected, options = {}) {
152
+ const problems = matchValue(actual, expected, '$', { showValues: options.showValues === true });
153
+ return { pass: problems.length === 0, problems };
154
+ }
155
+ /** Throws listing every problem (at most ten). Actual values are described by type unless `showValues` is set. */
156
+ export function assertMatches(actual, expected, options = {}) {
157
+ const { problems } = matches(actual, expected, options);
158
+ if (!problems.length)
159
+ return;
160
+ const shown = problems.slice(0, 10).map(problem => `- ${problem}`);
161
+ if (problems.length > 10)
162
+ shown.push(`- ... and ${problems.length - 10} more`);
163
+ assert.fail(`${options.label ?? 'The value'} does not match what was expected:\n${shown.join('\n')}`);
164
+ }
@@ -0,0 +1,136 @@
1
+ import type { OpenApiDocument, RequestCheck } from '../contracts/openapi.js';
2
+ import type { ApiRequest, ApiResult, Method, Query } from '../http/types.js';
3
+ type Primitive = string | number | boolean;
4
+ export type CaseKind = 'valid' | 'negative' | 'fuzz' | 'security' | 'mass-assignment' | 'ssrf';
5
+ /** A property a mass-assignment case adds to the request, with the distinctive value it is sent with. */
6
+ export interface InjectedProperty {
7
+ name: string;
8
+ value: string | number;
9
+ }
10
+ export interface OperationRef {
11
+ method: Method;
12
+ path: string;
13
+ }
14
+ export interface OperationInfo extends OperationRef {
15
+ operationId?: string | undefined;
16
+ tags: string[];
17
+ /** True when the operation takes a JSON request body. */
18
+ jsonBody: boolean;
19
+ /**
20
+ * The kind of request body cases are generated for: JSON, else `application/x-www-form-urlencoded`, else `multipart/form-data`.
21
+ * A form or multipart body gets cases when its required properties are text, numbers, booleans, lists of those, or (multipart) files;
22
+ * nested objects have no plain encoding, so such an operation gets parameter cases only.
23
+ */
24
+ bodyKind?: 'json' | 'form' | 'multipart' | undefined;
25
+ /** True when the operation needs credentials: it (or the document) declares a security requirement and none of the alternatives is optional. */
26
+ protected: boolean;
27
+ /** Request body content types no cases are generated for: XML and the like, and any form or multipart type a JSON body took precedence over. */
28
+ unsupportedBody: string[];
29
+ }
30
+ export interface GeneratedCase {
31
+ /** Stable and unique, e.g. "POST /accounts negative #3". */
32
+ id: string;
33
+ /** Ready to use as a test title. */
34
+ name: string;
35
+ kind: CaseKind;
36
+ method: Method;
37
+ /** The OpenAPI path template. The concrete path is in `request.path`. */
38
+ path: string;
39
+ description: string;
40
+ /**
41
+ * What a conforming API does: accept ('success'), reject with a 4xx ('rejected'), or at least not fail with a 5xx ('survives').
42
+ * 'denied': refuse the credentials. 'not-applied': reject the request, or accept it without applying the added properties
43
+ * (the response must not return the values that were sent).
44
+ */
45
+ expect: 'success' | 'rejected' | 'survives' | 'denied' | 'not-applied';
46
+ /** For 'denied': the statuses that count as a proper refusal. Usually 401 and 403; 400 is also accepted for malformed credentials. */
47
+ accept?: readonly number[] | undefined;
48
+ /** For 'not-applied': the properties that were added, and the values to look for in the response. */
49
+ injected?: readonly InjectedProperty[] | undefined;
50
+ /** True when the request breaks a rule the schema states. For a JSON request `OpenApiValidator.assertRequest(check)` then throws. False for transport-level breakage such as malformed JSON. */
51
+ violatesSchema: boolean;
52
+ /** What was done to the otherwise valid request, e.g. "body.name: minLength". */
53
+ violates?: string | undefined;
54
+ /** Send this with `ApiClient.request`. */
55
+ request: ApiRequest;
56
+ /** The same request as spec-checkable parts, for `OpenApiValidator.assertRequest`. Present for negative cases of operations with a JSON body or none; form and multipart requests have none. */
57
+ check?: RequestCheck | undefined;
58
+ }
59
+ export interface OpenApiCasesOptions {
60
+ /** Known-good values per operation ("METHOD /path/template"): used instead of generated ones. Needed when a schema cannot be sampled (complex patterns, business rules). */
61
+ baselines?: Readonly<Record<string, {
62
+ pathParams?: Readonly<Record<string, Primitive>> | undefined;
63
+ query?: Query | undefined;
64
+ headers?: Readonly<Record<string, string>> | undefined;
65
+ /** The body. For a form or multipart operation, an object of its fields (a file's content as text). */
66
+ json?: unknown;
67
+ }>> | undefined;
68
+ /** At most this many fuzz cases per operation, chosen deterministically. Default 60. */
69
+ maxFuzzCases?: number | undefined;
70
+ /** Makes the choice of fuzz cases reproducible. Default 1. */
71
+ seed?: number | undefined;
72
+ }
73
+ /**
74
+ * Builds test cases from an OpenAPI document: a valid request per operation, requests that break the spec's rules one at a time
75
+ * (negative), and hostile or extreme values (fuzz). Every negative case names the rule it breaks, and can be confirmed against the
76
+ * spec with `OpenApiValidator.assertRequest(case.check)`. Cases for POST, PUT, PATCH and DELETE send writes: run them only
77
+ * against an environment that may be written to.
78
+ */
79
+ export declare class OpenApiCases {
80
+ private readonly doc;
81
+ private readonly options;
82
+ private readonly operationsByKey;
83
+ constructor(doc: OpenApiDocument, options?: OpenApiCasesOptions);
84
+ operations(filter?: {
85
+ methods?: readonly Method[];
86
+ tags?: readonly string[];
87
+ }): OperationInfo[];
88
+ /** One request that satisfies the spec. Expect it to be accepted. */
89
+ valid(reference: OperationRef): GeneratedCase;
90
+ /** Requests that each break exactly one rule of the spec. Expect a 4xx for every one. */
91
+ negative(reference: OperationRef): GeneratedCase[];
92
+ /** 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. */
93
+ fuzz(reference: OperationRef): GeneratedCase[];
94
+ /**
95
+ * Authentication cases for a protected operation: no credentials, invalid credentials of each kind the spec declares (bearer, Basic,
96
+ * 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
97
+ * 403 (a 400 is also accepted for malformed credentials). An operation without a security requirement, or with optional
98
+ * authentication, has none. The requests are sent without the client's own credentials (`skipAuth`).
99
+ */
100
+ security(reference: OperationRef): GeneratedCase[];
101
+ /**
102
+ * 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.
103
+ * One case per read-only property the spec declares (sent with a distinctive value), plus one that adds privileged names the spec
104
+ * does not declare (`isAdmin`, `role`, ...) unless it forbids extra properties. Expect `assertCaseOutcome` to pass when the API
105
+ * rejects the request, or accepts it without returning the values that were sent; it fails when a value comes back. A response that
106
+ * merely mirrors the request body will be flagged. Booleans, enums and constants are not tried: no value would stand out.
107
+ */
108
+ massAssignment(reference: OperationRef): GeneratedCase[];
109
+ /**
110
+ * Server-side request forgery cases: every string field that looks like an address the server may fetch or redirect to (a query
111
+ * parameter or top-level body property with a URI format, or named like url, uri, link, callback, webhook, redirect, href or
112
+ * endpoint) is sent, one at a time, the cloud metadata address, loopback and private addresses, and a local file. Expect a 4xx.
113
+ * An API that deliberately checks addresses only when it fetches them will fail these cases; skip them for such an API. If the API
114
+ * is vulnerable, the server really does contact these addresses, so run them only against an environment that may be probed.
115
+ */
116
+ ssrf(reference: OperationRef): GeneratedCase[];
117
+ private buildOperation;
118
+ /** The wrong credentials worth trying for the schemes the requirements name. */
119
+ private credentialsFor;
120
+ private find;
121
+ /** A request that satisfies the spec: required parameters, an example or sampled body, and any known-good values the caller supplied. */
122
+ private baseline;
123
+ private makeCase;
124
+ /** Picks `limit` of `count` candidates reproducibly (seeded shuffle), keeping their original order. */
125
+ private choose;
126
+ }
127
+ /**
128
+ * Judges a response to a generated case. The message names the case and the rule it broke, and never includes the response body.
129
+ * 'success': 2xx. 'rejected': 4xx (accepting invalid input, or failing with a 5xx, is a defect). 'survives': anything below 500.
130
+ * 'denied': a refusal of the credentials. 'not-applied': a 4xx, or a 2xx whose body does not return the values that were sent
131
+ * (this one needs the whole response, because it reads the body; the message names the properties, never their values).
132
+ */
133
+ export declare function assertCaseOutcome(response: Pick<ApiResult, 'status'> & {
134
+ body?: unknown;
135
+ }, testCase: Pick<GeneratedCase, 'expect' | 'description' | 'method' | 'path' | 'violates' | 'accept' | 'injected'>): void;
136
+ export {};