@nikhil-qeas/api-core 0.5.1 → 0.6.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 +18 -0
- package/README.md +3 -3
- package/bin/qe-api.js +2 -4
- package/package.json +1 -1
- package/templates/project/README.md +12 -5
- package/templates/project/__dot__env.example +5 -0
- 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/security/write-protection.spec.ts +60 -0
- package/templates/project/tests/support/mock-api.ts +5 -0
- /package/templates/project/{config/mocha.config.json → __dot__mocharc.json} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
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.6.0] - 2026-11-23
|
|
6
|
+
|
|
7
|
+
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.
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- **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.
|
|
12
|
+
- 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.
|
|
13
|
+
- 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.
|
|
14
|
+
- 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`.
|
|
15
|
+
- Existing generated projects are unaffected. New projects get the new layout.
|
|
16
|
+
- **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`.
|
|
17
|
+
|
|
18
|
+
### Notes for upgrading
|
|
19
|
+
|
|
20
|
+
- **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.
|
|
21
|
+
- **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.
|
|
22
|
+
|
|
5
23
|
## [0.5.1] - 2026-11-23
|
|
6
24
|
|
|
7
25
|
### 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.6.0 qe-api init my-api-project
|
|
11
11
|
cd my-api-project
|
|
12
12
|
npm install
|
|
13
13
|
npm run check
|
|
@@ -15,7 +15,7 @@ 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
20
|
- working `@smoke`, `@contract` and `@security` samples, including a token-renewal scenario and negative authentication tests;
|
|
21
21
|
- ESLint with type-aware rules, `npm audit`, JUnit output and a GitLab CI pipeline.
|
|
@@ -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.6.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.
|
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;
|
|
@@ -73,7 +72,6 @@ function projectFiles(name) {
|
|
|
73
72
|
for (const path of templateFiles(TEMPLATE_DIR)) {
|
|
74
73
|
files.set(outputPath(path), readFileSync(join(TEMPLATE_DIR, path), 'utf8').replaceAll('__PROJECT_NAME__', name));
|
|
75
74
|
}
|
|
76
|
-
for (const directory of EMPTY_DIRS) files.set(`${directory}/.gitkeep`, '');
|
|
77
75
|
return files;
|
|
78
76
|
}
|
|
79
77
|
|
package/package.json
CHANGED
|
@@ -16,15 +16,18 @@ 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.
|
|
20
|
-
| `src/
|
|
21
|
-
| `src/
|
|
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.
|
|
23
|
+
| `tests/smoke`, `contract`, `security` | 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
|
+
| `.mocharc.json` | Mocha settings: TypeScript specs under `tests/`, the setup hooks, a 30 second timeout. |
|
|
26
27
|
| `.env.example` | Every setting, with comments. Copy to `.env` locally; use your CI secret store in pipelines. |
|
|
27
28
|
|
|
29
|
+
`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`.
|
|
30
|
+
|
|
28
31
|
## Commands
|
|
29
32
|
|
|
30
33
|
| Command | What it does |
|
|
@@ -50,4 +53,8 @@ Set `OAUTH_TOKEN_URL`, `OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET` (and optionally
|
|
|
50
53
|
|
|
51
54
|
## Safety
|
|
52
55
|
|
|
53
|
-
Store credentials in your CI secret store, never in source control or logs.
|
|
56
|
+
Store credentials in your CI secret store, never in source control or logs.
|
|
57
|
+
|
|
58
|
+
**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.
|
|
59
|
+
|
|
60
|
+
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
|
|
|
@@ -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 '../
|
|
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
|
|
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 './
|
|
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('
|
|
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/
|
|
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
|
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { expectStatus } from '@nikhil-qeas/api-core';
|
|
3
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
4
|
+
import { requestPolicy } from '../../src/environment.js';
|
|
5
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
6
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
7
|
+
|
|
8
|
+
const SETTINGS = ['QE_ENV', 'QE_ALLOW_MUTATIONS', 'QE_APPROVAL'] as const;
|
|
9
|
+
|
|
10
|
+
/** Runs the body with exactly these QE_* settings, whatever the surrounding shell has set, and restores them afterwards. */
|
|
11
|
+
async function withSettings(values: Partial<Record<(typeof SETTINGS)[number], string>>, body: () => void | Promise<void>): Promise<void> {
|
|
12
|
+
const saved = SETTINGS.map(name => [name, process.env[name]] as const);
|
|
13
|
+
for (const name of SETTINGS) delete process.env[name];
|
|
14
|
+
Object.assign(process.env, values);
|
|
15
|
+
try {
|
|
16
|
+
await body();
|
|
17
|
+
} finally {
|
|
18
|
+
for (const [name, value] of saved) {
|
|
19
|
+
if (value === undefined) delete process.env[name];
|
|
20
|
+
else process.env[name] = value;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('@security write protection', () => {
|
|
26
|
+
let mock: MockApi;
|
|
27
|
+
before(async () => { mock = await startMockApi(); });
|
|
28
|
+
after(async () => { await mock.close(); });
|
|
29
|
+
|
|
30
|
+
// Requests here are not recorded for OpenAPI coverage: the mock has no write routes.
|
|
31
|
+
const client = () => createApiClient(mock.baseUrl, { onEvent: () => undefined });
|
|
32
|
+
|
|
33
|
+
it('is read-only by default: writes are refused before anything is sent, reads still work', () => withSettings({}, async () => {
|
|
34
|
+
const api = client();
|
|
35
|
+
await assert.rejects(api.request({ method: 'POST', path: '/accounts', json: { id: 1 } }), /Blocked POST \/accounts: this run is read-only/);
|
|
36
|
+
for (const method of ['PUT', 'PATCH', 'DELETE'] as const) {
|
|
37
|
+
await assert.rejects(api.request({ method, path: '/accounts/1' }), /read-only/, method);
|
|
38
|
+
}
|
|
39
|
+
assert.deepEqual(mock.requests().filter(request => !request.startsWith('GET ') && request !== 'POST /oauth/token'), [], 'a refused write must never reach the server');
|
|
40
|
+
expectStatus(await api.request({ method: 'GET', path: '/health' }), 200);
|
|
41
|
+
}));
|
|
42
|
+
|
|
43
|
+
it('lets writes through only with both QE_ALLOW_MUTATIONS=true and QE_APPROVAL=approved', () => withSettings({ QE_ALLOW_MUTATIONS: 'true', QE_APPROVAL: 'approved' }, async () => {
|
|
44
|
+
const response = await client().request({ method: 'POST', path: '/accounts', json: { id: 1 } });
|
|
45
|
+
expectStatus(response, 404); // the mock has no such route, but the request was sent
|
|
46
|
+
assert.ok(mock.requests().includes('POST /accounts'));
|
|
47
|
+
}));
|
|
48
|
+
|
|
49
|
+
it('refuses to start when mutations are allowed without approval', () => withSettings({ QE_ALLOW_MUTATIONS: 'true' }, () => {
|
|
50
|
+
assert.throws(() => createApiClient(mock.baseUrl), /QE_APPROVAL=approved/);
|
|
51
|
+
}));
|
|
52
|
+
|
|
53
|
+
it('never allows mutations in production, even with approval', () => {
|
|
54
|
+
for (const environment of ['prod', 'production']) {
|
|
55
|
+
assert.throws(() => requestPolicy({ QE_ENV: environment, QE_ALLOW_MUTATIONS: 'true', QE_APPROVAL: 'approved' }), /forbidden in production/, environment);
|
|
56
|
+
}
|
|
57
|
+
assert.deepEqual(requestPolicy({ QE_ENV: 'prod' }), { production: true, allowDestructive: false });
|
|
58
|
+
assert.deepEqual(requestPolicy({}), { production: false, allowDestructive: false });
|
|
59
|
+
});
|
|
60
|
+
});
|
|
@@ -11,6 +11,8 @@ export interface MockApi {
|
|
|
11
11
|
tokensIssued(): number;
|
|
12
12
|
/** Invalidate the current access token on the server, as an expiry or revocation would. */
|
|
13
13
|
revokeTokens(): void;
|
|
14
|
+
/** Every request the server received, as "METHOD /path". Shows that a refused request was never sent. */
|
|
15
|
+
requests(): readonly string[];
|
|
14
16
|
close(): Promise<void>;
|
|
15
17
|
}
|
|
16
18
|
|
|
@@ -23,9 +25,11 @@ function send(res: ServerResponse, status: number, body: unknown): void {
|
|
|
23
25
|
export async function startMockApi(): Promise<MockApi> {
|
|
24
26
|
let issued = 0;
|
|
25
27
|
let validToken: string | undefined;
|
|
28
|
+
const received: string[] = [];
|
|
26
29
|
const server = createServer((req, res) => {
|
|
27
30
|
req.resume();
|
|
28
31
|
const { pathname } = new URL(req.url ?? '/', 'http://localhost');
|
|
32
|
+
received.push(`${req.method ?? ''} ${pathname}`);
|
|
29
33
|
if (req.method === 'POST' && pathname === '/oauth/token') {
|
|
30
34
|
issued++;
|
|
31
35
|
validToken = `tok-${issued}`;
|
|
@@ -58,6 +62,7 @@ export async function startMockApi(): Promise<MockApi> {
|
|
|
58
62
|
tokenUrl: `${origin}/oauth/token`,
|
|
59
63
|
tokensIssued: () => issued,
|
|
60
64
|
revokeTokens: () => { validToken = undefined; },
|
|
65
|
+
requests: () => received,
|
|
61
66
|
close: () => new Promise<void>(resolve => {
|
|
62
67
|
server.closeAllConnections();
|
|
63
68
|
server.close(() => resolve());
|
|
File without changes
|