@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
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,73 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@nikhil-qeas/api-core`. The format follows [Keep a Changelog](https://keepachangelog.com/), and the project uses semantic versioning (while below 1.0, minor versions may contain behavior changes, which are listed under "Changed").
|
|
4
4
|
|
|
5
|
+
## [0.8.0] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
This release adds a performance smoke test, an HTML test report, trace propagation, mass-assignment and SSRF cases, and generated cases for form and multipart request bodies. Nothing was removed from the library API, and the new options (`trace` and `requestIdHeader` on the client; `traceId` on a request; `messages` on `writeJunit`) all default to the old behavior, so code that only imports the package needs no edits. Two things change for code that uses `OpenApiCases`, and both are listed under Changed: operations with form or multipart bodies now get body cases, and two TypeScript unions gained members. New projects from `qe-api init` get new sample suites and a report; existing generated projects are unaffected.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- **HTML test report.** `writeHtmlReport(path, results, options)` and `renderHtmlReport` produce one self-contained page: the verdict, failures first (with the trace id, and the message when asked), tests that passed only after retries, the slowest ten, every test by suite, and `facts` and `notes` you supply. It has no scripts and loads nothing, a content-security-policy forbids both, every dynamic string is escaped, and it works in dark mode and on a phone. `problems` lists what is not a test, and makes the verdict FAILED whatever the listed tests did.
|
|
12
|
+
- **`MochaResultCollector.record(test, { traceId, retries })`** records a Mocha test from a root `afterEach` hook once, with its final outcome: a failed attempt that will be retried is not recorded, and a test that passed after retries is recorded with how many it needed, so flaky tests show instead of hiding behind a pass. Failure messages are kept scrubbed (new `scrubText`: Authorization values, JWTs, card numbers, private keys and cloud keys), stripped of colors and control characters, and cut to 40 lines and 2000 characters (`failureText`). `failedHooks(rootSuite)` lists failed `before` and `after` hooks, which are not tests and have no record, so a report can say FAILED instead of PASSED when a hook broke a run. `TestCaseResult` gains `retries` and `traceId`; new types `MochaTestLike`, `HtmlReportOptions` and `JunitOptions`.
|
|
13
|
+
- **`writeJunit(path, results, { messages: true })`** writes each failure's message (escaped, with its first line as the attribute). The default is unchanged: a failure says only "Test failed".
|
|
14
|
+
- **Form and multipart request bodies get generated cases.** Until now an operation whose body is `application/x-www-form-urlencoded` or `multipart/form-data` got parameter cases only. `OpenApiCases` now builds valid, negative, fuzz, authentication, mass-assignment and SSRF cases for them, sent as `request.form` or `request.multipart`. Because every field is text, the cases use text-aware values, as parameters do: text that cannot be read as the declared number or boolean, a value outside an enum, a missing required field, a value too short or long, a list with too few or too many items (a list repeats the field name) and an extra field where the spec forbids it. "A string for an integer" and an empty list are not violations there, so they are not generated. A `format: binary` (or `contentMediaType`) property is sent as a file part with the content type from `encoding`. `OperationInfo.bodyKind` says which kind of body cases are built for (JSON, else form, else multipart); form and multipart cases have no `check`; a body with a required nested object or a list of objects has no plain encoding and gets parameter cases only. Fuzz adds a `__proto__[polluted]` field in place of the JSON nesting and `__proto__` cases.
|
|
15
|
+
- **Performance smoke tests.** `runLoad(send, options)` calls a function many times, a few at a time, after a warm-up phase that is left out of the figures, and returns counts, the error rate, duration, throughput, nearest-rank latency percentiles (`p50` to `p99`, `min`, `mean`, `max`), statuses by code and errors by name, never bodies or messages. `expectLoad(report, limits)` fails listing every broken limit (`p50Ms` to `maxMs`, `maxErrorRate` with a default of no failures, `minThroughput`); a run that stopped early or measured nothing never passes, and an invalid limit throws. `summarizeLoad` gives one line for the log. It is a smoke test, not a load generator: at most 1000 requests, 50 at a time and 20 warm-up requests (`MAX_LOAD_REQUESTS`, `MAX_LOAD_CONCURRENCY`, `MAX_LOAD_WARMUP`), and it stops after `abortAfterFailures` failures (default 25) so a broken endpoint is not hammered. With a client that enforces a read-only policy a write load is refused before anything is sent.
|
|
16
|
+
- **Trace propagation.** `ApiClient` accepts `trace: true` (or a `TraceConfig`) and sends a W3C `traceparent` header, so a failed test can be found in the API's tracing backend. The trace id is a new one per request, a fixed one, or whatever a function returns for each request (for example the running test's id); `sampled` defaults to true. Every attempt of a retried request is a new span of the same trace. The trace id is reported as `result.traceId` and on `retry`, `success` and `network-error` events. `ApiRequest.traceId` overrides the setting for one request, and a `traceparent` header the caller sets is sent exactly as written and never duplicated. An invalid trace id throws before anything is sent. New exports: `newTraceId`, `newSpanId`, `formatTraceparent`, `parseTraceparent`, `isTraceId`, `TraceConfig`, `ParsedTraceparent`. This propagates context only: no spans are exported, and `tracestate` and `baggage` are not sent.
|
|
17
|
+
- **`requestIdHeader`** sends each request's id (`result.requestId`, the same on every attempt) in a header such as `X-Request-Id`, unless the request sets that header itself.
|
|
18
|
+
- **Mass-assignment cases.** `OpenApiCases.massAssignment(op)` builds, for a POST, PUT or PATCH with a JSON, form or multipart object body, one case per read-only property the spec declares (sent with a distinctive value) and one that adds privileged names the spec does not declare (`isAdmin`, `role`, `ownerId`, `userId`, `balance`, `verified`), unless the spec forbids extra properties. `assertCaseOutcome` judges them (`expect: 'not-applied'`): a 4xx passes, a 2xx passes unless the response returns a value that was sent, and the failure names the property, never the value. Because it reads the body, it needs the whole response, not only its status, and says so if given only a status.
|
|
19
|
+
- **SSRF cases.** `OpenApiCases.ssrf(op)` sends each address-like string field (a `uri` format, or a name such as `url`, `callback`, `webhook` or `redirect`) in the query or the top level of the body the cloud metadata address, loopback and private addresses, and a local file, and expects a 4xx.
|
|
20
|
+
- New case kinds `'mass-assignment'` and `'ssrf'`, `GeneratedCase.injected` and the `InjectedProperty` type.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- **Operations with form or multipart bodies now get body cases (runtime).** `OpenApiCases` used to build parameter cases only for an operation whose body is `application/x-www-form-urlencoded` or `multipart/form-data`, and `valid()` sent no body for it. Now `valid`, `negative`, `fuzz`, `security`, `massAssignment` and `ssrf` build body cases for it, so a suite that loops over every operation sends more, different requests than before, including writes and hostile values, to those operations. A read-only run still refuses the writes before sending. `OperationInfo.bodyKind` tells the kinds apart (`jsonBody` stays false for them), and `unsupportedBody` no longer lists a form or multipart type that is used for cases.
|
|
25
|
+
- **`CaseKind` and `GeneratedCase.expect` gained members (TypeScript only).** `CaseKind` adds `'mass-assignment'` and `'ssrf'`, and `expect` adds `'not-applied'`, so code that switches over them exhaustively must handle the new values. `assertCaseOutcome` now accepts a response that has a `body`, and needs the body to judge a `'not-applied'` case.
|
|
26
|
+
- **Generated projects** write `reports/html/index.html` after every run (and the pipeline keeps it as an artifact). A root `afterEach` hook records each test's final outcome, the root `afterAll` hook writes the page with the API coverage and request figures, names any failed hook, and includes scrubbed failure messages (`messages: true`, which the console and the JUnit report already show). `npm run test:ci -- --retries 2` retries failing tests, and the report lists the ones that only passed on a retry. Existing generated projects are unaffected; to get the report, copy `tests/setup/hooks.ts`, `src/observability.ts` and the `reports/html/` line of `.gitlab-ci.yml` from a new project.
|
|
27
|
+
- **Generated projects** document two more operations in the sample spec: `POST /oauth/token` (a form body) and `POST /accounts/{id}/documents` (a multipart upload with a file), and the mock validates both. The generated negative, fuzz and security suites build cases for them without any change. The sample `authentication.spec.ts` now asks for `clientAuth: 'body'`, because the mock's token endpoint takes the client credentials in the form body; the library default is an HTTP Basic header.
|
|
28
|
+
- **Generated projects** gain `tests/performance/health.spec.ts` (`@performance`: 50 requests, 5 at a time, with a generous latency budget and no failures allowed) and the script `test:performance`.
|
|
29
|
+
- **Generated projects** gain opt-in tracing: with `QE_TRACE=true` the client sends a `traceparent` header, a root hook starts a new trace before every test so all requests of a test share one, and a failed test prints its trace id. Off by default, so requests are unchanged. The mock records the `traceparent` headers it receives, and `tests/smoke/tracing.spec.ts` shows the behavior. A root `beforeEach` hook now runs for every test (it only generates an id).
|
|
30
|
+
- **Generated projects.** The sample `NewAccount` gains `webhookUrl` (a `uri`) and a read-only `accountNumber`; the mock accepts and ignores `accountNumber` and refuses a `webhookUrl` that is not a public http or https address. `tests/security/spec-cases.spec.ts` gains two suites, mass assignment and SSRF (7 cases for the sample). Existing generated projects are unaffected; copy the new suites from a scratch project to get them.
|
|
31
|
+
|
|
32
|
+
### Notes for upgrading
|
|
33
|
+
|
|
34
|
+
- **Already generated a project?** Nothing changes for it. To get the new features, generate a scratch project with this version (`npx --yes --package @nikhil-qeas/api-core@0.8.0 qe-api init scratch-project`) and copy what you want: `tests/setup/hooks.ts`, `src/observability.ts` and the `reports/html/` line of `.gitlab-ci.yml` for the HTML report; `tests/performance/` and the `test:performance` script; `tests/smoke/tracing.spec.ts` with the `QE_TRACE` parts of `src/environment.ts` and `src/clients/api.ts`; the two new suites in `tests/security/spec-cases.spec.ts`; and the new operations and validation in `openapi/openapi.json` and `tests/support/mock-api.ts` if you keep the samples.
|
|
35
|
+
- **If you loop over `cases.operations()` against a real environment**, operations with form or multipart bodies now send body requests too (see Changed). Run them only where hostile writes are acceptable, and note that the SSRF cases make a vulnerable server contact the internal addresses they carry.
|
|
36
|
+
- **Flaky tests.** `npm run test:ci -- --retries 2` retries failing tests in a generated project, and the HTML report lists the ones that only passed on a retry. Retries cannot be set from a hook; they come from Mocha's configuration.
|
|
37
|
+
|
|
38
|
+
## [0.7.0] - 2026-11-23
|
|
39
|
+
|
|
40
|
+
This release adds testing capabilities: test cases generated from your OpenAPI spec, security checks, GraphQL, and everyday helpers for polling, matching, uploads and cookies. Nothing was removed from the library API, and the new options (`cookies` on the client; `multipart`, `skipCookies`, `responseType` and `readOnly` on a request) all default to the old behavior, so code that only imports the package needs no edits. The one TypeScript-level change is listed under Changed. New projects from `qe-api init` get new sample suites; existing generated projects are unaffected.
|
|
41
|
+
|
|
42
|
+
### Added
|
|
43
|
+
|
|
44
|
+
- **GraphQL.** `GraphQLClient` sends queries and mutations over HTTP on top of an `ApiClient` (or the generated project's policy client) and returns `data`, `errors`, `extensions` and the HTTP response. `expectGraphQLSuccess` fails on HTTP errors, on any GraphQL error (partial data included) and on missing data; `expectGraphQLError` checks the code, path and status of an expected error. Failure messages name codes and paths, never the server's messages, unless `showMessages` is set. `operationKind` and `parseOperations` classify a document by the operations the server will run, ignoring comments, strings and field names.
|
|
45
|
+
- **`ApiRequest.readOnly`** declares that a POST changes nothing (a GraphQL query, a search endpoint that takes a body). `assertRequestPolicy` lets it through a read-only run; it is ignored for PUT, PATCH and DELETE. `GraphQLClient` sets it, together with `idempotent`, only for documents it can prove are queries. A mutation, a subscription and a document it cannot classify are sent as writes: refused in a read-only run and never retried after an ambiguous failure.
|
|
46
|
+
- **Security testing basics.** Four checks for common API weaknesses; all report the case, path or header and never a response value.
|
|
47
|
+
- `OpenApiCases.security(op)` builds authentication cases from `components.securitySchemes` and `security` (operation level overrides document level; `security: []` or an empty alternative means public): no credentials, an invalid and an empty bearer token, credentials of the wrong type, invalid Basic credentials, and an invalid API key in the header, query or cookie the spec names. `assertCaseOutcome` judges them (`expect: 'denied'`): 401 or 403, or whatever the case lists in the new `accept` field. A 2xx fails as granted, a 5xx as a crash, a 3xx as not a refusal. `OperationInfo` gains `protected`.
|
|
48
|
+
- `AuthorizationMatrix` checks who may do what, function-level and object-level, with refusals sent before grants, `deniedStatuses` for APIs that answer 404, a `strict` mode, and a status table (`toMarkdown()`).
|
|
49
|
+
- `findSensitiveData` and `expectNoSensitiveData` find secret-looking properties that carry a value and credential-looking values (JWTs, private keys, cloud keys, `Authorization` values, card numbers), with `allowKeys` and `allowPaths`.
|
|
50
|
+
- `checkSecurityHeaders` and `expectSecurityHeaders` check `nosniff`, HSTS, `Cache-Control: no-store`, version and stack leaks and wildcard CORS, with a severity threshold.
|
|
51
|
+
- `OpenApiDocument` gains `security` and `components.securitySchemes`.
|
|
52
|
+
- **Spec-driven negative and fuzz tests.** `OpenApiCases` builds test cases from an OpenAPI 3.0 or 3.1 document: `valid(op)`, `negative(op)` (requests that each break exactly one rule of the spec and say which) and `fuzz(op)` (hostile and extreme values in every string and number field). `assertCaseOutcome` judges the response and never quotes it. Cases are generated only where the rule is unambiguous, `baselines` supplies known-good values the generator cannot invent, and fuzz selection is seeded and capped. The library's own tests prove every negative case is really invalid, using an independent validator.
|
|
53
|
+
- **Request validation.** `OpenApiValidator.assertRequest()` checks a request against its operation: required path, query and header parameters, values against their schemas (query text is read as the declared type), a required body, a declared content type, and the body schema. Messages name the parameter or body and never the value. New public types: `RequestCheck`, `GeneratedCase`, `OperationInfo`, `OpenApiCasesOptions`.
|
|
54
|
+
- **`waitFor`** polls an eventually consistent API until a condition holds, with a constant or growing interval, `maxAttempts`, an `AbortSignal`, an injectable clock and optional `retryOnError`. It throws `WaitTimeoutError`, whose message names what was awaited and never quotes a result.
|
|
55
|
+
- **Partial matching and JSONPath.** `expectBody`, `matches` and `assertMatches` compare a value with an expectation where objects only need to contain the listed properties, with `match.*` for what varies (`any`, `string`, `number`, `oneOf`, `arrayOf`, `arrayContaining`, `length`, `exactly`, `not`, `absent`, `uuid`, `dateTime`). `jsonPath` and `expectJsonPath` evaluate a small JSONPath subset and throw on syntax they cannot evaluate. `expectHeader` checks response headers. Failure messages describe actual values by type unless `showValues` is set.
|
|
56
|
+
- **Multipart uploads.** `ApiRequest.multipart` sends text fields and files with a random boundary that appears nowhere in the data, browser-style escaping of names, and identical bytes on every retry. `RequestContext` gains `exactBodyBytes`, the exact bytes sent, so a signer can sign binary bodies. `encodeMultipart` is exported.
|
|
57
|
+
- **Binary responses.** `responseType: 'binary'` returns the body as a `Uint8Array` for downloads.
|
|
58
|
+
- **Cookies.** `ApiClient` accepts `cookies: true` or a shared `CookieJar` and keeps the session cookies a server sets (`Path`, `Secure`, `Max-Age`, `Expires` and `Domain` are honored; the jar is capped and never lists values). `skipCookies` opts a request out. Cookie values never appear in events or errors.
|
|
59
|
+
|
|
60
|
+
### Changed
|
|
61
|
+
|
|
62
|
+
- **`RequestContext` (TypeScript only).** It gains a required `exactBodyBytes: Uint8Array`, the exact bytes sent, so a request signer can sign binary bodies. Code that only reads the context, such as a signer, is unaffected. Code that builds a `RequestContext` itself, for example to unit-test a signer, must add the field.
|
|
63
|
+
- **Generated projects** gain a `POST /accounts` operation in the sample spec, a mock API that validates it, a `tests/negative/spec-cases.spec.ts` suite (`@negative` and `@fuzz`, about 70 cases) and the scripts `test:negative` and `test:fuzz`. The suite approves writes for itself because it runs against the local mock; against a real environment, approving writes stays an explicit decision. The write-protection test now expects the mock to reject its probe body with a 400 instead of a 404.
|
|
64
|
+
- **Generated projects** also gain security tests. The sample spec declares a bearer scheme and a protected `GET /admin/stats` (admins get 200, other users 403, nobody 401), and `tests/security` adds `spec-cases.spec.ts` (generated authentication cases for every protected operation), `authorization.spec.ts` (an authorization matrix with admin, user and anonymous) and `hygiene.spec.ts` (security headers and sensitive data). The mock sends `X-Content-Type-Options` and `Cache-Control: no-store`. The write approval the suites use moved to `tests/support/approved-writes.ts` so the negative and security suites share it.
|
|
65
|
+
|
|
66
|
+
### Notes for upgrading
|
|
67
|
+
|
|
68
|
+
- **Already generated a project?** Nothing changes for it. To get the new suites, generate a scratch project with this version (`npx --yes --package @nikhil-qeas/api-core@0.7.0 qe-api init scratch-project`) and copy what you want: `tests/negative/spec-cases.spec.ts`, `tests/security/*.spec.ts` and `tests/support/approved-writes.ts` with `identities.ts`, plus the `securitySchemes`, `security` and `GET /admin/stats` additions to the sample spec and mock if you keep the samples.
|
|
69
|
+
- **The generated negative, fuzz and security suites send requests an API should refuse** (invalid input, hostile payloads, missing or wrong credentials), and some of them are writes. The samples approve writes for themselves because they run against the local mock. Against a real environment, approving writes stays an explicit decision (`QE_ALLOW_MUTATIONS=true` and `QE_APPROVAL=approved`), and never in production.
|
|
70
|
+
- **GraphQL in a read-only run.** `GraphQLClient` sends a document it can prove is a query as a read, so the generated read-only guard allows it; a mutation, a subscription or a document it cannot classify is refused until writes are approved.
|
|
71
|
+
|
|
5
72
|
## [0.6.0] - 2026-11-23
|
|
6
73
|
|
|
7
74
|
This release changes what `qe-api init` generates. The library API (`ApiClient`, `TokenManager`, `OpenApiCoverage` and the rest) is unchanged, so code that only imports the package needs no edits.
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ A reusable TypeScript API test utility library and project initializer. Public n
|
|
|
7
7
|
**Generate a complete new project:**
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
-
npx --yes --package @nikhil-qeas/api-core@0.
|
|
10
|
+
npx --yes --package @nikhil-qeas/api-core@0.8.0 qe-api init my-api-project
|
|
11
11
|
cd my-api-project
|
|
12
12
|
npm install
|
|
13
13
|
npm run check
|
|
@@ -17,7 +17,7 @@ The generated project is wired to everything in this package and runs out of the
|
|
|
17
17
|
|
|
18
18
|
- an `ApiClient` factory that is **read-only by default** (writes need both `QE_ALLOW_MUTATIONS=true` and `QE_APPROVAL=approved`, and are never allowed in production), with retries, `Retry-After` handling and OAuth2 client credentials (set `OAUTH_*` to turn it on) with automatic token renewal;
|
|
19
19
|
- an OpenAPI document (`openapi/openapi.json`, replace it with yours) that drives both **contract tests** (Ajv-backed) and an end-of-run **coverage report** (`reports/coverage/api.md`, with an optional `QE_COVERAGE_MIN_OPERATIONS` gate);
|
|
20
|
-
- working `@smoke`, `@contract` and `@security` samples, including a token-renewal scenario and negative authentication tests;
|
|
20
|
+
- working `@smoke`, `@contract` and `@security` samples, including a token-renewal scenario and negative authentication tests, plus `@negative` and `@fuzz` suites generated from the OpenAPI spec;
|
|
21
21
|
- ESLint with type-aware rules, `npm audit`, JUnit output and a GitLab CI pipeline.
|
|
22
22
|
|
|
23
23
|
`npm run check` in the new project runs typecheck, lint and all tests. The project's README explains the layout. Generated projects pin this package at the version that generated them, and share its TypeScript, ESLint and Ajv ranges.
|
|
@@ -25,7 +25,7 @@ The generated project is wired to everything in this package and runs out of the
|
|
|
25
25
|
**Add utilities to an existing project:**
|
|
26
26
|
|
|
27
27
|
```bash
|
|
28
|
-
npm install --save-dev @nikhil-qeas/api-core@0.
|
|
28
|
+
npm install --save-dev @nikhil-qeas/api-core@0.8.0
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
Installing the package does **not** modify your source tree: utilities live under `node_modules`. Run the generator explicitly when you want a new project. The CLI refuses to overwrite an existing directory.
|
|
@@ -34,10 +34,16 @@ Installing the package does **not** modify your source tree: utilities live unde
|
|
|
34
34
|
|
|
35
35
|
- HTTP client with timeout handling, exact-body signing interface, and safe retries with exponential backoff, jitter and `Retry-After` support
|
|
36
36
|
- Token cache with OAuth2 client-credentials and refresh-token providers, and automatic re-authentication on HTTP 401
|
|
37
|
-
- OpenAPI 3.0/3.1 response
|
|
37
|
+
- OpenAPI 3.0/3.1 response and request validation, with a ready-made Ajv backend (`createOpenApiValidator`)
|
|
38
|
+
- Spec-driven negative and fuzz test generation (`OpenApiCases`)
|
|
39
|
+
- Security testing basics: authentication, mass-assignment and SSRF cases from the spec, an authorization matrix, sensitive-data and security-header checks
|
|
40
|
+
- Performance smoke tests (`runLoad`, `expectLoad`): bounded concurrent requests with latency percentiles, error rate and throughput limits
|
|
41
|
+
- Trace propagation (W3C `traceparent`) and request-id headers, so a failed test can be found in the API's tracing backend
|
|
42
|
+
- GraphQL (`GraphQLClient`): queries and mutations over HTTP, the `errors` array checked, and queries recognised as reads so a read-only run allows them
|
|
43
|
+
- Everyday helpers: polling (`waitFor`), partial matching and JSONPath (`expectBody`, `match`, `jsonPath`), multipart uploads, binary downloads and cookies
|
|
38
44
|
- Synthetic test data and cleanup helpers
|
|
39
45
|
- In-process concurrency and execution context
|
|
40
|
-
- JUnit, runner-neutral Mocha result collection and metadata-only Allure adapter
|
|
46
|
+
- JUnit, runner-neutral Mocha result collection, a self-contained HTML report (failures first, flaky tests, failed hooks) and metadata-only Allure adapter
|
|
41
47
|
- Spec-driven endpoint coverage from an OpenAPI document (`OpenApiCoverage`), plus a manual scenario registry
|
|
42
48
|
- Safety policies, simple metrics and data redaction
|
|
43
49
|
|
|
@@ -67,6 +73,211 @@ contract.assertResponse({ method: 'GET', path: '/accounts/{id}', status: respons
|
|
|
67
73
|
- Failures never include response data. By default the message says details are suppressed; `errorDetail: 'schema'` adds the violated schema locations and rule messages (never values or property names).
|
|
68
74
|
- Use `createAjvCompiler({ dialect })` with `new OpenApiValidator(spec, compiler)` when you need to control the Ajv setup yourself, or pass any compiler with the same `compile()` shape.
|
|
69
75
|
|
|
76
|
+
## Polling, matchers and JSONPath
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { match, waitFor, expectBody, expectHeader, expectJsonPath } from '@nikhil-qeas/api-core';
|
|
80
|
+
|
|
81
|
+
// Eventually consistent APIs: poll until the job is done, or fail with a clear timeout.
|
|
82
|
+
const job = await waitFor(
|
|
83
|
+
() => api.request({ method: 'GET', path: `/jobs/${id}` }),
|
|
84
|
+
response => response.body.state === 'done',
|
|
85
|
+
{ description: 'the export job to finish', describe: response => `HTTP ${response.status}`, timeoutMs: 30_000 }
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
// Partial matching: objects only need to contain what you list. match.* stands in for values that vary.
|
|
89
|
+
expectBody(job, { state: 'done', id, createdAt: match.dateTime(), items: match.arrayOf({ sku: match.string(/^[A-Z]{3}-\d{4}$/) }, { minLength: 1 }) });
|
|
90
|
+
expectJsonPath(job, '$.items[*].price', match.number({ min: 0 }));
|
|
91
|
+
expectHeader(job, 'content-type', /^application\/json/);
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
- **`waitFor(attempt, until, options)`** returns the first value `until` accepts, or throws `WaitTimeoutError`. Options: `timeoutMs` (10 s), `intervalMs` (250 ms), `backoffFactor` and `maxIntervalMs` for a growing wait, `maxAttempts`, `retryOnError` (treat an error as "not yet", for example while a resource still answers 404 through a client that throws), an `AbortSignal`, and a `clock` that makes tests instant. The last wait is cut short so the deadline is not overshot. The timeout message names what you waited for and never quotes a result: `describe` supplies a safe summary, and the last result is on the error as `lastValue`.
|
|
95
|
+
- **Matching:** `expectBody`, `matches` and `assertMatches` compare a value with an expectation. Objects only have to contain the listed properties, arrays must match item for item, and `match.anything()`, `any(type)`, `string(regex)`, `number({ min, max })`, `oneOf(...)`, `arrayOf(...)`, `arrayContaining(...)`, `length(...)`, `exactly(...)`, `not(...)`, `absent()`, `uuid()` and `dateTime()` cover what varies. Every problem is reported with its path, for example `$.accounts[1].status: expected "open" but got a different string`.
|
|
96
|
+
- **Messages describe actual values by type** ("a string", "an array of 3 items") because responses may hold sensitive data. Pass `{ showValues: true }` while debugging to see them.
|
|
97
|
+
- **`jsonPath(value, path)`** evaluates a small JSONPath subset: `$`, `.name`, `['name']`, `[0]`, `[-1]`, `[*]`, `.*`, `..name`. A path it cannot evaluate (filters, slices, unions) throws instead of silently matching nothing, and only own properties are read. `expectJsonPath` requires at least one match and, when given an expectation, checks every match against it.
|
|
98
|
+
|
|
99
|
+
## Uploads, downloads and cookies
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
const api = new ApiClient({ baseUrl, cookies: true }); // keeps the session cookies the server sets
|
|
103
|
+
|
|
104
|
+
await api.request({ method: 'POST', path: '/login', json: { user, password } }); // Set-Cookie is stored, even on a redirect
|
|
105
|
+
await api.request({
|
|
106
|
+
method: 'POST', path: '/documents',
|
|
107
|
+
multipart: [{ name: 'kind', value: 'invoice' }, { name: 'file', filename: 'q3.pdf', data: pdfBytes, contentType: 'application/pdf' }]
|
|
108
|
+
});
|
|
109
|
+
const download = await api.request({ method: 'GET', path: '/documents/7/file', responseType: 'binary' }); // download.body is a Uint8Array
|
|
110
|
+
api.cookies?.get('sid'); // or .set(...), .delete(...), .clear(), .names()
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
- **`multipart`** sends text fields and files (bytes or a string). The client sets the `Content-Type` with a random boundary that appears nowhere in the data, so supplying your own is an error. Names and filenames are escaped the way browsers do, so a hostile one cannot inject headers or extra parts. A retry resends exactly the same bytes, and a request signer receives them as `exactBodyBytes` (`exactBody` is a lossy text decoding for binary bodies).
|
|
114
|
+
- **`responseType: 'binary'`** returns the response as a `Uint8Array` in `body`, byte for byte. The default decodes text and would corrupt a file.
|
|
115
|
+
- **`cookies: true`** (or your own `CookieJar`, shared between clients) keeps the cookies a response sets and sends them back on matching requests. `Path`, `Secure` (https only), `Max-Age`, `Expires` and a `Domain` that must match the host are honored; `SameSite` and `HttpOnly` are browser concerns and ignored. The jar is capped at 100 cookies, ignores malformed ones, and lists names but never values. Cookie values are credentials: they never appear in events or error messages.
|
|
116
|
+
- **`skipCookies: true`** sends a request without the jar and does not keep what it sets; an explicit `Cookie` header is never replaced. Cookies are off unless you ask.
|
|
117
|
+
|
|
118
|
+
## GraphQL
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
import { ApiClient, GraphQLClient, expectGraphQLError, expectGraphQLSuccess } from '@nikhil-qeas/api-core';
|
|
122
|
+
|
|
123
|
+
const graphql = new GraphQLClient(new ApiClient({ baseUrl: process.env.QE_BASE_URL! }), { path: '/graphql' });
|
|
124
|
+
|
|
125
|
+
const found = await graphql.execute<{ user: { id: string; name: string } }>({
|
|
126
|
+
query: 'query User($id: ID!) { user(id: $id) { id name } }',
|
|
127
|
+
variables: { id: '42' }
|
|
128
|
+
});
|
|
129
|
+
expectGraphQLSuccess(found);
|
|
130
|
+
console.log(found.data?.user.name);
|
|
131
|
+
|
|
132
|
+
const denied = await graphql.execute({ query: 'mutation { deleteUser(id: "42") }' });
|
|
133
|
+
expectGraphQLError(denied, { code: 'FORBIDDEN', path: 'deleteUser' });
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
- **`execute()`** POSTs `{ query, variables, operationName }` as JSON, accepts `application/graphql-response+json` and plain JSON, and returns `{ operation, status, data, errors, extensions, response }`. `response` is the HTTP result, for header and timing checks. Pass `operationName` when the document holds several operations.
|
|
137
|
+
- **Check `errors`, not just the status.** A GraphQL server often answers HTTP 200 for a request that failed. `expectGraphQLSuccess` fails on a non-2xx status, on any GraphQL error (partial data does not hide it) and on missing data. `expectGraphQLError(result, { code, path, status })` is its counterpart for negative tests; `path` is `'user.email'` or `['user', 'email']`. Failure messages name error codes and paths and never the server's error messages, which often echo data; `showMessages: true` adds them, shortened, and leaves out any that hold a credential.
|
|
138
|
+
- **Reads and writes.** A query is a POST, so a read-only execution policy would refuse it. The client classifies the document before sending (`operationKind(document, operationName)`): a query, including one selected by `operationName` out of a multi-operation document, is sent with `readOnly` and `idempotent`, so a read-only run allows it and it is retried after a transient failure. A mutation, a subscription and anything it cannot classify with certainty (a document that does not parse, or several operations and no matching `operationName`) are sent as the writes they may be: refused before anything is sent in a read-only run, never retried after an ambiguous failure. The words "mutation" or "query" in comments, strings and field names do not count, only the operations the server will run. This relies on the GraphQL convention that a query has no side effects.
|
|
139
|
+
- **`ApiRequest.readOnly`** is the underlying switch, for other POSTs that only read (a search endpoint that takes a body). It is a claim, not a check, and it is ignored for PUT, PATCH and DELETE. `assertRequestPolicy` honors it.
|
|
140
|
+
- **Not covered:** subscriptions (WebSocket or SSE), persisted queries (a request needs the full document), multipart file uploads, batched requests, and GraphQL-specific security checks (introspection exposure, query depth and cost limits). Nothing is generated from a GraphQL schema. A GraphQL endpoint has no OpenAPI document, so OpenAPI coverage lists `POST /graphql` as matching no operation, unless you describe it in your spec.
|
|
141
|
+
|
|
142
|
+
## Negative and fuzz tests from your OpenAPI spec
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import { ApiClient, OpenApiCases, assertCaseOutcome } from '@nikhil-qeas/api-core';
|
|
146
|
+
|
|
147
|
+
const cases = new OpenApiCases(spec); // an OpenAPI 3.0 or 3.1 document
|
|
148
|
+
const api = new ApiClient({ baseUrl: process.env.QE_BASE_URL! });
|
|
149
|
+
|
|
150
|
+
for (const operation of cases.operations({ methods: ['POST'] })) {
|
|
151
|
+
for (const testCase of cases.negative(operation)) {
|
|
152
|
+
it(testCase.name, async () => assertCaseOutcome(await api.request(testCase.request), testCase));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
- **`valid(op)`**: one request that satisfies the spec. Expect a 2xx.
|
|
158
|
+
- **`negative(op)`**: requests that each break exactly one rule, and say which: a missing required property or parameter, the wrong type, null, `minLength`/`maxLength`, `pattern`, `format`, `enum`, `minimum`/`maximum`/`multipleOf`, array sizes, an extra property where `additionalProperties` is false, a body of the wrong type or none when one is required, plus malformed JSON and an unsupported content type. Expect a 4xx.
|
|
159
|
+
- **`fuzz(op)`**: hostile and extreme values in each string and number field (injection strings, null bytes, unicode tricks, `MAX_SAFE_INTEGER`, 200-level nesting, a `__proto__` key). Expect an answer below 500: 2xx and 4xx are both acceptable, a 5xx is a defect. Capped by `maxFuzzCases` (default 60 per operation) and reproducible through `seed`.
|
|
160
|
+
- **`assertCaseOutcome(response, testCase)`** judges the answer by the case's expectation. Messages name the case and the rule it broke and never quote the response.
|
|
161
|
+
- **It claims only what it can be sure of.** A case is built only when the rule is unambiguous: nothing is generated from `oneOf`/`anyOf` schemas (what breaks one alternative may satisfy another), `readOnly` properties are never sent, and null is not offered to nullable fields. Every case that breaks the schema carries a `check` that `validator.assertRequest(testCase.check)` rejects, which is how the library's own tests prove the cases are really invalid.
|
|
162
|
+
- **Known-good values:** pass `baselines` (`{ 'POST /accounts': { json: {...}, pathParams: {...}, query: {...}, headers: {...} } }`) when the generator cannot invent a valid value (business rules, complex patterns).
|
|
163
|
+
- **Form and multipart bodies.** `operation.bodyKind` says which body cases are built for: JSON first, else `application/x-www-form-urlencoded`, else `multipart/form-data`. A form or multipart body is sent as `request.form` or `request.multipart`, and every field is text, so its cases use text-aware values, as parameters do: text that cannot be read as the declared number or boolean, an enum value that is not allowed, a missing required field, a value that is too short or long, a list with too few or too many items (a list repeats the field name), and an extra field where the spec forbids it. "A string for an integer" is not a violation there, and an empty list is not either (it sends nothing, the same as the field missing). A multipart property with `format: binary` (or a `contentMediaType`) is sent as a file part with the content type from `encoding` (the first of a list), and the sampled text as its content. Fuzz values go into every text and number field, and into file content. Mass-assignment, SSRF and authentication cases work on form and multipart bodies too. Form and multipart cases have no `check`, because `OpenApiValidator.assertRequest` validates JSON bodies. Supply known-good fields as `baselines: { 'POST /oauth/token': { json: { grant_type: 'client_credentials', client_id: '...' } } }`.
|
|
164
|
+
- **Limits:** XML and other body types, and form or multipart bodies with a required nested object (or a list of objects), which have no plain encoding, are listed in `operation.unsupportedBody` or get parameter cases only; cookie parameters, `not`, `if/then/else` and `dependentRequired` are not modeled. Header parameters get missing and invalid-value cases but are not fuzzed, because the HTTP stack rejects bad header values before the API sees them. `Authorization`, `Content-Type` and `Accept` parameters are left to the client.
|
|
165
|
+
- **These cases send writes and hostile payloads.** Run them only against an environment that may be written to. In a generated project the write guard refuses them until you approve writes.
|
|
166
|
+
|
|
167
|
+
**Request validation.** `OpenApiValidator.assertRequest({ method, path: '/accounts/{id}', pathParams, query, headers, json })` checks a request against its operation: required parameters present, values matching their schemas (query text such as `'10'` is read as the declared integer), a body when one is required, a declared content type, and a body matching its schema. Use it to make sure your own tests send conforming requests. Messages name the parameter or body, never the value.
|
|
168
|
+
|
|
169
|
+
## Security testing basics
|
|
170
|
+
|
|
171
|
+
Six checks for common API weaknesses (OWASP API Security Top 10: broken authentication, broken object-level and function-level authorization, mass assignment, excessive data exposure, server-side request forgery, security misconfiguration). They are tests of *your* API's behavior, not a scanner: they send requests an API should refuse, so run them only against environments where that is acceptable.
|
|
172
|
+
|
|
173
|
+
**1. Authentication cases from the spec.** `cases.security(op)` returns cases for operations the spec protects (`security` on the operation, or on the document and not overridden with `security: []`; an empty requirement `{}` among the alternatives makes authentication optional, so no cases are built). Credentials are removed from the client (`skipAuth`), then each case sends:
|
|
174
|
+
|
|
175
|
+
- no credentials at all;
|
|
176
|
+
- an invalid bearer token (`http` bearer, `oauth2` and `openIdConnect` schemes), an empty one, and credentials of the wrong type (Basic instead of Bearer);
|
|
177
|
+
- invalid Basic credentials, when a Basic scheme is declared;
|
|
178
|
+
- an invalid API key in the header, query string or cookie the spec names (`apiKey` schemes).
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
const cases = new OpenApiCases(spec); // spec.components.securitySchemes must declare the schemes
|
|
182
|
+
for (const operation of cases.operations()) {
|
|
183
|
+
for (const testCase of cases.security(operation)) {
|
|
184
|
+
it(testCase.description, async () => assertCaseOutcome(await api.request(testCase.request), testCase));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`assertCaseOutcome` expects 401 or 403 (a 400 is also accepted for an empty or malformed credential). A 2xx fails with `access was granted ... without valid credentials`, which is how a server that only checks that an `Authorization` header exists is caught; a 5xx fails as a crash; any other status fails with the statuses it expected. The failure names the case, never the response.
|
|
190
|
+
|
|
191
|
+
**2. Who may do what: `AuthorizationMatrix`.** Rules name the identities that must be allowed and the ones that must be refused. Each identity is anything with a `request()` method, typically an `ApiClient` with that identity's credentials.
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
const matrix = new AuthorizationMatrix({ admin: adminApi, user: userApi, anonymous: anonymousApi });
|
|
195
|
+
await matrix.assert([
|
|
196
|
+
{ request: { method: 'GET', path: '/admin/stats' }, allow: ['admin'], deny: ['user', 'anonymous'] }, // function-level
|
|
197
|
+
{ name: "alice's account", request: { method: 'GET', path: `/accounts/${aliceAccountId}` }, allow: ['alice'], deny: ['bob'], deniedStatuses: [403, 404] } // object-level
|
|
198
|
+
]);
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Refusals are sent before grants, so a destructive request that wrongly succeeds for the wrong identity is reported on its own cell instead of breaking the grants that follow (use disposable resources for rules that change data). A refusal means 401 or 403; add 404 through `deniedStatuses` (per rule or in the options) when the API hides what exists. `strict: true` requires every rule to say what happens for every identity. `run()` returns the report instead of throwing; `report.toMarkdown()` renders a table of statuses (✅ as expected, ❌ not, — not tested), and a failure message includes it. Statuses only: never response bodies.
|
|
202
|
+
|
|
203
|
+
**3. Excessive data exposure: `expectNoSensitiveData(response, options)`.** Fails when the body contains a property named like a secret that carries a value (`password`, `passwordHash`, `secret`, `clientSecret`, `apiKey`, `privateKey`, `token`, `refreshToken`, `ssn`, `cvv`, `pin`, `otp`, ...; whole words, so `shipping` is not `pin`), or a string that looks like a JWT, a private key, a cloud access key, an `Authorization` credential or a Luhn-valid card number. `null`, `""`, booleans (`hasPassword`) and ordinary names (`token_type`, `nextPageToken`) are fine. Allow what belongs with `allowKeys` (`['access_token']` on a login response) or `allowPaths` (`['$.items[*].apiKey']`; a concrete index `[0]` means every item). `findSensitiveData(body)` returns the findings. Messages list paths and reasons, never values.
|
|
204
|
+
|
|
205
|
+
**4. Security headers: `expectSecurityHeaders(response, options)`.** Fails (at `failOn`, default `'medium'`) when `X-Content-Type-Options: nosniff` is missing; with `https: true`, when `Strict-Transport-Security` is missing or its `max-age` is under six months; with `sensitive: true`, when `Cache-Control` lacks `no-store`. It reports as low severity: a `Server` header with a version number, `X-Powered-By` and `X-AspNet-Version`, and `Access-Control-Allow-Origin: *`, which becomes high when credentials are also allowed. `checkSecurityHeaders` returns the findings; `ignore` accepts the headers you accept. Messages name the header and never its value.
|
|
206
|
+
|
|
207
|
+
**5. Mass assignment: `cases.massAssignment(op)`.** A client must not be able to set what the server owns. For a POST, PUT or PATCH with a JSON, form or multipart object body it builds one case per read-only property the spec declares, sent with a distinctive value (`readOnly` string and number properties; booleans, enums and constants would not stand out and are skipped), and one case that adds privileged names the spec does not declare (`isAdmin`, `role`, `ownerId`, `userId`, `balance`, `verified`), unless the spec forbids extra properties or already declares the name. `assertCaseOutcome` passes a 4xx, and passes a 2xx that does not return what was sent; it fails when the response returns a sent value, found at any depth and under another spelling (`is_admin`, a number returned as text), and names the property, never the value. A server that stores a value but does not return it is not caught, and a response that merely mirrors the request body is flagged. The judging reads the body, so pass `assertCaseOutcome` the whole response.
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
for (const testCase of cases.massAssignment(operation)) {
|
|
211
|
+
it(testCase.description, async () => assertCaseOutcome(await api.request(testCase.request), testCase));
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
**6. Server-side request forgery: `cases.ssrf(op)`.** Every string field that holds an address (a query parameter or top-level body property with a `uri`, `url` or `uri-reference` format, or a name with the word `url`, `uri`, `link`, `callback`, `webhook`, `redirect`, `href` or `endpoint`) is sent, one at a time, the cloud metadata address, a loopback address with a port, `localhost`, the IPv6 loopback address, a private network address and a local file. The API must answer 4xx. An API that deliberately checks addresses only when it fetches them fails these cases, so skip them for such an API. Against a vulnerable API the server really contacts the address, so run these only where that is acceptable. Case ids are `METHOD /path mass-assignment #n` and `METHOD /path ssrf #n`.
|
|
216
|
+
|
|
217
|
+
**What this does not cover:** it does not find injection flaws (SQL, command, template), test rate limiting, forge tokens, scan for vulnerable dependencies or replace a penetration test. Mass-assignment and SSRF cases look at what the response says; they cannot see what the server did with the value afterwards, and SSRF cases cannot prove a fetch happened. It checks that an API refuses what its spec says it should refuse, and that responses do not give away what they should not.
|
|
218
|
+
|
|
219
|
+
## Performance smoke tests
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { expectLoad, runLoad, summarizeLoad } from '@nikhil-qeas/api-core';
|
|
223
|
+
|
|
224
|
+
const report = await runLoad(() => api.request({ method: 'GET', path: '/accounts/42' }), { requests: 50, concurrency: 5 });
|
|
225
|
+
console.log(summarizeLoad(report));
|
|
226
|
+
expectLoad(report, { p95Ms: 300, maxErrorRate: 0.02, minThroughput: 20 });
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
This catches an endpoint that became slow, or started failing, under a little concurrency. It is not a load test.
|
|
230
|
+
|
|
231
|
+
- **`runLoad(send, options)`** calls `send()` (any function that returns something with a `status`) `requests` times, `concurrency` at a time. A warm-up phase (`warmup`, default 3) runs first and is left out of every figure. The report has the counts, the error rate, the duration and throughput, `latency` (`min`, `mean`, `p50`, `p90`, `p95`, `p99`, `max` in ms, nearest-rank percentiles), `statuses` by code and `errors` by error name. It never holds a response body or an error message. Latency is measured around each call to `send`, so it includes the client's own work and retries.
|
|
232
|
+
- **`expectLoad(report, limits)`** fails and lists every limit that is broken: `p50Ms`, `p90Ms`, `p95Ms`, `p99Ms`, `meanMs`, `maxMs` (a figure equal to its limit passes), `maxErrorRate` (a share from 0 to 1; default 0, so no failures are allowed) and `minThroughput`. A run that stopped early or measured nothing never passes, and a limit that is not a finite number of at least 0 throws instead of silently passing.
|
|
233
|
+
- **Failure means a status of 400 or more, or a request that threw.** Change it with `isSuccess: status => status < 500` when a 404 is expected.
|
|
234
|
+
- **Hard limits.** At most 1000 requests, 50 at a time and 20 warm-up requests, and these cannot be raised: use k6 or Gatling for real load. The run stops sending after `abortAfterFailures` failures (default 25, warm-up included), so a broken endpoint is not hammered; requests already in flight finish. `signal` stops it on demand.
|
|
235
|
+
- **Read-only runs stay read-only.** `send` is yours, so use a client that enforces your execution policy (the generated project's `createApiClient()` does): a POST load is then refused before anything is sent, every call throws, and the run stops after the allowed failures.
|
|
236
|
+
- **Timing depends on the machine.** Numbers from a laptop, a shared CI runner and a test environment differ; set limits with headroom, and prefer percentiles over the maximum. Use `now` to inject a clock in tests of your own.
|
|
237
|
+
|
|
238
|
+
## Test reports and flaky tests
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
import { MochaResultCollector, failedHooks, writeHtmlReport } from '@nikhil-qeas/api-core';
|
|
242
|
+
|
|
243
|
+
const results = new MochaResultCollector();
|
|
244
|
+
export const mochaHooks = { // a Mocha root hook plugin
|
|
245
|
+
afterEach(this: Mocha.Context) { if (this.currentTest) results.record(this.currentTest); },
|
|
246
|
+
async afterAll(this: Mocha.Context) {
|
|
247
|
+
const broken = this.test?.parent ? failedHooks(this.test.parent) : [];
|
|
248
|
+
await writeHtmlReport('reports/html/index.html', results.results(), {
|
|
249
|
+
messages: true,
|
|
250
|
+
problems: broken.length ? [`${broken.length} hooks failed: ${broken.join('; ')}`] : []
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Generated projects already do this; run `npm run test:ci -- --retries 2` there to retry failing tests.
|
|
257
|
+
|
|
258
|
+
- **`MochaResultCollector.record(test, { traceId })`** takes a Mocha test from a root `afterEach` hook and records it once, with its final outcome. Mocha runs `afterEach` after every attempt, and an attempt that will be retried has no state yet, so nothing is recorded for it: a test that fails twice and then passes is one record, `passed`, with `retries: 2`. That is a flaky test, and the reports list it as one instead of hiding it behind a pass. A failure's message is kept scrubbed (`scrubText`: Authorization values, JWTs, card numbers, private keys, cloud keys), stripped of colors and control characters, and cut to 40 lines and 2000 characters (`failureText`). Retries are set in Mocha's configuration (`--retries 2`); setting them from a root hook does nothing. Tests marked `it.skip` are not recorded, because Mocha runs no hook for them.
|
|
259
|
+
- **`writeHtmlReport(path, results, options)`** writes one page: the verdict, failures first (with the trace id, and the message when `messages: true`), the tests that passed only after retries, the slowest ten, every test by suite, and any `facts` you give (coverage, request figures). It is self-contained: no scripts, no files to load, a content-security-policy that forbids both, and every test title, message and fact is escaped. It works in dark mode and on a phone. Failure messages are left out unless `messages` is true, because a message can quote data (an assertion that compares two bodies prints both).
|
|
260
|
+
- **A failed hook is not a test.** If a `before` hook fails, its tests never run and have no record, so a report built from tests alone would say PASSED on a failed run. `failedHooks(rootSuite)` lists the failed hooks (it reads Mocha's `getHooks`, which Mocha's type definitions do not declare, so it accepts any suite), and `problems` makes the report say FAILED, name them, and show the problem in red whatever the listed tests did. `renderHtmlReport` returns the page as text, and `notes` adds neutral warnings.
|
|
261
|
+
- **`writeJunit(path, results, { messages: true })`** now writes each failure's message (escaped, with the first line as the attribute). The default is unchanged: a failure says only "Test failed". `TestCaseResult` gains `retries` and `traceId`.
|
|
262
|
+
- **Not Mocha-only.** `TestCaseResult` is a plain object (`name`, `suite`, `status`, `durationMs`, and optionally `message`, `retries`, `traceId`), so any runner can feed the writers.
|
|
263
|
+
|
|
264
|
+
## Tracing and correlation
|
|
265
|
+
|
|
266
|
+
```ts
|
|
267
|
+
const api = new ApiClient({ baseUrl: process.env.QE_BASE_URL!, trace: true }); // a new trace per request
|
|
268
|
+
const result = await api.request({ method: 'GET', path: '/accounts/42' });
|
|
269
|
+
console.log(result.traceId); // search for this id in Jaeger, Tempo, Datadog, ... to see what the server did
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
When a test fails in CI, the first question is what the server did. `trace` makes every request carry a W3C `traceparent` header (`00-<trace id>-<span id>-01`), and the trace id comes back on the result and on every event.
|
|
273
|
+
|
|
274
|
+
- **One trace per test.** `trace: { traceId: () => idOfTheRunningTest }` calls the function for each request, so every request of a test lands in one trace; when it returns `undefined` the request gets a trace of its own. A fixed id works too, and `sampled: false` clears the sampled flag (default: sampled, since test traffic is worth keeping). `ApiRequest.traceId` overrides the setting for one request, and sends a `traceparent` even when the client does not trace.
|
|
275
|
+
- **Retries.** Every attempt of a retried request is a new span of the same trace, so the failed attempts show up next to the one that worked. The `retry`, `success` and `network-error` events all carry `traceId`.
|
|
276
|
+
- **Your own header wins.** A `traceparent` header you set on a request or in `defaultHeaders` is sent exactly as written (a deliberately malformed one works for negative tests), never duplicated, and its trace id is the one reported.
|
|
277
|
+
- **Request ids.** `requestIdHeader: 'X-Request-Id'` also sends the request's id (`result.requestId`) in that header, the same on every attempt, unless the request sets it itself. Use it to correlate with logs that have no tracing.
|
|
278
|
+
- **Helpers:** `newTraceId()`, `newSpanId()`, `formatTraceparent()`, `parseTraceparent()`, `isTraceId()`. An invalid trace id throws before anything is sent, not even a token request.
|
|
279
|
+
- **What this is not.** It propagates trace context; it does not export spans, needs no OpenTelemetry SDK, and records nothing. `tracestate` and `baggage` are not sent. It helps only when the API under test joins incoming traces (many gateways and services do; some strip the header). Generated projects wire it up with `QE_TRACE=true`.
|
|
280
|
+
|
|
70
281
|
## Retries, backoff and Retry-After
|
|
71
282
|
|
|
72
283
|
```ts
|
package/bin/qe-api.js
CHANGED
|
@@ -46,6 +46,9 @@ function projectPackage(name) {
|
|
|
46
46
|
'test:smoke': `${MOCHA} --grep "@smoke"`,
|
|
47
47
|
'test:contract': `${MOCHA} --grep "@contract"`,
|
|
48
48
|
'test:security': `${MOCHA} --grep "@security"`,
|
|
49
|
+
'test:negative': `${MOCHA} --grep "@negative"`,
|
|
50
|
+
'test:fuzz': `${MOCHA} --grep "@fuzz"`,
|
|
51
|
+
'test:performance': `${MOCHA} --grep "@performance"`,
|
|
49
52
|
'test:ci': `node -e "require('node:fs').mkdirSync('reports/junit',{recursive:true})" && ${MOCHA} --reporter xunit --reporter-option output=reports/junit/results.xml`,
|
|
50
53
|
check: 'npm run typecheck && npm run lint && npm test',
|
|
51
54
|
'audit:security': 'npm audit --audit-level=high'
|
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import type { ApiResult } from '../http/types.js';
|
|
2
|
+
import type { MatchOptions, Matcher } from '../testing/matchers.js';
|
|
2
3
|
export declare function expectStatus(response: ApiResult, status: number): void;
|
|
3
4
|
export declare function expectClientError(response: ApiResult): void;
|
|
4
5
|
export declare function expectResponseTime(response: ApiResult, budgetMs: number): void;
|
|
5
6
|
export type Validator<T> = (value: unknown) => value is T;
|
|
6
7
|
export declare function expectContract<T>(response: ApiResult, validator: Validator<T>): T;
|
|
8
|
+
/**
|
|
9
|
+
* Checks the response body against an expectation: objects only need to contain the expected properties, arrays must match item for
|
|
10
|
+
* item, and `match.*` stands in for values that vary. Failures list each problem by path and describe actual values by type only,
|
|
11
|
+
* unless `showValues` is set.
|
|
12
|
+
*/
|
|
13
|
+
export declare function expectBody(response: Pick<ApiResult, 'status' | 'body'>, expected: unknown, options?: MatchOptions): void;
|
|
14
|
+
/** Checks that a JSONPath (`$.items[0].id`, `$..status`, `$.accounts[*].currency`) matches in the body and, when given, that every match meets the expectation. */
|
|
15
|
+
export declare function expectJsonPath(response: Pick<ApiResult, 'status' | 'body'>, path: string, expected?: unknown, options?: MatchOptions): void;
|
|
16
|
+
/** Checks that a response header is present and, when given, equals a string, matches a pattern or satisfies a matcher. The value is never quoted. */
|
|
17
|
+
export declare function expectHeader(response: Pick<ApiResult, 'headers'>, name: string, expected?: string | RegExp | Matcher): void;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
|
+
import { jsonPath } from '../testing/json-path.js';
|
|
3
|
+
import { assertMatches } from '../testing/matchers.js';
|
|
2
4
|
export function expectStatus(response, status) {
|
|
3
5
|
assert.equal(response.status, status, `Expected HTTP ${status}, received ${response.status}`);
|
|
4
6
|
}
|
|
@@ -12,3 +14,32 @@ export function expectContract(response, validator) {
|
|
|
12
14
|
assert.ok(validator(response.body), 'Response contract validation failed');
|
|
13
15
|
return response.body;
|
|
14
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* Checks the response body against an expectation: objects only need to contain the expected properties, arrays must match item for
|
|
19
|
+
* item, and `match.*` stands in for values that vary. Failures list each problem by path and describe actual values by type only,
|
|
20
|
+
* unless `showValues` is set.
|
|
21
|
+
*/
|
|
22
|
+
export function expectBody(response, expected, options = {}) {
|
|
23
|
+
assertMatches(response.body, expected, { ...options, label: `The response body (HTTP ${response.status})` });
|
|
24
|
+
}
|
|
25
|
+
/** Checks that a JSONPath (`$.items[0].id`, `$..status`, `$.accounts[*].currency`) matches in the body and, when given, that every match meets the expectation. */
|
|
26
|
+
export function expectJsonPath(response, path, expected, options = {}) {
|
|
27
|
+
const found = jsonPath(response.body, path);
|
|
28
|
+
assert.ok(found.length > 0, `JSONPath ${path} matched nothing in the response body (HTTP ${response.status})`);
|
|
29
|
+
if (expected === undefined)
|
|
30
|
+
return;
|
|
31
|
+
found.forEach((value, index) => assertMatches(value, expected, { ...options, label: `JSONPath ${path}${found.length > 1 ? ` (match ${index + 1} of ${found.length})` : ''}` }));
|
|
32
|
+
}
|
|
33
|
+
/** Checks that a response header is present and, when given, equals a string, matches a pattern or satisfies a matcher. The value is never quoted. */
|
|
34
|
+
export function expectHeader(response, name, expected) {
|
|
35
|
+
const actual = response.headers[name.toLowerCase()];
|
|
36
|
+
assert.ok(actual !== undefined, `Response header "${name}" is missing`);
|
|
37
|
+
if (expected === undefined)
|
|
38
|
+
return;
|
|
39
|
+
if (typeof expected === 'string')
|
|
40
|
+
assert.ok(actual === expected, `Response header "${name}" does not have the expected value`);
|
|
41
|
+
else if (expected instanceof RegExp)
|
|
42
|
+
assert.ok(new RegExp(expected.source, expected.flags.replace(/[gy]/g, '')).test(actual), `Response header "${name}" does not match ${String(expected)}`);
|
|
43
|
+
else
|
|
44
|
+
assertMatches(actual, expected, { label: `Response header "${name}"` });
|
|
45
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ApiResult, Method } from '../http/types.js';
|
|
1
|
+
import type { ApiResult, Method, Query } from '../http/types.js';
|
|
2
2
|
type CompiledValidator = ((data: unknown) => boolean) & {
|
|
3
3
|
errors?: readonly unknown[] | null;
|
|
4
4
|
};
|
|
@@ -18,9 +18,14 @@ export interface OpenApiValidatorOptions {
|
|
|
18
18
|
export interface OpenApiDocument {
|
|
19
19
|
openapi: string;
|
|
20
20
|
paths: Record<string, unknown>;
|
|
21
|
+
/** Document-wide security requirements: a list of alternatives, each naming schemes. */
|
|
22
|
+
security?: unknown[];
|
|
21
23
|
components?: {
|
|
24
|
+
securitySchemes?: Record<string, unknown>;
|
|
22
25
|
schemas?: Record<string, unknown>;
|
|
23
26
|
responses?: Record<string, unknown>;
|
|
27
|
+
parameters?: Record<string, unknown>;
|
|
28
|
+
requestBodies?: Record<string, unknown>;
|
|
24
29
|
};
|
|
25
30
|
}
|
|
26
31
|
export interface ContractCheck {
|
|
@@ -31,13 +36,35 @@ export interface ContractCheck {
|
|
|
31
36
|
contentType?: string;
|
|
32
37
|
response: Pick<ApiResult, 'status' | 'body' | 'headers'>;
|
|
33
38
|
}
|
|
39
|
+
/** A request as the spec describes it: the operation (by its path template), path/query/header values and the JSON body. */
|
|
40
|
+
export interface RequestCheck {
|
|
41
|
+
method: Method;
|
|
42
|
+
/** The OpenAPI path template, e.g. `/accounts/{id}`. */
|
|
43
|
+
path: string;
|
|
44
|
+
pathParams?: Readonly<Record<string, string | number | boolean>> | undefined;
|
|
45
|
+
query?: Query | undefined;
|
|
46
|
+
headers?: Readonly<Record<string, string>> | undefined;
|
|
47
|
+
/** The JSON body. Leave undefined to send none. */
|
|
48
|
+
json?: unknown;
|
|
49
|
+
/** Defaults to `application/json`. */
|
|
50
|
+
contentType?: string | undefined;
|
|
51
|
+
}
|
|
34
52
|
/** Validates a response against an OpenAPI 3.x response schema with a supplied JSON Schema compiler (e.g. Ajv). */
|
|
35
53
|
export declare class OpenApiValidator {
|
|
36
54
|
private readonly doc;
|
|
37
55
|
private readonly compiler;
|
|
38
56
|
private readonly compiled;
|
|
57
|
+
private readonly requestValidators;
|
|
39
58
|
private readonly errorDetail;
|
|
40
59
|
constructor(doc: OpenApiDocument, compiler: JsonSchemaCompiler, options?: OpenApiValidatorOptions);
|
|
41
60
|
assertResponse(check: ContractCheck): void;
|
|
61
|
+
/**
|
|
62
|
+
* Checks a request against the operation's parameters and request body: required parameters present, values matching
|
|
63
|
+
* their schemas, a body when one is required, a declared content type, and a body matching its schema.
|
|
64
|
+
* Messages name the offending parameter or body and never include the values.
|
|
65
|
+
*/
|
|
66
|
+
assertRequest(check: RequestCheck): void;
|
|
67
|
+
/** Compiles a request-side schema once and remembers its normalized form, which says which types it asks for. */
|
|
68
|
+
private requestValidator;
|
|
42
69
|
}
|
|
43
70
|
export {};
|