@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
|
@@ -27,7 +27,7 @@ describe('@security write protection', () => {
|
|
|
27
27
|
before(async () => { mock = await startMockApi(); });
|
|
28
28
|
after(async () => { await mock.close(); });
|
|
29
29
|
|
|
30
|
-
// Requests here are not recorded for OpenAPI coverage: the
|
|
30
|
+
// Requests here are not recorded for OpenAPI coverage: they exist to test the guard, not the API.
|
|
31
31
|
const client = () => createApiClient(mock.baseUrl, { onEvent: () => undefined });
|
|
32
32
|
|
|
33
33
|
it('is read-only by default: writes are refused before anything is sent, reads still work', () => withSettings({}, async () => {
|
|
@@ -42,7 +42,7 @@ describe('@security write protection', () => {
|
|
|
42
42
|
|
|
43
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
44
|
const response = await client().request({ method: 'POST', path: '/accounts', json: { id: 1 } });
|
|
45
|
-
expectStatus(response,
|
|
45
|
+
expectStatus(response, 400); // the mock rejects this body, but the request was sent
|
|
46
46
|
assert.ok(mock.requests().includes('POST /accounts'));
|
|
47
47
|
}));
|
|
48
48
|
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { expectStatus } from '@nikhil-qeas/api-core';
|
|
1
|
+
import { expectBody, expectHeader, expectStatus } from '@nikhil-qeas/api-core';
|
|
3
2
|
import { createApiClient } from '../../src/clients/api.js';
|
|
4
3
|
import { startMockApi } from '../support/mock-api.js';
|
|
5
4
|
import type { MockApi } from '../support/mock-api.js';
|
|
@@ -12,6 +11,7 @@ describe('@smoke API health', () => {
|
|
|
12
11
|
it('answers the health check', async () => {
|
|
13
12
|
const response = await createApiClient(mock.baseUrl).request({ method: 'GET', path: '/health' });
|
|
14
13
|
expectStatus(response, 200);
|
|
15
|
-
|
|
14
|
+
expectHeader(response, 'content-type', /^application\/json/);
|
|
15
|
+
expectBody(response, { status: 'ok' });
|
|
16
16
|
});
|
|
17
17
|
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { startMockApi } from './mock-api.js';
|
|
2
|
+
import type { MockApi } from './mock-api.js';
|
|
3
|
+
|
|
4
|
+
const APPROVAL = { QE_ALLOW_MUTATIONS: 'true', QE_APPROVAL: 'approved' } as const;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Starts the local mock API for a suite and approves writes while it runs: generated negative, fuzz and security cases send
|
|
8
|
+
* POST, PUT, PATCH and DELETE. The approval is for this suite against this mock only. Against a real environment, approve
|
|
9
|
+
* writes for that environment in the shell or the CI job (never in code), and only where hostile writes are acceptable.
|
|
10
|
+
*/
|
|
11
|
+
export function useMockWithApprovedWrites(): () => MockApi {
|
|
12
|
+
let mock: MockApi;
|
|
13
|
+
let saved: Array<[string, string | undefined]> = [];
|
|
14
|
+
before(async () => {
|
|
15
|
+
mock = await startMockApi();
|
|
16
|
+
saved = Object.keys(APPROVAL).map(name => [name, process.env[name]]);
|
|
17
|
+
Object.assign(process.env, APPROVAL);
|
|
18
|
+
});
|
|
19
|
+
after(async () => {
|
|
20
|
+
for (const [name, value] of saved) {
|
|
21
|
+
if (value === undefined) delete process.env[name];
|
|
22
|
+
else process.env[name] = value;
|
|
23
|
+
}
|
|
24
|
+
await mock.close();
|
|
25
|
+
});
|
|
26
|
+
return () => mock;
|
|
27
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ApiRequest, ApiResult } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
3
|
+
|
|
4
|
+
/** The access tokens of the local mock API's test identities. Replace them with the test accounts of the environment you test. */
|
|
5
|
+
export const TOKENS = { admin: 'admin-token', user: 'user-token' } as const;
|
|
6
|
+
|
|
7
|
+
export interface Identity {
|
|
8
|
+
request<T = unknown>(request: ApiRequest): Promise<ApiResult<T>>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A client that sends every request as one identity, or as nobody when no token is given, whatever OAUTH_* is configured.
|
|
13
|
+
* Authorization checks compare what each identity may do, so each one must send exactly its own credentials.
|
|
14
|
+
*/
|
|
15
|
+
export function actingAs(baseUrl: string, token?: string): Identity {
|
|
16
|
+
const api = createApiClient(baseUrl);
|
|
17
|
+
return {
|
|
18
|
+
request: <T = unknown>(request: ApiRequest) => api.request<T>({
|
|
19
|
+
...request,
|
|
20
|
+
skipAuth: true,
|
|
21
|
+
headers: { ...request.headers, ...(token === undefined ? {} : { Authorization: `Bearer ${token}` }) }
|
|
22
|
+
})
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
|
-
import type { ServerResponse } from 'node:http';
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
3
3
|
import { once } from 'node:events';
|
|
4
4
|
import type { AddressInfo } from 'node:net';
|
|
5
5
|
|
|
@@ -16,18 +16,38 @@ export interface MockApi {
|
|
|
16
16
|
close(): Promise<void>;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
const CURRENCIES = ['USD', 'EUR', 'GBP'];
|
|
20
|
+
/** Test identities the mock knows: GET /admin/stats is for admins only. Any other token is unknown. */
|
|
21
|
+
const ROLES = new Map([['admin-token', 'admin'], ['user-token', 'user']]);
|
|
22
|
+
|
|
19
23
|
function send(res: ServerResponse, status: number, body: unknown): void {
|
|
20
24
|
res.statusCode = status;
|
|
21
25
|
res.setHeader('content-type', 'application/json');
|
|
26
|
+
res.setHeader('x-content-type-options', 'nosniff');
|
|
27
|
+
res.setHeader('cache-control', 'no-store');
|
|
22
28
|
res.end(JSON.stringify(body));
|
|
23
29
|
}
|
|
24
30
|
|
|
31
|
+
/** Why a POST /accounts body is invalid, or undefined when it is valid. Mirrors NewAccount in openapi/openapi.json. */
|
|
32
|
+
function newAccountProblem(body: unknown): string | undefined {
|
|
33
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) return 'the body must be an object';
|
|
34
|
+
const fields = body as Record<string, unknown>;
|
|
35
|
+
const unexpected = Object.keys(fields).find(key => !['name', 'currency', 'initialDeposit'].includes(key));
|
|
36
|
+
if (unexpected !== undefined) return 'unexpected property';
|
|
37
|
+
const { name, currency, initialDeposit } = fields;
|
|
38
|
+
if (typeof name !== 'string' || name.length < 1 || name.length > 50) return 'name must be 1 to 50 characters';
|
|
39
|
+
if (typeof currency !== 'string' || !CURRENCIES.includes(currency)) return 'currency must be USD, EUR or GBP';
|
|
40
|
+
if (initialDeposit !== undefined && (typeof initialDeposit !== 'number' || initialDeposit < 0)) return 'initialDeposit must be a number of at least 0';
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
25
44
|
export async function startMockApi(): Promise<MockApi> {
|
|
26
45
|
let issued = 0;
|
|
46
|
+
let created = 0;
|
|
27
47
|
let validToken: string | undefined;
|
|
28
48
|
const received: string[] = [];
|
|
29
|
-
|
|
30
|
-
|
|
49
|
+
|
|
50
|
+
const route = (req: IncomingMessage, res: ServerResponse, rawBody: string): void => {
|
|
31
51
|
const { pathname } = new URL(req.url ?? '/', 'http://localhost');
|
|
32
52
|
received.push(`${req.method ?? ''} ${pathname}`);
|
|
33
53
|
if (req.method === 'POST' && pathname === '/oauth/token') {
|
|
@@ -40,6 +60,27 @@ export async function startMockApi(): Promise<MockApi> {
|
|
|
40
60
|
send(res, 200, { status: 'ok' });
|
|
41
61
|
return;
|
|
42
62
|
}
|
|
63
|
+
if (req.method === 'POST' && pathname === '/accounts') {
|
|
64
|
+
if (!(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) {
|
|
65
|
+
send(res, 415, { error: 'unsupported_media_type' });
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
let body: unknown;
|
|
69
|
+
try {
|
|
70
|
+
body = JSON.parse(rawBody);
|
|
71
|
+
} catch {
|
|
72
|
+
send(res, 400, { error: 'malformed_json' });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const problem = newAccountProblem(body);
|
|
76
|
+
if (problem !== undefined) {
|
|
77
|
+
send(res, 400, { error: 'invalid_request' });
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
created++;
|
|
81
|
+
send(res, 201, { id: `acc-${created}`, status: 'open', balance: (body as { initialDeposit?: number }).initialDeposit ?? 0 });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
43
84
|
const account = /^\/accounts\/([^/]+)$/.exec(pathname);
|
|
44
85
|
if (req.method === 'GET' && account) {
|
|
45
86
|
const id = decodeURIComponent(account[1] ?? '');
|
|
@@ -47,12 +88,25 @@ export async function startMockApi(): Promise<MockApi> {
|
|
|
47
88
|
else send(res, 200, { id, status: 'open', balance: 12.5 });
|
|
48
89
|
return;
|
|
49
90
|
}
|
|
91
|
+
if (req.method === 'GET' && pathname === '/admin/stats') {
|
|
92
|
+
const role = ROLES.get((req.headers.authorization ?? '').replace(/^Bearer /, ''));
|
|
93
|
+
if (role === undefined) send(res, 401, { error: 'invalid_token' });
|
|
94
|
+
else if (role !== 'admin') send(res, 403, { error: 'forbidden' });
|
|
95
|
+
else send(res, 200, { accounts: created });
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
50
98
|
if (req.method === 'GET' && pathname === '/secure/profile') {
|
|
51
99
|
if (validToken !== undefined && req.headers.authorization === `Bearer ${validToken}`) send(res, 200, { user: 'qa-bot' });
|
|
52
100
|
else send(res, 401, { error: 'invalid_token' });
|
|
53
101
|
return;
|
|
54
102
|
}
|
|
55
103
|
send(res, 404, { error: 'not_found' });
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const server = createServer((req, res) => {
|
|
107
|
+
const chunks: Buffer[] = [];
|
|
108
|
+
req.on('data', (chunk: Buffer) => chunks.push(chunk));
|
|
109
|
+
req.on('end', () => route(req, res, Buffer.concat(chunks).toString('utf8')));
|
|
56
110
|
});
|
|
57
111
|
server.listen(0, '127.0.0.1');
|
|
58
112
|
await once(server, 'listening');
|