@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.
Files changed (54) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +141 -5
  3. package/bin/qe-api.js +4 -4
  4. package/dist/contracts/assertions.d.ts +11 -0
  5. package/dist/contracts/assertions.js +31 -0
  6. package/dist/contracts/openapi.d.ts +28 -1
  7. package/dist/contracts/openapi.js +113 -0
  8. package/dist/graphql/graphql.d.ts +86 -0
  9. package/dist/graphql/graphql.js +312 -0
  10. package/dist/http/api-client.d.ts +5 -0
  11. package/dist/http/api-client.js +30 -6
  12. package/dist/http/cookies.d.ts +32 -0
  13. package/dist/http/cookies.js +116 -0
  14. package/dist/http/multipart.d.ts +20 -0
  15. package/dist/http/multipart.js +48 -0
  16. package/dist/http/types.d.ts +16 -0
  17. package/dist/index.d.ts +21 -2
  18. package/dist/index.js +11 -1
  19. package/dist/reporting/redaction.d.ts +4 -0
  20. package/dist/reporting/redaction.js +26 -2
  21. package/dist/security/authorization-matrix.d.ts +55 -0
  22. package/dist/security/authorization-matrix.js +102 -0
  23. package/dist/security/headers.d.ts +21 -0
  24. package/dist/security/headers.js +45 -0
  25. package/dist/security/policy.js +3 -2
  26. package/dist/security/sensitive-data.d.ts +22 -0
  27. package/dist/security/sensitive-data.js +76 -0
  28. package/dist/testing/json-path.d.ts +6 -0
  29. package/dist/testing/json-path.js +97 -0
  30. package/dist/testing/matchers.d.ts +63 -0
  31. package/dist/testing/matchers.js +164 -0
  32. package/dist/testing/spec-cases.d.ts +98 -0
  33. package/dist/testing/spec-cases.js +795 -0
  34. package/dist/testing/wait-for.d.ts +40 -0
  35. package/dist/testing/wait-for.js +82 -0
  36. package/package.json +1 -1
  37. package/templates/project/README.md +55 -6
  38. package/templates/project/__dot__env.example +5 -0
  39. package/templates/project/openapi/openapi.json +243 -19
  40. package/templates/project/src/clients/api.ts +27 -6
  41. package/templates/project/src/{config/environment.ts → environment.ts} +16 -1
  42. package/templates/project/src/observability.ts +1 -1
  43. package/templates/project/src/{contracts/openapi.ts → openapi.ts} +1 -1
  44. package/templates/project/tests/contract/openapi.contract.spec.ts +1 -1
  45. package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
  46. package/templates/project/tests/security/authorization.spec.ts +29 -0
  47. package/templates/project/tests/security/hygiene.spec.ts +37 -0
  48. package/templates/project/tests/security/spec-cases.spec.ts +24 -0
  49. package/templates/project/tests/security/write-protection.spec.ts +60 -0
  50. package/templates/project/tests/smoke/health.spec.ts +3 -3
  51. package/templates/project/tests/support/approved-writes.ts +27 -0
  52. package/templates/project/tests/support/identities.ts +24 -0
  53. package/templates/project/tests/support/mock-api.ts +62 -3
  54. /package/templates/project/{config/mocha.config.json → __dot__mocharc.json} +0 -0
@@ -0,0 +1,40 @@
1
+ import type { ClientClock } from '../http/retry.js';
2
+ /** Thrown when the condition did not become true in time. The message never includes results: see `lastValue` and `lastError` for debugging. */
3
+ export declare class WaitTimeoutError extends Error {
4
+ readonly attempts: number;
5
+ readonly elapsedMs: number;
6
+ readonly lastValue: unknown;
7
+ readonly lastError: unknown;
8
+ constructor(message: string, attempts: number, elapsedMs: number, lastValue: unknown, lastError: unknown);
9
+ }
10
+ export interface WaitForOptions<T> {
11
+ /** Give up after this long. Default 10000. */
12
+ timeoutMs?: number | undefined;
13
+ /** First wait between attempts. Default 250. */
14
+ intervalMs?: number | undefined;
15
+ /** Upper bound for the wait when it grows. Default 2000. */
16
+ maxIntervalMs?: number | undefined;
17
+ /** Multiplies the wait after each attempt. Default 1: a constant interval. */
18
+ backoffFactor?: number | undefined;
19
+ /** Give up after this many attempts, whatever the time. */
20
+ maxAttempts?: number | undefined;
21
+ /** What is being waited for, for the timeout message: "the export job to finish". */
22
+ description?: string | undefined;
23
+ /** A safe summary of a result for the timeout message, e.g. `response => \`HTTP ${response.status}\``. Results are never printed otherwise. */
24
+ describe?: ((value: T) => string) | undefined;
25
+ /** Treat an error thrown by the attempt as "not yet" (true, or a predicate choosing which errors). Default false: errors propagate at once. */
26
+ retryOnError?: boolean | ((error: unknown) => boolean) | undefined;
27
+ signal?: AbortSignal | undefined;
28
+ /** Replace to run waits instantly and deterministically in tests. */
29
+ clock?: ClientClock | undefined;
30
+ }
31
+ /**
32
+ * Polls until a condition holds, for eventually consistent APIs: a job that finishes later, a record that appears after a delay,
33
+ * a cache that expires. Returns the first value `until` accepts, or throws `WaitTimeoutError`.
34
+ *
35
+ * ```ts
36
+ * const job = await waitFor(() => api.request({ method: 'GET', path: `/jobs/${id}` }), r => r.body.state === 'done',
37
+ * { description: 'the job to finish', describe: r => `HTTP ${r.status}`, timeoutMs: 30_000 });
38
+ * ```
39
+ */
40
+ export declare function waitFor<T>(attempt: () => T | Promise<T>, until: (value: T) => boolean | Promise<boolean>, options?: WaitForOptions<T>): Promise<T>;
@@ -0,0 +1,82 @@
1
+ import { systemClock } from '../http/retry.js';
2
+ /** Thrown when the condition did not become true in time. The message never includes results: see `lastValue` and `lastError` for debugging. */
3
+ export class WaitTimeoutError extends Error {
4
+ attempts;
5
+ elapsedMs;
6
+ lastValue;
7
+ lastError;
8
+ constructor(message, attempts, elapsedMs, lastValue, lastError) {
9
+ super(message);
10
+ this.attempts = attempts;
11
+ this.elapsedMs = elapsedMs;
12
+ this.lastValue = lastValue;
13
+ this.lastError = lastError;
14
+ this.name = 'WaitTimeoutError';
15
+ }
16
+ }
17
+ function nonNegative(value, fallback, name) {
18
+ const resolved = value ?? fallback;
19
+ if (!Number.isFinite(resolved) || resolved < 0)
20
+ throw new Error(`Invalid waitFor option: ${name} must be a non-negative number`);
21
+ return resolved;
22
+ }
23
+ function sleepUnlessAborted(clock, ms, signal) {
24
+ if (!signal)
25
+ return clock.sleep(ms);
26
+ return new Promise((resolve, reject) => {
27
+ const onAbort = () => reject(signal.reason instanceof Error ? signal.reason : new Error('waitFor was aborted'));
28
+ signal.addEventListener('abort', onAbort, { once: true });
29
+ clock.sleep(ms).then(() => { signal.removeEventListener('abort', onAbort); resolve(); }, (error) => { signal.removeEventListener('abort', onAbort); reject(error instanceof Error ? error : new Error('waitFor sleep failed')); });
30
+ });
31
+ }
32
+ /**
33
+ * Polls until a condition holds, for eventually consistent APIs: a job that finishes later, a record that appears after a delay,
34
+ * a cache that expires. Returns the first value `until` accepts, or throws `WaitTimeoutError`.
35
+ *
36
+ * ```ts
37
+ * const job = await waitFor(() => api.request({ method: 'GET', path: `/jobs/${id}` }), r => r.body.state === 'done',
38
+ * { description: 'the job to finish', describe: r => `HTTP ${r.status}`, timeoutMs: 30_000 });
39
+ * ```
40
+ */
41
+ export async function waitFor(attempt, until, options = {}) {
42
+ const clock = options.clock ?? systemClock;
43
+ const timeoutMs = nonNegative(options.timeoutMs, 10_000, 'timeoutMs');
44
+ const maxInterval = nonNegative(options.maxIntervalMs, 2_000, 'maxIntervalMs');
45
+ const factor = nonNegative(options.backoffFactor, 1, 'backoffFactor');
46
+ let interval = nonNegative(options.intervalMs, 250, 'intervalMs');
47
+ const maxAttempts = options.maxAttempts === undefined ? Number.POSITIVE_INFINITY : nonNegative(options.maxAttempts, 0, 'maxAttempts');
48
+ const started = clock.now();
49
+ let attempts = 0;
50
+ let lastValue;
51
+ let lastError;
52
+ let hasValue = false;
53
+ for (;;) {
54
+ options.signal?.throwIfAborted();
55
+ attempts++;
56
+ try {
57
+ const value = await attempt();
58
+ lastValue = value;
59
+ hasValue = true;
60
+ lastError = undefined;
61
+ if (await until(value))
62
+ return value;
63
+ }
64
+ catch (error) {
65
+ const retry = options.retryOnError === true || (typeof options.retryOnError === 'function' && options.retryOnError(error));
66
+ if (!retry)
67
+ throw error;
68
+ lastError = error;
69
+ }
70
+ const elapsed = clock.now() - started;
71
+ if (elapsed >= timeoutMs || attempts >= maxAttempts) {
72
+ let message = `Timed out after ${Math.round(elapsed)}ms and ${attempts} attempt${attempts === 1 ? '' : 's'} waiting for ${options.description ?? 'the condition to hold'}`;
73
+ if (lastError !== undefined)
74
+ message += `; the last attempt failed with ${lastError instanceof Error ? lastError.name : 'an error'}`;
75
+ else if (hasValue && options.describe)
76
+ message += `; the last result was ${options.describe(lastValue)}`;
77
+ throw new WaitTimeoutError(message, attempts, Math.round(elapsed), lastValue, lastError);
78
+ }
79
+ await sleepUnlessAborted(clock, Math.min(interval, timeoutMs - elapsed), options.signal); // never sleep past the deadline
80
+ interval = Math.min(maxInterval, interval * factor);
81
+ }
82
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nikhil-qeas/api-core",
3
- "version": "0.5.1",
3
+ "version": "0.7.0",
4
4
  "description": "Reusable TypeScript API automation core with HTTP, auth, OpenAPI adapter, test isolation, reporting and CI",
5
5
  "private": false,
6
6
  "type": "module",
@@ -16,21 +16,25 @@ The sample tests start a local mock API (`tests/support/mock-api.ts`) and need n
16
16
  | Path | Purpose |
17
17
  |---|---|
18
18
  | `openapi/openapi.json` | The API's OpenAPI document. **Replace it with your API's spec**: contract checks and coverage both read it. |
19
- | `src/clients/api.ts` | `createApiClient()`: retries with backoff and `Retry-After`, OAuth2 when `OAUTH_*` is set, metrics and coverage hooks. Add production guards and approvals here. |
20
- | `src/config/environment.ts` | Reads `API_BASE_URL` and the optional `OAUTH_*` settings. |
21
- | `src/contracts/openapi.ts` | Loads the spec and builds the Ajv-backed contract validator. |
19
+ | `src/clients/api.ts` | `createApiClient()`: read-only unless writes are approved, retries with backoff and `Retry-After`, OAuth2 when `OAUTH_*` is set, metrics and coverage hooks. |
20
+ | `src/environment.ts` | Reads `API_BASE_URL`, the optional `OAUTH_*` settings, and the write-protection policy (`QE_ENV`, `QE_ALLOW_MUTATIONS`, `QE_APPROVAL`). |
21
+ | `src/openapi.ts` | Loads the spec and builds the Ajv-backed contract validator. |
22
22
  | `src/observability.ts` | Run-wide metrics and OpenAPI coverage collectors. |
23
- | `tests/smoke`, `contract`, `security` | Working samples. Add `regression` and `negative` suites beside them. |
23
+ | `tests/smoke`, `contract`, `security`, `negative` | Working samples. Any `tests/**/*.spec.ts` is picked up, so add folders such as `tests/regression` or `tests/negative` when you need them. |
24
24
  | `tests/setup/hooks.ts` | After the run: writes `reports/coverage/api.md` and `api.json` and can enforce a minimum. |
25
25
  | `tests/support/mock-api.ts` | The local mock API and token endpoint the samples use. Delete it once you test a real environment. |
26
+ | `tests/support/approved-writes.ts`, `identities.ts` | Helpers for the generated suites: run a suite with writes approved for the mock, and send requests as one test identity (or as nobody). |
27
+ | `.mocharc.json` | Mocha settings: TypeScript specs under `tests/`, the setup hooks, a 30 second timeout. |
26
28
  | `.env.example` | Every setting, with comments. Copy to `.env` locally; use your CI secret store in pipelines. |
27
29
 
30
+ `reports/` is created by the test run and is git-ignored. The framework itself (the HTTP client, token handling, retries, contract validation and coverage) is not copied into this project: it is the `@nikhil-qeas/api-core` package in `node_modules`.
31
+
28
32
  ## Commands
29
33
 
30
34
  | Command | What it does |
31
35
  |---|---|
32
36
  | `npm test` | Every test. |
33
- | `npm run test:smoke` / `test:contract` / `test:security` | Tests whose title contains `@smoke` / `@contract` / `@security`. Tag your own `describe` titles the same way. |
37
+ | `npm run test:smoke` / `test:contract` / `test:security` / `test:negative` / `test:fuzz` | Tests whose title contains `@smoke` / `@contract` / `@security` / `@negative` / `@fuzz`. Tag your own `describe` titles the same way. |
34
38
  | `npm run test:ci` | Everything, with JUnit XML in `reports/junit/results.xml` for the pipeline. |
35
39
  | `npm run lint` | ESLint with type-aware rules: an unawaited request is a check that silently never runs. |
36
40
  | `npm run audit:security` | `npm audit` for high-severity advisories. |
@@ -44,10 +48,55 @@ contract.assertResponse({ method: 'GET', path: '/accounts/{id}', status: respons
44
48
 
45
49
  Use the spec's path template, not the concrete URL. After every run `reports/coverage/api.md` lists the operations and documented responses the suite exercised, responses the API returned that the spec does not declare, and requests that match no operation. Set `QE_COVERAGE_MIN_OPERATIONS=80` on full runs to fail when coverage drops. Coverage counts requests, not passes.
46
50
 
51
+ ## Writing your own tests
52
+
53
+ The framework ships helpers for the things API tests keep needing. The sample smoke test uses two of them; the package README (`node_modules/@nikhil-qeas/api-core/README.md`) documents all of them.
54
+
55
+ ```ts
56
+ import { match, waitFor, expectBody, expectHeader, expectJsonPath } from '@nikhil-qeas/api-core';
57
+
58
+ expectBody(response, { id: match.uuid(), status: 'open', createdAt: match.dateTime() }); // objects only need to contain what you list
59
+ expectJsonPath(response, '$.items[*].price', match.number({ min: 0 }));
60
+ expectHeader(response, 'content-type', /^application\/json/);
61
+
62
+ const done = await waitFor(() => api.request({ method: 'GET', path: `/jobs/${id}` }), r => r.body.state === 'done', { description: 'the job to finish' });
63
+ ```
64
+
65
+ `createApiClient(baseUrl, { cookies: true })` keeps session cookies, `multipart: [...]` uploads files, and `responseType: 'binary'` downloads them.
66
+
67
+ ## Negative and fuzz tests
68
+
69
+ `tests/negative/spec-cases.spec.ts` generates test cases from `openapi/openapi.json`, so they follow your spec when you replace it:
70
+
71
+ - **`@negative`**: requests that each break exactly one rule of the spec (a missing required field, the wrong type, a string too long, a bad format or enum value, a number out of range, a missing parameter, malformed JSON, an unsupported content type). Every one must be rejected with a 4xx, and a valid request must be accepted. The failure message names the rule: `body.name is shorter than minLength 1 (body.name: minLength): invalid input was accepted with HTTP 201`.
72
+ - **`@fuzz`**: hostile and extreme values in every string and number field (injection strings, null bytes, unicode tricks, huge and odd numbers, 200-level nesting, a `__proto__` key). The API must answer without failing; 2xx and 4xx are both fine, a 5xx is a defect. The choice of cases is reproducible (seeded) and capped per operation.
73
+
74
+ If the generator cannot invent a valid value (a business rule, a complex pattern), supply known-good ones: `new OpenApiCases(loadSpec(), { baselines: { 'POST /accounts': { json: { name: 'Savings', currency: 'EUR' } } } })`. Operations with multipart, form or XML bodies get parameter cases only.
75
+
76
+ **These cases send writes and hostile payloads.** The sample suite approves writes for itself because it runs against the local mock. Against a real environment, approve writes (`QE_ALLOW_MUTATIONS=true` and `QE_APPROVAL=approved`) in the shell or CI job, only for an environment where that is acceptable, and never in production.
77
+
78
+ ## Security tests
79
+
80
+ Everything under `tests/security` is tagged `@security` (`npm run test:security`):
81
+
82
+ - **`spec-cases.spec.ts`: authentication, generated from the spec.** Every operation the spec protects (`security` on the operation, or on the document and not overridden with `security: []`) must refuse a request with no credentials, an invalid bearer token or API key (in the header, query or cookie the spec names), an empty token, and credentials of the wrong type, using 401 or 403. A server that only checks that an `Authorization` header exists fails. Declare the schemes under `components.securitySchemes`.
83
+ - **`authorization.spec.ts`: who may do what.** `AuthorizationMatrix` sends each rule's request as each identity and compares the status, covering function-level checks (a normal user calling an admin operation) and object-level checks (user B reading user A's data; add `deniedStatuses: [403, 404]` when the API hides what exists). Refusals are checked first, and a failure prints a table of statuses.
84
+ - **`hygiene.spec.ts`: what a response gives away.** `expectSecurityHeaders` checks `X-Content-Type-Options`, `Strict-Transport-Security` (with `https: true`), `Cache-Control: no-store` (with `sensitive: true`), version leaks in `Server` and `X-Powered-By`, and wildcard CORS. `expectNoSensitiveData` finds properties named like secrets that carry a value, and values that look like JWTs, private keys, cloud keys or card numbers (`allowKeys` for what belongs, such as `access_token` on a login response). Failures name the header or path, never its value.
85
+
86
+ The mock API's test identities (`tests/support/identities.ts`) stand in for the test accounts of your environment. Like the negative cases, these send requests an API should refuse, so run them only against environments where that is acceptable.
87
+
88
+ ## GraphQL
89
+
90
+ `GraphQLClient` wraps the generated client: `new GraphQLClient(createApiClient()).execute({ query, variables })`, then `expectGraphQLSuccess(result)` or `expectGraphQLError(result, { code: 'FORBIDDEN' })`. A GraphQL query is a POST, but the client proves from the document that it is a query, so it is allowed in the default read-only run. A mutation is refused before it is sent, with the same read-only error as any other write, until you approve writes (see Safety below). `result.errors` matters as much as the status: a failed request is often HTTP 200. GraphQL APIs have no OpenAPI document, so their requests are listed as matching no operation in `reports/coverage/api.md`; that does not fail a run. The package README documents the details.
91
+
47
92
  ## Authentication
48
93
 
49
94
  Set `OAUTH_TOKEN_URL`, `OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET` (and optionally `OAUTH_SCOPE`) and `createApiClient()` sends a bearer token automatically. When the server answers 401 the client renews the token and resends once. Use `skipAuth: true` or your own `Authorization` header on a request for negative tests. `tests/security/authentication.spec.ts` shows both against the mock API.
50
95
 
51
96
  ## Safety
52
97
 
53
- Store credentials in your CI secret store, never in source control or logs. Writes against shared or production-like systems need their own approvals: `QE_ALLOW_MUTATIONS` stays `false` by default, and `createApiClient()` is the place to enforce environment guards. The core library's `assertRequestPolicy` and `rejectUnsafeEnvironment` help.
98
+ Store credentials in your CI secret store, never in source control or logs.
99
+
100
+ **Runs are read-only by default.** `createApiClient()` refuses POST, PUT, PATCH and DELETE before anything is sent, and the error says why. To run write tests against a safe test environment set **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`, whatever else is set. `tests/security/write-protection.spec.ts` shows each case, and checks against the mock API that a refused write never reaches the server.
101
+
102
+ These guards stop *your tests* from sending writes by accident. They do not replace access control on the system under test: use dedicated accounts and approved environments. The policy lives in `requestPolicy()` (`src/environment.ts`), where you can also pin the hosts a run may call with `allowedHosts`.
@@ -1,5 +1,10 @@
1
+ # Execution policy. Runs are READ-ONLY by default: POST, PUT, PATCH and DELETE are refused before anything is sent.
2
+ # To run write tests against a safe test environment, set QE_ALLOW_MUTATIONS=true AND QE_APPROVAL=approved.
3
+ # Writes are never allowed when QE_ENV is prod or production, and the client refuses to start with only one of the two.
1
4
  QE_ENV=local
2
5
  QE_ALLOW_MUTATIONS=false
6
+ # QE_APPROVAL=approved
7
+
3
8
  # API under test. The sample tests start their own local mock API and do not need this.
4
9
  # API_BASE_URL=https://test.example.invalid
5
10
 
@@ -8,11 +8,69 @@
8
8
  "/health": {
9
9
  "get": {
10
10
  "operationId": "health",
11
- "tags": ["ops"],
11
+ "tags": [
12
+ "ops"
13
+ ],
12
14
  "responses": {
13
15
  "200": {
14
16
  "description": "The service is up",
15
- "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Health" } } }
17
+ "content": {
18
+ "application/json": {
19
+ "schema": {
20
+ "$ref": "#/components/schemas/Health"
21
+ }
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
27
+ },
28
+ "/accounts": {
29
+ "post": {
30
+ "operationId": "createAccount",
31
+ "tags": [
32
+ "accounts"
33
+ ],
34
+ "requestBody": {
35
+ "required": true,
36
+ "content": {
37
+ "application/json": {
38
+ "schema": {
39
+ "$ref": "#/components/schemas/NewAccount"
40
+ }
41
+ }
42
+ }
43
+ },
44
+ "responses": {
45
+ "201": {
46
+ "description": "The account was created",
47
+ "content": {
48
+ "application/json": {
49
+ "schema": {
50
+ "$ref": "#/components/schemas/Account"
51
+ }
52
+ }
53
+ }
54
+ },
55
+ "400": {
56
+ "description": "The request was invalid",
57
+ "content": {
58
+ "application/json": {
59
+ "schema": {
60
+ "$ref": "#/components/schemas/Error"
61
+ }
62
+ }
63
+ }
64
+ },
65
+ "415": {
66
+ "description": "The content type is not supported",
67
+ "content": {
68
+ "application/json": {
69
+ "schema": {
70
+ "$ref": "#/components/schemas/Error"
71
+ }
72
+ }
73
+ }
16
74
  }
17
75
  }
18
76
  }
@@ -20,16 +78,39 @@
20
78
  "/accounts/{id}": {
21
79
  "get": {
22
80
  "operationId": "getAccount",
23
- "tags": ["accounts"],
24
- "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
81
+ "tags": [
82
+ "accounts"
83
+ ],
84
+ "parameters": [
85
+ {
86
+ "name": "id",
87
+ "in": "path",
88
+ "required": true,
89
+ "schema": {
90
+ "type": "string"
91
+ }
92
+ }
93
+ ],
25
94
  "responses": {
26
95
  "200": {
27
96
  "description": "The account",
28
- "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Account" } } }
97
+ "content": {
98
+ "application/json": {
99
+ "schema": {
100
+ "$ref": "#/components/schemas/Account"
101
+ }
102
+ }
103
+ }
29
104
  },
30
105
  "404": {
31
106
  "description": "No such account",
32
- "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
107
+ "content": {
108
+ "application/json": {
109
+ "schema": {
110
+ "$ref": "#/components/schemas/Error"
111
+ }
112
+ }
113
+ }
33
114
  }
34
115
  }
35
116
  }
@@ -37,15 +118,79 @@
37
118
  "/secure/profile": {
38
119
  "get": {
39
120
  "operationId": "getProfile",
40
- "tags": ["security"],
121
+ "tags": [
122
+ "security"
123
+ ],
124
+ "security": [
125
+ {
126
+ "bearerAuth": []
127
+ }
128
+ ],
41
129
  "responses": {
42
130
  "200": {
43
131
  "description": "The authenticated caller",
44
- "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Profile" } } }
132
+ "content": {
133
+ "application/json": {
134
+ "schema": {
135
+ "$ref": "#/components/schemas/Profile"
136
+ }
137
+ }
138
+ }
45
139
  },
46
140
  "401": {
47
141
  "description": "Missing or invalid access token",
48
- "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
142
+ "content": {
143
+ "application/json": {
144
+ "schema": {
145
+ "$ref": "#/components/schemas/Error"
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+ },
153
+ "/admin/stats": {
154
+ "get": {
155
+ "operationId": "getAdminStats",
156
+ "tags": [
157
+ "security"
158
+ ],
159
+ "security": [
160
+ {
161
+ "bearerAuth": []
162
+ }
163
+ ],
164
+ "responses": {
165
+ "200": {
166
+ "description": "Statistics only an administrator may read",
167
+ "content": {
168
+ "application/json": {
169
+ "schema": {
170
+ "$ref": "#/components/schemas/Stats"
171
+ }
172
+ }
173
+ }
174
+ },
175
+ "401": {
176
+ "description": "Missing or invalid access token",
177
+ "content": {
178
+ "application/json": {
179
+ "schema": {
180
+ "$ref": "#/components/schemas/Error"
181
+ }
182
+ }
183
+ }
184
+ },
185
+ "403": {
186
+ "description": "The caller is not an administrator",
187
+ "content": {
188
+ "application/json": {
189
+ "schema": {
190
+ "$ref": "#/components/schemas/Error"
191
+ }
192
+ }
193
+ }
49
194
  }
50
195
  }
51
196
  }
@@ -55,28 +200,107 @@
55
200
  "schemas": {
56
201
  "Health": {
57
202
  "type": "object",
58
- "required": ["status"],
59
- "properties": { "status": { "type": "string", "enum": ["ok"] } }
203
+ "required": [
204
+ "status"
205
+ ],
206
+ "properties": {
207
+ "status": {
208
+ "type": "string",
209
+ "enum": [
210
+ "ok"
211
+ ]
212
+ }
213
+ }
214
+ },
215
+ "NewAccount": {
216
+ "type": "object",
217
+ "required": [
218
+ "name",
219
+ "currency"
220
+ ],
221
+ "additionalProperties": false,
222
+ "properties": {
223
+ "name": {
224
+ "type": "string",
225
+ "minLength": 1,
226
+ "maxLength": 50
227
+ },
228
+ "currency": {
229
+ "type": "string",
230
+ "enum": [
231
+ "USD",
232
+ "EUR",
233
+ "GBP"
234
+ ]
235
+ },
236
+ "initialDeposit": {
237
+ "type": "number",
238
+ "minimum": 0
239
+ }
240
+ }
60
241
  },
61
242
  "Account": {
62
243
  "type": "object",
63
- "required": ["id", "status"],
244
+ "required": [
245
+ "id",
246
+ "status"
247
+ ],
64
248
  "additionalProperties": false,
65
249
  "properties": {
66
- "id": { "type": "string" },
67
- "status": { "type": "string", "enum": ["open", "closed"] },
68
- "balance": { "type": "number" }
250
+ "id": {
251
+ "type": "string"
252
+ },
253
+ "status": {
254
+ "type": "string",
255
+ "enum": [
256
+ "open",
257
+ "closed"
258
+ ]
259
+ },
260
+ "balance": {
261
+ "type": "number"
262
+ }
69
263
  }
70
264
  },
71
265
  "Profile": {
72
266
  "type": "object",
73
- "required": ["user"],
74
- "properties": { "user": { "type": "string" } }
267
+ "required": [
268
+ "user"
269
+ ],
270
+ "properties": {
271
+ "user": {
272
+ "type": "string"
273
+ }
274
+ }
75
275
  },
76
276
  "Error": {
77
277
  "type": "object",
78
- "required": ["error"],
79
- "properties": { "error": { "type": "string" } }
278
+ "required": [
279
+ "error"
280
+ ],
281
+ "properties": {
282
+ "error": {
283
+ "type": "string"
284
+ }
285
+ }
286
+ },
287
+ "Stats": {
288
+ "type": "object",
289
+ "required": [
290
+ "accounts"
291
+ ],
292
+ "properties": {
293
+ "accounts": {
294
+ "type": "integer",
295
+ "minimum": 0
296
+ }
297
+ }
298
+ }
299
+ },
300
+ "securitySchemes": {
301
+ "bearerAuth": {
302
+ "type": "http",
303
+ "scheme": "bearer"
80
304
  }
81
305
  }
82
306
  }
@@ -1,6 +1,6 @@
1
- import { ApiClient, TokenManager, clientCredentialsProvider } from '@nikhil-qeas/api-core';
2
- import type { ApiClientConfig } from '@nikhil-qeas/api-core';
3
- import { oauthSettings, targetBaseUrl } from '../config/environment.js';
1
+ import { ApiClient, TokenManager, assertRequestPolicy, clientCredentialsProvider } from '@nikhil-qeas/api-core';
2
+ import type { ApiClientConfig, ApiRequest, ApiResult, SecurityPolicy } from '@nikhil-qeas/api-core';
3
+ import { oauthSettings, requestPolicy, targetBaseUrl } from '../environment.js';
4
4
  import { recordEvent } from '../observability.js';
5
5
 
6
6
  let sharedTokens: TokenManager | undefined;
@@ -12,21 +12,42 @@ function tokensFromEnvironment(): TokenManager | undefined {
12
12
  return sharedTokens;
13
13
  }
14
14
 
15
+ /** An ApiClient that refuses requests the execution policy does not allow (writes in a read-only run) before anything is sent. */
16
+ class PolicyEnforcingClient extends ApiClient {
17
+ private readonly target: string;
18
+ constructor(config: ApiClientConfig, private readonly policy: SecurityPolicy) {
19
+ super(config);
20
+ this.target = config.baseUrl;
21
+ }
22
+ override async request<T = unknown>(req: ApiRequest): Promise<ApiResult<T>> {
23
+ try {
24
+ assertRequestPolicy(this.target, req, this.policy);
25
+ } catch (error) {
26
+ throw new Error(
27
+ `Blocked ${req.method} ${req.path}: this run is read-only. Writes need QE_ALLOW_MUTATIONS=true and QE_APPROVAL=approved, and are never allowed when QE_ENV is prod or production.`,
28
+ { cause: error }
29
+ );
30
+ }
31
+ return await super.request<T>(req);
32
+ }
33
+ }
34
+
15
35
  /**
16
36
  * Client for the API under test.
37
+ * - Read-only unless QE_ALLOW_MUTATIONS=true and QE_APPROVAL=approved (never in production): see requestPolicy().
17
38
  * - Retries safe requests with backoff and honors Retry-After; mutations are never retried after an ambiguous failure.
18
39
  * - Authenticates with OAuth2 client credentials when OAUTH_* is configured, and renews the token once on a 401.
19
40
  * - Feeds every request to the metrics and OpenAPI coverage collectors.
20
- * Add project-specific approvals (production guards, allowed hosts) here before connecting real environments.
21
41
  */
22
42
  export function createApiClient(baseUrl: string = targetBaseUrl(), overrides: Partial<ApiClientConfig> = {}): ApiClient {
43
+ const policy = requestPolicy(); // throws for an unsafe QE_* combination, before a client exists
23
44
  const tokens = tokensFromEnvironment();
24
- return new ApiClient({
45
+ return new PolicyEnforcingClient({
25
46
  baseUrl,
26
47
  timeoutMs: 15_000,
27
48
  maxSafeRetries: 1,
28
49
  onEvent: recordEvent,
29
50
  ...(tokens ? { auth: { tokens } } : {}),
30
51
  ...overrides
31
- });
52
+ }, policy);
32
53
  }
@@ -1,4 +1,5 @@
1
- import { requireEnv } from '@nikhil-qeas/api-core';
1
+ import { rejectUnsafeEnvironment, requireEnv } from '@nikhil-qeas/api-core';
2
+ import type { SecurityPolicy } from '@nikhil-qeas/api-core';
2
3
 
3
4
  /** Base URL of the API under test (API_BASE_URL). */
4
5
  export function targetBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
@@ -27,3 +28,17 @@ export function oauthSettings(env: NodeJS.ProcessEnv = process.env): OAuthSettin
27
28
  ...(env.OAUTH_SCOPE ? { scope: env.OAUTH_SCOPE } : {})
28
29
  };
29
30
  }
31
+
32
+ /**
33
+ * What the run may send (QE_ENV, QE_ALLOW_MUTATIONS, QE_APPROVAL).
34
+ * Runs are read-only: POST, PUT, PATCH and DELETE are refused unless QE_ALLOW_MUTATIONS=true and QE_APPROVAL=approved,
35
+ * and never when QE_ENV is prod or production. An unsafe combination throws immediately, before any client exists.
36
+ * Add `allowedHosts: ['test.example.com']` here to pin the hosts a run may call.
37
+ */
38
+ export function requestPolicy(env: NodeJS.ProcessEnv = process.env): SecurityPolicy {
39
+ rejectUnsafeEnvironment(env);
40
+ return {
41
+ production: ['prod', 'production'].includes(env.QE_ENV ?? ''),
42
+ allowDestructive: env.QE_ALLOW_MUTATIONS === 'true'
43
+ };
44
+ }
@@ -1,6 +1,6 @@
1
1
  import { MetricsCollector, OpenApiCoverage } from '@nikhil-qeas/api-core';
2
2
  import type { HttpEvent } from '@nikhil-qeas/api-core';
3
- import { loadSpec } from './contracts/openapi.js';
3
+ import { loadSpec } from './openapi.js';
4
4
 
5
5
  /** Request timings, errors and retry counts for the whole run. */
6
6
  export const metrics = new MetricsCollector();
@@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs';
2
2
  import { createOpenApiValidator } from '@nikhil-qeas/api-core';
3
3
  import type { OpenApiDocument, OpenApiValidator } from '@nikhil-qeas/api-core';
4
4
 
5
- const SPEC_FILE = new URL('../../openapi/openapi.json', import.meta.url);
5
+ const SPEC_FILE = new URL('../openapi/openapi.json', import.meta.url);
6
6
 
7
7
  /** The OpenAPI document that contract checks and coverage use. Replace openapi/openapi.json with your API's spec. */
8
8
  export function loadSpec(): OpenApiDocument {
@@ -1,6 +1,6 @@
1
1
  import type { ApiResult, OpenApiValidator } from '@nikhil-qeas/api-core';
2
2
  import { createApiClient } from '../../src/clients/api.js';
3
- import { contractValidator } from '../../src/contracts/openapi.js';
3
+ import { contractValidator } from '../../src/openapi.js';
4
4
  import { startMockApi } from '../support/mock-api.js';
5
5
  import type { MockApi } from '../support/mock-api.js';
6
6