@nikhil-qeas/api-core 0.5.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +141 -5
- package/bin/qe-api.js +4 -4
- 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 +5 -0
- package/dist/http/api-client.js +30 -6
- 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/types.d.ts +16 -0
- package/dist/index.d.ts +21 -2
- package/dist/index.js +11 -1
- package/dist/reporting/redaction.d.ts +4 -0
- package/dist/reporting/redaction.js +26 -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/matchers.d.ts +63 -0
- package/dist/testing/matchers.js +164 -0
- package/dist/testing/spec-cases.d.ts +98 -0
- package/dist/testing/spec-cases.js +795 -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 +55 -6
- package/templates/project/__dot__env.example +5 -0
- package/templates/project/openapi/openapi.json +243 -19
- package/templates/project/src/clients/api.ts +27 -6
- package/templates/project/src/{config/environment.ts → environment.ts} +16 -1
- package/templates/project/src/observability.ts +1 -1
- package/templates/project/src/{contracts/openapi.ts → openapi.ts} +1 -1
- package/templates/project/tests/contract/openapi.contract.spec.ts +1 -1
- package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
- 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 +24 -0
- package/templates/project/tests/security/write-protection.spec.ts +60 -0
- package/templates/project/tests/smoke/health.spec.ts +3 -3
- 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 +62 -3
- /package/templates/project/{config/mocha.config.json → __dot__mocharc.json} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,58 @@
|
|
|
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.7.0] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
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.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- **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.
|
|
12
|
+
- **`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.
|
|
13
|
+
- **Security testing basics.** Four checks for common API weaknesses; all report the case, path or header and never a response value.
|
|
14
|
+
- `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`.
|
|
15
|
+
- `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()`).
|
|
16
|
+
- `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`.
|
|
17
|
+
- `checkSecurityHeaders` and `expectSecurityHeaders` check `nosniff`, HSTS, `Cache-Control: no-store`, version and stack leaks and wildcard CORS, with a severity threshold.
|
|
18
|
+
- `OpenApiDocument` gains `security` and `components.securitySchemes`.
|
|
19
|
+
- **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.
|
|
20
|
+
- **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`.
|
|
21
|
+
- **`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.
|
|
22
|
+
- **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.
|
|
23
|
+
- **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.
|
|
24
|
+
- **Binary responses.** `responseType: 'binary'` returns the body as a `Uint8Array` for downloads.
|
|
25
|
+
- **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.
|
|
26
|
+
|
|
27
|
+
### Changed
|
|
28
|
+
|
|
29
|
+
- **`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.
|
|
30
|
+
- **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.
|
|
31
|
+
- **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.
|
|
32
|
+
|
|
33
|
+
### Notes for upgrading
|
|
34
|
+
|
|
35
|
+
- **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.
|
|
36
|
+
- **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.
|
|
37
|
+
- **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.
|
|
38
|
+
|
|
39
|
+
## [0.6.0] - 2026-11-23
|
|
40
|
+
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
### Changed
|
|
44
|
+
|
|
45
|
+
- **A simpler generated project layout.** `qe-api init` now writes 19 files in 9 folders instead of 27 files in 21 (not counting the project folder itself), and every folder holds something.
|
|
46
|
+
- Removed nine empty placeholder folders that nothing referenced: `config/environments`, `docs`, `reports`, `src/auth`, `src/data`, `src/workflows`, `tests/fixtures`, `tests/negative` and `tests/regression`. `reports/` is created by the test run (it is git-ignored, so its `.gitkeep` was never committed anyway). Add folders such as `tests/regression` when you need them: any `tests/**/*.spec.ts` is picked up.
|
|
47
|
+
- Removed the duplicate-looking folder names: `config/` and `src/config/` became `.mocharc.json` and `src/environment.ts`, and `src/contracts/` became `src/openapi.ts`, so `openapi/` (the spec), `src/openapi.ts` (the loader) and `tests/contract/` (the tests) no longer share confusing names.
|
|
48
|
+
- Mocha settings moved from `config/mocha.config.json` to `.mocharc.json`, which Mocha finds on its own, so the npm scripts no longer pass `--config`.
|
|
49
|
+
- Existing generated projects are unaffected. New projects get the new layout.
|
|
50
|
+
- **Generated projects are read-only by default.** `createApiClient()` now refuses POST, PUT, PATCH and DELETE before anything is sent, with an error that says why. Writes need both `QE_ALLOW_MUTATIONS=true` and `QE_APPROVAL=approved`; the client refuses to start with only one of them, and writes are never allowed when `QE_ENV` is `prod` or `production`. Before, `.env.example` and the README mentioned `QE_ENV` and `QE_ALLOW_MUTATIONS` but no generated code read them, so nothing stopped a write. The generated project gains `tests/security/write-protection.spec.ts`, which also proves against the mock API that a refused write never reaches the server. **Teams that generate a new project and run POST tests must set both variables.** Existing generated projects are unaffected, and the library's `ApiClient` is unchanged: the guard lives in the generated `src/clients/api.ts` and `src/environment.ts`, built on the existing `assertRequestPolicy` and `rejectUnsafeEnvironment`.
|
|
51
|
+
|
|
52
|
+
### Notes for upgrading
|
|
53
|
+
|
|
54
|
+
- **Already generated a project?** Nothing changes for it. To get the write protection, copy `src/clients/api.ts`, `src/environment.ts`, `tests/security/write-protection.spec.ts` and the `QE_*` lines of `.env.example` from a project generated by 0.6.0 (run `npx --yes --package @nikhil-qeas/api-core@0.6.0 qe-api init scratch-project` and diff against yours), and add the request log to `tests/support/mock-api.ts` if you use it.
|
|
55
|
+
- **CI that runs write tests** (POST, PUT, PATCH, DELETE) against a generated project's client must now set `QE_ALLOW_MUTATIONS=true` and `QE_APPROVAL=approved`, only for a test environment that may be written to. Both are refused in production.
|
|
56
|
+
|
|
5
57
|
## [0.5.1] - 2026-11-23
|
|
6
58
|
|
|
7
59
|
### Fixed
|
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.7.0 qe-api init my-api-project
|
|
11
11
|
cd my-api-project
|
|
12
12
|
npm install
|
|
13
13
|
npm run check
|
|
@@ -15,9 +15,9 @@ npm run check
|
|
|
15
15
|
|
|
16
16
|
The generated project is wired to everything in this package and runs out of the box against a local mock API (no environment, credentials or network needed):
|
|
17
17
|
|
|
18
|
-
- an `ApiClient` factory with retries, `Retry-After` handling and OAuth2 client credentials (set `OAUTH_*` to turn it on) with automatic token renewal;
|
|
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.7.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,7 +34,11 @@ 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 cases from the spec's security schemes, an authorization matrix, sensitive-data and security-header checks
|
|
40
|
+
- GraphQL (`GraphQLClient`): queries and mutations over HTTP, the `errors` array checked, and queries recognised as reads so a read-only run allows them
|
|
41
|
+
- Everyday helpers: polling (`waitFor`), partial matching and JSONPath (`expectBody`, `match`, `jsonPath`), multipart uploads, binary downloads and cookies
|
|
38
42
|
- Synthetic test data and cleanup helpers
|
|
39
43
|
- In-process concurrency and execution context
|
|
40
44
|
- JUnit, runner-neutral Mocha result collection and metadata-only Allure adapter
|
|
@@ -67,6 +71,138 @@ contract.assertResponse({ method: 'GET', path: '/accounts/{id}', status: respons
|
|
|
67
71
|
- 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
72
|
- 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
73
|
|
|
74
|
+
## Polling, matchers and JSONPath
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import { match, waitFor, expectBody, expectHeader, expectJsonPath } from '@nikhil-qeas/api-core';
|
|
78
|
+
|
|
79
|
+
// Eventually consistent APIs: poll until the job is done, or fail with a clear timeout.
|
|
80
|
+
const job = await waitFor(
|
|
81
|
+
() => api.request({ method: 'GET', path: `/jobs/${id}` }),
|
|
82
|
+
response => response.body.state === 'done',
|
|
83
|
+
{ description: 'the export job to finish', describe: response => `HTTP ${response.status}`, timeoutMs: 30_000 }
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
// Partial matching: objects only need to contain what you list. match.* stands in for values that vary.
|
|
87
|
+
expectBody(job, { state: 'done', id, createdAt: match.dateTime(), items: match.arrayOf({ sku: match.string(/^[A-Z]{3}-\d{4}$/) }, { minLength: 1 }) });
|
|
88
|
+
expectJsonPath(job, '$.items[*].price', match.number({ min: 0 }));
|
|
89
|
+
expectHeader(job, 'content-type', /^application\/json/);
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
- **`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`.
|
|
93
|
+
- **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`.
|
|
94
|
+
- **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.
|
|
95
|
+
- **`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.
|
|
96
|
+
|
|
97
|
+
## Uploads, downloads and cookies
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
const api = new ApiClient({ baseUrl, cookies: true }); // keeps the session cookies the server sets
|
|
101
|
+
|
|
102
|
+
await api.request({ method: 'POST', path: '/login', json: { user, password } }); // Set-Cookie is stored, even on a redirect
|
|
103
|
+
await api.request({
|
|
104
|
+
method: 'POST', path: '/documents',
|
|
105
|
+
multipart: [{ name: 'kind', value: 'invoice' }, { name: 'file', filename: 'q3.pdf', data: pdfBytes, contentType: 'application/pdf' }]
|
|
106
|
+
});
|
|
107
|
+
const download = await api.request({ method: 'GET', path: '/documents/7/file', responseType: 'binary' }); // download.body is a Uint8Array
|
|
108
|
+
api.cookies?.get('sid'); // or .set(...), .delete(...), .clear(), .names()
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
- **`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).
|
|
112
|
+
- **`responseType: 'binary'`** returns the response as a `Uint8Array` in `body`, byte for byte. The default decodes text and would corrupt a file.
|
|
113
|
+
- **`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.
|
|
114
|
+
- **`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.
|
|
115
|
+
|
|
116
|
+
## GraphQL
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { ApiClient, GraphQLClient, expectGraphQLError, expectGraphQLSuccess } from '@nikhil-qeas/api-core';
|
|
120
|
+
|
|
121
|
+
const graphql = new GraphQLClient(new ApiClient({ baseUrl: process.env.QE_BASE_URL! }), { path: '/graphql' });
|
|
122
|
+
|
|
123
|
+
const found = await graphql.execute<{ user: { id: string; name: string } }>({
|
|
124
|
+
query: 'query User($id: ID!) { user(id: $id) { id name } }',
|
|
125
|
+
variables: { id: '42' }
|
|
126
|
+
});
|
|
127
|
+
expectGraphQLSuccess(found);
|
|
128
|
+
console.log(found.data?.user.name);
|
|
129
|
+
|
|
130
|
+
const denied = await graphql.execute({ query: 'mutation { deleteUser(id: "42") }' });
|
|
131
|
+
expectGraphQLError(denied, { code: 'FORBIDDEN', path: 'deleteUser' });
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- **`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.
|
|
135
|
+
- **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.
|
|
136
|
+
- **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.
|
|
137
|
+
- **`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.
|
|
138
|
+
- **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.
|
|
139
|
+
|
|
140
|
+
## Negative and fuzz tests from your OpenAPI spec
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { ApiClient, OpenApiCases, assertCaseOutcome } from '@nikhil-qeas/api-core';
|
|
144
|
+
|
|
145
|
+
const cases = new OpenApiCases(spec); // an OpenAPI 3.0 or 3.1 document
|
|
146
|
+
const api = new ApiClient({ baseUrl: process.env.QE_BASE_URL! });
|
|
147
|
+
|
|
148
|
+
for (const operation of cases.operations({ methods: ['POST'] })) {
|
|
149
|
+
for (const testCase of cases.negative(operation)) {
|
|
150
|
+
it(testCase.name, async () => assertCaseOutcome(await api.request(testCase.request), testCase));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
- **`valid(op)`**: one request that satisfies the spec. Expect a 2xx.
|
|
156
|
+
- **`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.
|
|
157
|
+
- **`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`.
|
|
158
|
+
- **`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.
|
|
159
|
+
- **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.
|
|
160
|
+
- **Known-good values:** pass `baselines` (`{ 'POST /accounts': { json: {...}, pathParams: {...}, query: {...}, headers: {...} } }`) when the generator cannot invent a valid value (business rules, complex patterns).
|
|
161
|
+
- **Limits:** bodies are generated for JSON only (multipart, form and XML bodies are listed in `operation.unsupportedBody` and 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.
|
|
162
|
+
- **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.
|
|
163
|
+
|
|
164
|
+
**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.
|
|
165
|
+
|
|
166
|
+
## Security testing basics
|
|
167
|
+
|
|
168
|
+
Four checks for the most common API weaknesses (OWASP API Security Top 10: broken authentication, broken object-level and function-level authorization, excessive data exposure, 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.
|
|
169
|
+
|
|
170
|
+
**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:
|
|
171
|
+
|
|
172
|
+
- no credentials at all;
|
|
173
|
+
- an invalid bearer token (`http` bearer, `oauth2` and `openIdConnect` schemes), an empty one, and credentials of the wrong type (Basic instead of Bearer);
|
|
174
|
+
- invalid Basic credentials, when a Basic scheme is declared;
|
|
175
|
+
- an invalid API key in the header, query string or cookie the spec names (`apiKey` schemes).
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
const cases = new OpenApiCases(spec); // spec.components.securitySchemes must declare the schemes
|
|
179
|
+
for (const operation of cases.operations()) {
|
|
180
|
+
for (const testCase of cases.security(operation)) {
|
|
181
|
+
it(testCase.description, async () => assertCaseOutcome(await api.request(testCase.request), testCase));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`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.
|
|
187
|
+
|
|
188
|
+
**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.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
const matrix = new AuthorizationMatrix({ admin: adminApi, user: userApi, anonymous: anonymousApi });
|
|
192
|
+
await matrix.assert([
|
|
193
|
+
{ request: { method: 'GET', path: '/admin/stats' }, allow: ['admin'], deny: ['user', 'anonymous'] }, // function-level
|
|
194
|
+
{ name: "alice's account", request: { method: 'GET', path: `/accounts/${aliceAccountId}` }, allow: ['alice'], deny: ['bob'], deniedStatuses: [403, 404] } // object-level
|
|
195
|
+
]);
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
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.
|
|
199
|
+
|
|
200
|
+
**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.
|
|
201
|
+
|
|
202
|
+
**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.
|
|
203
|
+
|
|
204
|
+
**What this does not cover:** it does not find injection flaws, test rate limiting, forge tokens, scan for vulnerable dependencies or replace a penetration test. It checks that an API refuses what its spec says it should refuse, and that responses do not give away what they should not.
|
|
205
|
+
|
|
70
206
|
## Retries, backoff and Retry-After
|
|
71
207
|
|
|
72
208
|
```ts
|
package/bin/qe-api.js
CHANGED
|
@@ -6,11 +6,10 @@ import { fileURLToPath } from 'node:url';
|
|
|
6
6
|
const USAGE = 'Usage: qe-api init <project-name> [--dir <path>]';
|
|
7
7
|
const TEMPLATE_DIR = fileURLToPath(new URL('../templates/project/', import.meta.url));
|
|
8
8
|
const OWN_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
9
|
-
/** Directories the generated project starts with, each kept in git by an empty .gitkeep. */
|
|
10
|
-
const EMPTY_DIRS = ['config/environments', 'src/auth', 'src/data', 'src/workflows', 'tests/fixtures', 'tests/regression', 'tests/negative', 'docs', 'reports'];
|
|
11
9
|
/** Tooling the generated project shares with this package, taken from its devDependencies so the two never drift apart. */
|
|
12
10
|
const SHARED_TOOLING = ['@eslint/js', '@types/node', 'ajv', 'ajv-formats', 'eslint', 'globals', 'typescript', 'typescript-eslint'];
|
|
13
|
-
|
|
11
|
+
// Mocha finds .mocharc.json in the project root by itself, so the commands need no --config flag.
|
|
12
|
+
const MOCHA = 'node --import tsx ./node_modules/mocha/bin/mocha.js';
|
|
14
13
|
|
|
15
14
|
function parseArguments(args) {
|
|
16
15
|
const [command, name] = args;
|
|
@@ -47,6 +46,8 @@ function projectPackage(name) {
|
|
|
47
46
|
'test:smoke': `${MOCHA} --grep "@smoke"`,
|
|
48
47
|
'test:contract': `${MOCHA} --grep "@contract"`,
|
|
49
48
|
'test:security': `${MOCHA} --grep "@security"`,
|
|
49
|
+
'test:negative': `${MOCHA} --grep "@negative"`,
|
|
50
|
+
'test:fuzz': `${MOCHA} --grep "@fuzz"`,
|
|
50
51
|
'test:ci': `node -e "require('node:fs').mkdirSync('reports/junit',{recursive:true})" && ${MOCHA} --reporter xunit --reporter-option output=reports/junit/results.xml`,
|
|
51
52
|
check: 'npm run typecheck && npm run lint && npm test',
|
|
52
53
|
'audit:security': 'npm audit --audit-level=high'
|
|
@@ -73,7 +74,6 @@ function projectFiles(name) {
|
|
|
73
74
|
for (const path of templateFiles(TEMPLATE_DIR)) {
|
|
74
75
|
files.set(outputPath(path), readFileSync(join(TEMPLATE_DIR, path), 'utf8').replaceAll('__PROJECT_NAME__', name));
|
|
75
76
|
}
|
|
76
|
-
for (const directory of EMPTY_DIRS) files.set(`${directory}/.gitkeep`, '');
|
|
77
77
|
return files;
|
|
78
78
|
}
|
|
79
79
|
|
|
@@ -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 {};
|
|
@@ -33,6 +33,53 @@ function resolveResponse(doc, raw) {
|
|
|
33
33
|
}
|
|
34
34
|
return current;
|
|
35
35
|
}
|
|
36
|
+
/** Resolves a parameter or request body object, following local `#/components/<bucket>/*` references. Fails closed on anything else. */
|
|
37
|
+
function resolveComponent(doc, raw, bucket, label) {
|
|
38
|
+
const prefix = `#/components/${bucket}/`;
|
|
39
|
+
const seen = new Set();
|
|
40
|
+
let current = object(raw, label);
|
|
41
|
+
while (typeof current.$ref === 'string') {
|
|
42
|
+
const ref = current.$ref;
|
|
43
|
+
if (!ref.startsWith(prefix))
|
|
44
|
+
throw new Error(`Only local component ${label} references are permitted`);
|
|
45
|
+
if (seen.has(ref))
|
|
46
|
+
throw new Error(`Cyclic ${label} reference`);
|
|
47
|
+
seen.add(ref);
|
|
48
|
+
const name = unescapePointer(ref.slice(prefix.length));
|
|
49
|
+
const container = doc.components?.[bucket] ?? {};
|
|
50
|
+
if (!name || !Object.prototype.hasOwnProperty.call(container, name))
|
|
51
|
+
throw new Error(`Unresolved component ${label}`);
|
|
52
|
+
current = object(container[name], label);
|
|
53
|
+
}
|
|
54
|
+
return current;
|
|
55
|
+
}
|
|
56
|
+
/** Query, path and header values arrive as strings; give them the type the schema asks for so "5" can satisfy `type: integer`. */
|
|
57
|
+
function coerceParameter(value, schema) {
|
|
58
|
+
if (Array.isArray(value)) {
|
|
59
|
+
const items = schema.items !== null && typeof schema.items === 'object' && !Array.isArray(schema.items) ? schema.items : {};
|
|
60
|
+
return value.map(entry => coerceParameter(entry, items));
|
|
61
|
+
}
|
|
62
|
+
if (typeof value !== 'string')
|
|
63
|
+
return value;
|
|
64
|
+
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
|
65
|
+
if ((types.includes('integer') || types.includes('number')) && /^-?\d+(\.\d+)?$/.test(value))
|
|
66
|
+
return Number(value);
|
|
67
|
+
if (types.includes('boolean')) {
|
|
68
|
+
if (value === 'true')
|
|
69
|
+
return true;
|
|
70
|
+
if (value === 'false')
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
function asList(value) { return Array.isArray(value) ? value : []; }
|
|
76
|
+
function headerValue(headers, name) {
|
|
77
|
+
const wanted = name.toLowerCase();
|
|
78
|
+
for (const [key, value] of Object.entries(headers ?? {}))
|
|
79
|
+
if (key.toLowerCase() === wanted)
|
|
80
|
+
return value;
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
36
83
|
const SCHEMA_KEYWORDS = ['items', 'additionalProperties', 'additionalItems', 'not', 'contains', 'propertyNames', 'if', 'then', 'else', 'unevaluatedProperties', 'unevaluatedItems'];
|
|
37
84
|
const SCHEMA_LIST_KEYWORDS = ['oneOf', 'anyOf', 'allOf', 'prefixItems'];
|
|
38
85
|
const SCHEMA_MAP_KEYWORDS = ['properties', 'patternProperties', 'dependentSchemas'];
|
|
@@ -120,6 +167,7 @@ export class OpenApiValidator {
|
|
|
120
167
|
doc;
|
|
121
168
|
compiler;
|
|
122
169
|
compiled = new Map();
|
|
170
|
+
requestValidators = new Map();
|
|
123
171
|
errorDetail;
|
|
124
172
|
constructor(doc, compiler, options = {}) {
|
|
125
173
|
this.doc = doc;
|
|
@@ -161,4 +209,69 @@ export class OpenApiValidator {
|
|
|
161
209
|
const valid = validate(check.response.body);
|
|
162
210
|
assert.ok(valid, this.errorDetail === 'schema' ? `${base} Violations: ${describeViolations(validate.errors)}` : `${base} Error details suppressed to protect response data`);
|
|
163
211
|
}
|
|
212
|
+
/**
|
|
213
|
+
* Checks a request against the operation's parameters and request body: required parameters present, values matching
|
|
214
|
+
* their schemas, a body when one is required, a declared content type, and a body matching its schema.
|
|
215
|
+
* Messages name the offending parameter or body and never include the values.
|
|
216
|
+
*/
|
|
217
|
+
assertRequest(check) {
|
|
218
|
+
const label = `${check.method} ${check.path}`;
|
|
219
|
+
const fail = (what, errors) => {
|
|
220
|
+
const detail = this.errorDetail === 'schema' && errors !== undefined ? ` Violations: ${describeViolations(errors)}` : '';
|
|
221
|
+
return assert.fail(`OpenAPI request contract failed (${label}): ${what}.${detail}`);
|
|
222
|
+
};
|
|
223
|
+
const pathItem = object(this.doc.paths[check.path], 'path');
|
|
224
|
+
const op = object(pathItem[check.method.toLowerCase()], 'operation');
|
|
225
|
+
const declared = new Map(); // an operation parameter overrides a path-level one of the same name
|
|
226
|
+
for (const raw of [...asList(pathItem.parameters), ...asList(op.parameters)]) {
|
|
227
|
+
const parameter = resolveComponent(this.doc, raw, 'parameters', 'parameter');
|
|
228
|
+
declared.set(`${String(parameter.in)}:${String(parameter.name)}`, parameter);
|
|
229
|
+
}
|
|
230
|
+
for (const parameter of declared.values()) {
|
|
231
|
+
const { name } = parameter;
|
|
232
|
+
const location = parameter.in;
|
|
233
|
+
if (typeof name !== 'string' || (location !== 'path' && location !== 'query' && location !== 'header'))
|
|
234
|
+
continue; // cookies are not checked
|
|
235
|
+
const value = location === 'path' ? check.pathParams?.[name] : location === 'query' ? check.query?.[name] : headerValue(check.headers, name);
|
|
236
|
+
if (value === undefined) {
|
|
237
|
+
if (parameter.required === true || location === 'path')
|
|
238
|
+
fail(`missing required ${location} parameter "${name}"`);
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (parameter.schema === undefined)
|
|
242
|
+
continue;
|
|
243
|
+
const entry = this.requestValidator(`PARAM|${label}|${location}:${name}`, parameter.schema);
|
|
244
|
+
if (!entry.validate(coerceParameter(value, entry.schema)))
|
|
245
|
+
fail(`${location} parameter "${name}" violates its schema`, entry.validate.errors);
|
|
246
|
+
}
|
|
247
|
+
const body = op.requestBody === undefined ? undefined : resolveComponent(this.doc, op.requestBody, 'requestBodies', 'request body');
|
|
248
|
+
if (check.json === undefined) {
|
|
249
|
+
if (body?.required === true)
|
|
250
|
+
fail('the required request body is missing');
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (!body)
|
|
254
|
+
return fail('the operation declares no request body');
|
|
255
|
+
const content = object(body.content ?? {}, 'request body content');
|
|
256
|
+
const actualType = mediaType(check.contentType ?? 'application/json');
|
|
257
|
+
const selected = content[actualType] ?? (actualType.endsWith('+json') ? content['application/json'] : undefined);
|
|
258
|
+
if (!selected)
|
|
259
|
+
return fail(`the content type ${actualType} is not declared for the request body`);
|
|
260
|
+
const schema = object(selected, 'media type').schema;
|
|
261
|
+
if (schema === undefined)
|
|
262
|
+
return;
|
|
263
|
+
const entry = this.requestValidator(`BODY|${label}|${actualType}`, schema);
|
|
264
|
+
if (!entry.validate(check.json))
|
|
265
|
+
fail('the request body does not match its schema', entry.validate.errors);
|
|
266
|
+
}
|
|
267
|
+
/** Compiles a request-side schema once and remembers its normalized form, which says which types it asks for. */
|
|
268
|
+
requestValidator(key, schema) {
|
|
269
|
+
let entry = this.requestValidators.get(key);
|
|
270
|
+
if (!entry) {
|
|
271
|
+
const normalized = normalizeRoot(this.doc, schema, this.compiler.supportsRefs === true);
|
|
272
|
+
entry = { validate: this.compiler.compile(normalized), schema: normalized };
|
|
273
|
+
this.requestValidators.set(key, entry);
|
|
274
|
+
}
|
|
275
|
+
return entry;
|
|
276
|
+
}
|
|
164
277
|
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { ApiRequest, ApiResult } from '../http/types.js';
|
|
2
|
+
export type OperationKind = 'query' | 'mutation' | 'subscription';
|
|
3
|
+
export interface DocumentOperation {
|
|
4
|
+
kind: OperationKind;
|
|
5
|
+
name?: string | undefined;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The operations a document defines (fragments are not operations), or undefined when the document cannot be read with certainty:
|
|
9
|
+
* unbalanced brackets, an unterminated string, a character GraphQL does not use, or a definition that is not executable.
|
|
10
|
+
* Comments, strings and field names that merely say "mutation" are never mistaken for the keyword.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseOperations(document: string): DocumentOperation[] | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* What running the document would do: the kind of the operation the server will select. 'unknown' when that cannot be told for
|
|
15
|
+
* certain (a document that does not parse, several operations and no matching `operationName`), which callers must treat as a write.
|
|
16
|
+
*/
|
|
17
|
+
export declare function operationKind(document: string, operationName?: string): OperationKind | 'unknown';
|
|
18
|
+
/** Anything that sends requests: an `ApiClient`, or the generated project's policy-enforcing client. */
|
|
19
|
+
export interface GraphQLTransport {
|
|
20
|
+
request<T = unknown>(request: ApiRequest): Promise<ApiResult<T>>;
|
|
21
|
+
}
|
|
22
|
+
export interface GraphQLClientOptions {
|
|
23
|
+
/** The endpoint. Default `/graphql`. */
|
|
24
|
+
path?: string | undefined;
|
|
25
|
+
}
|
|
26
|
+
export interface GraphQLRequest {
|
|
27
|
+
/** The document: one or more operations and fragments. */
|
|
28
|
+
query: string;
|
|
29
|
+
variables?: Record<string, unknown> | undefined;
|
|
30
|
+
/** Required by servers when the document holds several operations. */
|
|
31
|
+
operationName?: string | undefined;
|
|
32
|
+
headers?: Record<string, string> | undefined;
|
|
33
|
+
timeoutMs?: number | undefined;
|
|
34
|
+
/** Send without the client's configured credentials (negative authentication tests). */
|
|
35
|
+
skipAuth?: boolean | undefined;
|
|
36
|
+
}
|
|
37
|
+
export interface GraphQLError {
|
|
38
|
+
message?: string;
|
|
39
|
+
path?: Array<string | number>;
|
|
40
|
+
/** `extensions.code`, when the server sends one. */
|
|
41
|
+
code?: string;
|
|
42
|
+
extensions?: Record<string, unknown>;
|
|
43
|
+
}
|
|
44
|
+
export interface GraphQLResult<T = unknown> {
|
|
45
|
+
/** What the document does, as classified before sending. 'unknown' was treated as a write. */
|
|
46
|
+
operation: OperationKind | 'unknown';
|
|
47
|
+
status: number;
|
|
48
|
+
/** `undefined` when the response has no `data` key (a request error or a non-GraphQL response); `null` when the server sent null. */
|
|
49
|
+
data: T | null | undefined;
|
|
50
|
+
errors: GraphQLError[];
|
|
51
|
+
extensions?: Record<string, unknown> | undefined;
|
|
52
|
+
/** The underlying HTTP response, for header and timing checks. */
|
|
53
|
+
response: ApiResult;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* GraphQL over HTTP on top of an `ApiClient`: sends the document as a POST, classifies it, and reads `data` and `errors`.
|
|
57
|
+
*
|
|
58
|
+
* Because a query is a POST, a read-only execution policy would refuse it. The client marks a request `readOnly` (and safe to
|
|
59
|
+
* retry) only when the document provably is a query. A mutation, a subscription and anything it cannot classify are sent as the
|
|
60
|
+
* writes they may be, so a read-only run refuses them before anything is sent and they are never retried after an ambiguous failure.
|
|
61
|
+
* This trusts the GraphQL convention that a query has no side effects.
|
|
62
|
+
*/
|
|
63
|
+
export declare class GraphQLClient {
|
|
64
|
+
private readonly api;
|
|
65
|
+
private readonly path;
|
|
66
|
+
constructor(api: GraphQLTransport, options?: GraphQLClientOptions);
|
|
67
|
+
execute<T = unknown>(request: GraphQLRequest): Promise<GraphQLResult<T>>;
|
|
68
|
+
}
|
|
69
|
+
export interface GraphQLAssertOptions {
|
|
70
|
+
/** Include the servers' error messages in failures, shortened. Off by default: messages can echo data. */
|
|
71
|
+
showMessages?: boolean | undefined;
|
|
72
|
+
}
|
|
73
|
+
type Judged = Pick<GraphQLResult, 'operation' | 'status' | 'data' | 'errors'>;
|
|
74
|
+
/** Fails unless the response is HTTP 2xx, has no GraphQL errors (partial data with errors is a failure) and carries data. */
|
|
75
|
+
export declare function expectGraphQLSuccess(result: Judged, options?: GraphQLAssertOptions): void;
|
|
76
|
+
export interface ExpectedGraphQLError {
|
|
77
|
+
/** An `extensions.code` one of the errors must have. */
|
|
78
|
+
code?: string | undefined;
|
|
79
|
+
/** A path one of the errors must have: `'user.email'` or `['user', 'email']`. */
|
|
80
|
+
path?: string | readonly (string | number)[] | undefined;
|
|
81
|
+
/** The HTTP status the response must have. */
|
|
82
|
+
status?: number | undefined;
|
|
83
|
+
}
|
|
84
|
+
/** Fails unless the response carries at least one GraphQL error matching the expectation (any error at all when none is given). */
|
|
85
|
+
export declare function expectGraphQLError(result: Judged, expected?: ExpectedGraphQLError, options?: GraphQLAssertOptions): void;
|
|
86
|
+
export {};
|