@nikhil-qeas/api-core 0.6.0 → 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 +34 -0
- package/README.md +140 -4
- package/bin/qe-api.js +2 -0
- package/dist/contracts/assertions.d.ts +11 -0
- package/dist/contracts/assertions.js +31 -0
- package/dist/contracts/openapi.d.ts +28 -1
- package/dist/contracts/openapi.js +113 -0
- package/dist/graphql/graphql.d.ts +86 -0
- package/dist/graphql/graphql.js +312 -0
- package/dist/http/api-client.d.ts +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 +44 -2
- package/templates/project/openapi/openapi.json +243 -19
- 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 +2 -2
- 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 +57 -3
|
@@ -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
|
@@ -20,9 +20,10 @@ The sample tests start a local mock API (`tests/support/mock-api.ts`) and need n
|
|
|
20
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
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. Any `tests/**/*.spec.ts` is picked up, so add folders such as `tests/regression` or `tests/negative` when you need 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). |
|
|
26
27
|
| `.mocharc.json` | Mocha settings: TypeScript specs under `tests/`, the setup hooks, a 30 second timeout. |
|
|
27
28
|
| `.env.example` | Every setting, with comments. Copy to `.env` locally; use your CI secret store in pipelines. |
|
|
28
29
|
|
|
@@ -33,7 +34,7 @@ The sample tests start a local mock API (`tests/support/mock-api.ts`) and need n
|
|
|
33
34
|
| Command | What it does |
|
|
34
35
|
|---|---|
|
|
35
36
|
| `npm test` | Every test. |
|
|
36
|
-
| `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. |
|
|
37
38
|
| `npm run test:ci` | Everything, with JUnit XML in `reports/junit/results.xml` for the pipeline. |
|
|
38
39
|
| `npm run lint` | ESLint with type-aware rules: an unawaited request is a check that silently never runs. |
|
|
39
40
|
| `npm run audit:security` | `npm audit` for high-severity advisories. |
|
|
@@ -47,6 +48,47 @@ contract.assertResponse({ method: 'GET', path: '/accounts/{id}', status: respons
|
|
|
47
48
|
|
|
48
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.
|
|
49
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
|
+
|
|
50
92
|
## Authentication
|
|
51
93
|
|
|
52
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.
|
|
@@ -8,11 +8,69 @@
|
|
|
8
8
|
"/health": {
|
|
9
9
|
"get": {
|
|
10
10
|
"operationId": "health",
|
|
11
|
-
"tags": [
|
|
11
|
+
"tags": [
|
|
12
|
+
"ops"
|
|
13
|
+
],
|
|
12
14
|
"responses": {
|
|
13
15
|
"200": {
|
|
14
16
|
"description": "The service is up",
|
|
15
|
-
"content": {
|
|
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": [
|
|
24
|
-
|
|
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": {
|
|
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": {
|
|
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": [
|
|
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": {
|
|
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": {
|
|
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": [
|
|
59
|
-
|
|
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": [
|
|
244
|
+
"required": [
|
|
245
|
+
"id",
|
|
246
|
+
"status"
|
|
247
|
+
],
|
|
64
248
|
"additionalProperties": false,
|
|
65
249
|
"properties": {
|
|
66
|
-
"id": {
|
|
67
|
-
|
|
68
|
-
|
|
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": [
|
|
74
|
-
|
|
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": [
|
|
79
|
-
|
|
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
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { OpenApiCases, assertCaseOutcome } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
3
|
+
import { loadSpec } from '../../src/openapi.js';
|
|
4
|
+
import { useMockWithApprovedWrites } from '../support/approved-writes.js';
|
|
5
|
+
|
|
6
|
+
// Test cases generated from openapi/openapi.json, so they follow the spec when you replace it:
|
|
7
|
+
// @negative requests that each break one rule of the spec (missing field, wrong type, too long, bad format, ...) must be rejected with a 4xx.
|
|
8
|
+
// @fuzz hostile and extreme values (injection strings, huge or odd numbers, deep nesting) must not make the API fail with a 5xx.
|
|
9
|
+
// If an API needs values the generator cannot invent (business rules, complex patterns), give it known-good ones:
|
|
10
|
+
// new OpenApiCases(loadSpec(), { baselines: { 'POST /accounts': { json: { name: 'Savings', currency: 'EUR' } } } })
|
|
11
|
+
const cases = new OpenApiCases(loadSpec());
|
|
12
|
+
|
|
13
|
+
// These cases send POST, PUT, PATCH and DELETE, so the suite approves writes for itself while it runs against the local mock
|
|
14
|
+
// (see tests/support/approved-writes.ts). Against a real environment, approve writes in the shell or the CI job, never in code.
|
|
15
|
+
|
|
16
|
+
describe('@negative requests the spec forbids are rejected', () => {
|
|
17
|
+
const mock = useMockWithApprovedWrites();
|
|
18
|
+
for (const operation of cases.operations()) {
|
|
19
|
+
const negative = cases.negative(operation);
|
|
20
|
+
if (!negative.length) continue;
|
|
21
|
+
describe(`${operation.method} ${operation.path}`, () => {
|
|
22
|
+
it('accepts a valid request', async () => {
|
|
23
|
+
const valid = cases.valid(operation);
|
|
24
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(valid.request), valid);
|
|
25
|
+
});
|
|
26
|
+
for (const testCase of negative) {
|
|
27
|
+
it(testCase.description, async () => {
|
|
28
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(testCase.request), testCase);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe('@fuzz hostile input does not crash the API', () => {
|
|
36
|
+
const mock = useMockWithApprovedWrites();
|
|
37
|
+
for (const operation of cases.operations()) {
|
|
38
|
+
const fuzz = cases.fuzz(operation);
|
|
39
|
+
if (!fuzz.length) continue;
|
|
40
|
+
describe(`${operation.method} ${operation.path}`, () => {
|
|
41
|
+
for (const testCase of fuzz) {
|
|
42
|
+
it(testCase.description, async () => {
|
|
43
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(testCase.request), testCase);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { AuthorizationMatrix } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { actingAs, TOKENS } from '../support/identities.js';
|
|
3
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
4
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
5
|
+
|
|
6
|
+
// Who may do what. Each rule lists the identities that must be allowed and the ones that must be refused; the matrix sends the
|
|
7
|
+
// request as each of them. Refusals are checked first, so a request that wrongly succeeds for the wrong identity is reported on
|
|
8
|
+
// its own line. Failures print a table of statuses, never response bodies.
|
|
9
|
+
//
|
|
10
|
+
// Object-level authorization works the same way: give each identity its own resource and refuse the others, e.g.
|
|
11
|
+
// { name: "alice's account", request: { method: 'GET', path: '/accounts/123' }, allow: ['alice'], deny: ['bob'], deniedStatuses: [403, 404] }
|
|
12
|
+
// (use disposable resources for rules that change data, and approve writes as the write-protection test shows).
|
|
13
|
+
describe('@security authorization', () => {
|
|
14
|
+
let mock: MockApi;
|
|
15
|
+
before(async () => { mock = await startMockApi(); });
|
|
16
|
+
after(async () => { await mock.close(); });
|
|
17
|
+
|
|
18
|
+
it('lets only administrators read admin data, and everyone read public data', async () => {
|
|
19
|
+
const matrix = new AuthorizationMatrix({
|
|
20
|
+
admin: actingAs(mock.baseUrl, TOKENS.admin),
|
|
21
|
+
user: actingAs(mock.baseUrl, TOKENS.user),
|
|
22
|
+
anonymous: actingAs(mock.baseUrl)
|
|
23
|
+
});
|
|
24
|
+
await matrix.assert([
|
|
25
|
+
{ request: { method: 'GET', path: '/admin/stats' }, allow: ['admin'], deny: ['user', 'anonymous'] },
|
|
26
|
+
{ name: 'health check is public', request: { method: 'GET', path: '/health' }, allow: ['admin', 'user', 'anonymous'] }
|
|
27
|
+
]);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { expectNoSensitiveData, expectSecurityHeaders, expectStatus } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
3
|
+
import { actingAs, TOKENS } from '../support/identities.js';
|
|
4
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
5
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
6
|
+
|
|
7
|
+
// Response hygiene: what an API sends back besides the answer. Failure messages name the header or the path, never its value.
|
|
8
|
+
// expectSecurityHeaders x-content-type-options, Strict-Transport-Security (https: true), Cache-Control no-store (sensitive: true),
|
|
9
|
+
// version leaks in Server / X-Powered-By, and a wildcard CORS origin. Fails at medium severity by default.
|
|
10
|
+
// expectNoSensitiveData properties named like secrets that carry a value, and values that look like JWTs, keys or card numbers.
|
|
11
|
+
// Allow what belongs, e.g. { allowKeys: ['access_token'] } on a login response.
|
|
12
|
+
describe('@security response hygiene', () => {
|
|
13
|
+
let mock: MockApi;
|
|
14
|
+
before(async () => { mock = await startMockApi(); });
|
|
15
|
+
after(async () => { await mock.close(); });
|
|
16
|
+
|
|
17
|
+
it('sends the baseline security headers', async () => {
|
|
18
|
+
const response = await createApiClient(mock.baseUrl).request({ method: 'GET', path: '/health' });
|
|
19
|
+
expectStatus(response, 200);
|
|
20
|
+
expectSecurityHeaders(response); // add { https: true } when the API is served over https
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('marks a response with restricted data as not cacheable', async () => {
|
|
24
|
+
const response = await actingAs(mock.baseUrl, TOKENS.admin).request({ method: 'GET', path: '/admin/stats' });
|
|
25
|
+
expectStatus(response, 200);
|
|
26
|
+
expectSecurityHeaders(response, { sensitive: true });
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('does not expose secrets in what it returns', async () => {
|
|
30
|
+
const api = actingAs(mock.baseUrl, TOKENS.admin);
|
|
31
|
+
for (const path of ['/accounts/acc-1', '/admin/stats']) {
|
|
32
|
+
const response = await api.request({ method: 'GET', path });
|
|
33
|
+
expectStatus(response, 200);
|
|
34
|
+
expectNoSensitiveData(response);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { OpenApiCases, assertCaseOutcome } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
3
|
+
import { loadSpec } from '../../src/openapi.js';
|
|
4
|
+
import { useMockWithApprovedWrites } from '../support/approved-writes.js';
|
|
5
|
+
|
|
6
|
+
// Authentication cases generated from the security schemes in openapi/openapi.json. Every operation that requires credentials
|
|
7
|
+
// must refuse a request with none, with an invalid token or API key, and with credentials of the wrong type, using 401 or 403.
|
|
8
|
+
// A server that only checks that an Authorization header exists fails these cases. Public operations (`security: []`) are skipped.
|
|
9
|
+
const cases = new OpenApiCases(loadSpec());
|
|
10
|
+
|
|
11
|
+
describe('@security protected operations refuse missing and wrong credentials', () => {
|
|
12
|
+
const mock = useMockWithApprovedWrites();
|
|
13
|
+
for (const operation of cases.operations()) {
|
|
14
|
+
const security = cases.security(operation);
|
|
15
|
+
if (!security.length) continue;
|
|
16
|
+
describe(`${operation.method} ${operation.path}`, () => {
|
|
17
|
+
for (const testCase of security) {
|
|
18
|
+
it(testCase.description, async () => {
|
|
19
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(testCase.request), testCase);
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
});
|