@nikhil-qeas/api-core 0.5.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +141 -5
- package/bin/qe-api.js +4 -4
- package/dist/contracts/assertions.d.ts +11 -0
- package/dist/contracts/assertions.js +31 -0
- package/dist/contracts/openapi.d.ts +28 -1
- package/dist/contracts/openapi.js +113 -0
- package/dist/graphql/graphql.d.ts +86 -0
- package/dist/graphql/graphql.js +312 -0
- package/dist/http/api-client.d.ts +5 -0
- package/dist/http/api-client.js +30 -6
- package/dist/http/cookies.d.ts +32 -0
- package/dist/http/cookies.js +116 -0
- package/dist/http/multipart.d.ts +20 -0
- package/dist/http/multipart.js +48 -0
- package/dist/http/types.d.ts +16 -0
- package/dist/index.d.ts +21 -2
- package/dist/index.js +11 -1
- package/dist/reporting/redaction.d.ts +4 -0
- package/dist/reporting/redaction.js +26 -2
- package/dist/security/authorization-matrix.d.ts +55 -0
- package/dist/security/authorization-matrix.js +102 -0
- package/dist/security/headers.d.ts +21 -0
- package/dist/security/headers.js +45 -0
- package/dist/security/policy.js +3 -2
- package/dist/security/sensitive-data.d.ts +22 -0
- package/dist/security/sensitive-data.js +76 -0
- package/dist/testing/json-path.d.ts +6 -0
- package/dist/testing/json-path.js +97 -0
- package/dist/testing/matchers.d.ts +63 -0
- package/dist/testing/matchers.js +164 -0
- package/dist/testing/spec-cases.d.ts +98 -0
- package/dist/testing/spec-cases.js +795 -0
- package/dist/testing/wait-for.d.ts +40 -0
- package/dist/testing/wait-for.js +82 -0
- package/package.json +1 -1
- package/templates/project/README.md +55 -6
- package/templates/project/__dot__env.example +5 -0
- package/templates/project/openapi/openapi.json +243 -19
- package/templates/project/src/clients/api.ts +27 -6
- package/templates/project/src/{config/environment.ts → environment.ts} +16 -1
- package/templates/project/src/observability.ts +1 -1
- package/templates/project/src/{contracts/openapi.ts → openapi.ts} +1 -1
- package/templates/project/tests/contract/openapi.contract.spec.ts +1 -1
- package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
- package/templates/project/tests/security/authorization.spec.ts +29 -0
- package/templates/project/tests/security/hygiene.spec.ts +37 -0
- package/templates/project/tests/security/spec-cases.spec.ts +24 -0
- package/templates/project/tests/security/write-protection.spec.ts +60 -0
- package/templates/project/tests/smoke/health.spec.ts +3 -3
- package/templates/project/tests/support/approved-writes.ts +27 -0
- package/templates/project/tests/support/identities.ts +24 -0
- package/templates/project/tests/support/mock-api.ts +62 -3
- /package/templates/project/{config/mocha.config.json → __dot__mocharc.json} +0 -0
|
@@ -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
|
+
});
|
|
@@ -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: they exist to test the guard, not the API.
|
|
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, 400); // the mock rejects this body, 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
|
+
});
|
|
@@ -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
|
|
|
@@ -11,21 +11,45 @@ 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
|
|
|
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
|
+
|
|
17
23
|
function send(res: ServerResponse, status: number, body: unknown): void {
|
|
18
24
|
res.statusCode = status;
|
|
19
25
|
res.setHeader('content-type', 'application/json');
|
|
26
|
+
res.setHeader('x-content-type-options', 'nosniff');
|
|
27
|
+
res.setHeader('cache-control', 'no-store');
|
|
20
28
|
res.end(JSON.stringify(body));
|
|
21
29
|
}
|
|
22
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
|
+
|
|
23
44
|
export async function startMockApi(): Promise<MockApi> {
|
|
24
45
|
let issued = 0;
|
|
46
|
+
let created = 0;
|
|
25
47
|
let validToken: string | undefined;
|
|
26
|
-
const
|
|
27
|
-
|
|
48
|
+
const received: string[] = [];
|
|
49
|
+
|
|
50
|
+
const route = (req: IncomingMessage, res: ServerResponse, rawBody: string): void => {
|
|
28
51
|
const { pathname } = new URL(req.url ?? '/', 'http://localhost');
|
|
52
|
+
received.push(`${req.method ?? ''} ${pathname}`);
|
|
29
53
|
if (req.method === 'POST' && pathname === '/oauth/token') {
|
|
30
54
|
issued++;
|
|
31
55
|
validToken = `tok-${issued}`;
|
|
@@ -36,6 +60,27 @@ export async function startMockApi(): Promise<MockApi> {
|
|
|
36
60
|
send(res, 200, { status: 'ok' });
|
|
37
61
|
return;
|
|
38
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
|
+
}
|
|
39
84
|
const account = /^\/accounts\/([^/]+)$/.exec(pathname);
|
|
40
85
|
if (req.method === 'GET' && account) {
|
|
41
86
|
const id = decodeURIComponent(account[1] ?? '');
|
|
@@ -43,12 +88,25 @@ export async function startMockApi(): Promise<MockApi> {
|
|
|
43
88
|
else send(res, 200, { id, status: 'open', balance: 12.5 });
|
|
44
89
|
return;
|
|
45
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
|
+
}
|
|
46
98
|
if (req.method === 'GET' && pathname === '/secure/profile') {
|
|
47
99
|
if (validToken !== undefined && req.headers.authorization === `Bearer ${validToken}`) send(res, 200, { user: 'qa-bot' });
|
|
48
100
|
else send(res, 401, { error: 'invalid_token' });
|
|
49
101
|
return;
|
|
50
102
|
}
|
|
51
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')));
|
|
52
110
|
});
|
|
53
111
|
server.listen(0, '127.0.0.1');
|
|
54
112
|
await once(server, 'listening');
|
|
@@ -58,6 +116,7 @@ export async function startMockApi(): Promise<MockApi> {
|
|
|
58
116
|
tokenUrl: `${origin}/oauth/token`,
|
|
59
117
|
tokensIssued: () => issued,
|
|
60
118
|
revokeTokens: () => { validToken = undefined; },
|
|
119
|
+
requests: () => received,
|
|
61
120
|
close: () => new Promise<void>(resolve => {
|
|
62
121
|
server.closeAllConnections();
|
|
63
122
|
server.close(() => resolve());
|
|
File without changes
|