@nikhil-qeas/api-core 0.6.0 → 0.8.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 +67 -0
- package/README.md +216 -5
- package/bin/qe-api.js +3 -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 +20 -0
- package/dist/http/api-client.js +70 -9
- 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/trace.d.ts +26 -0
- package/dist/http/trace.js +43 -0
- package/dist/http/types.d.ts +22 -0
- package/dist/index.d.ts +31 -5
- package/dist/index.js +16 -3
- package/dist/integrations/mocha.d.ts +32 -0
- package/dist/integrations/mocha.js +81 -0
- package/dist/reporting/html-report.d.ts +23 -0
- package/dist/reporting/html-report.js +118 -0
- package/dist/reporting/junit.d.ts +11 -2
- package/dist/reporting/junit.js +9 -3
- package/dist/reporting/redaction.d.ts +10 -0
- package/dist/reporting/redaction.js +36 -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/load.d.ts +85 -0
- package/dist/testing/load.js +134 -0
- package/dist/testing/matchers.d.ts +63 -0
- package/dist/testing/matchers.js +164 -0
- package/dist/testing/spec-cases.d.ts +136 -0
- package/dist/testing/spec-cases.js +1065 -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 +80 -5
- package/templates/project/__dot__env.example +4 -0
- package/templates/project/__dot__gitlab-ci.yml +1 -0
- package/templates/project/openapi/openapi.json +476 -19
- package/templates/project/src/clients/api.ts +4 -2
- package/templates/project/src/environment.ts +8 -0
- package/templates/project/src/observability.ts +15 -1
- package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
- package/templates/project/tests/performance/health.spec.ts +22 -0
- package/templates/project/tests/security/authentication.spec.ts +3 -1
- 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 +61 -0
- package/templates/project/tests/security/write-protection.spec.ts +2 -2
- package/templates/project/tests/setup/hooks.ts +32 -5
- package/templates/project/tests/smoke/health.spec.ts +3 -3
- package/templates/project/tests/smoke/tracing.spec.ts +48 -0
- 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 +166 -3
|
@@ -11,7 +11,9 @@ describe('@security authentication', () => {
|
|
|
11
11
|
after(async () => { await mock.close(); });
|
|
12
12
|
|
|
13
13
|
const authenticatedClient = (): ApiClient => createApiClient(mock.baseUrl, {
|
|
14
|
-
|
|
14
|
+
// The mock's token endpoint (TokenRequest in openapi/openapi.json) takes the client credentials in the form body. The default is an
|
|
15
|
+
// HTTP Basic header: use whichever your API's token endpoint expects.
|
|
16
|
+
auth: { tokens: new TokenManager(clientCredentialsProvider({ tokenUrl: mock.tokenUrl, clientId: 'qa-client', clientSecret: 'qa-secret', clientAuth: 'body' })) }
|
|
15
17
|
});
|
|
16
18
|
|
|
17
19
|
it('sends the access token, and renews it once when the server rejects it', async () => {
|
|
@@ -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,61 @@
|
|
|
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
|
+
// Security cases generated from openapi/openapi.json, so they follow the spec when you replace it:
|
|
7
|
+
// authentication every operation that requires credentials must refuse a request with none, with an invalid token or API key, and
|
|
8
|
+
// with credentials of the wrong type, using 401 or 403. A server that only checks that an Authorization header
|
|
9
|
+
// exists fails. Public operations (`security: []`) are skipped.
|
|
10
|
+
// mass assignment a client must not be able to set what the server owns: read-only properties the spec declares, and (unless the
|
|
11
|
+
// spec forbids extra properties) privileged names such as isAdmin and role. The API must reject the request or
|
|
12
|
+
// ignore the properties; it fails when a response returns a value that was sent.
|
|
13
|
+
// SSRF fields that hold an address (a URI format, or a name such as url, callback, webhook or redirect) must refuse the
|
|
14
|
+
// cloud metadata address, loopback and private addresses and local files with a 4xx. Skip this suite if your API
|
|
15
|
+
// deliberately checks addresses only when it fetches them.
|
|
16
|
+
const cases = new OpenApiCases(loadSpec());
|
|
17
|
+
|
|
18
|
+
describe('@security protected operations refuse missing and wrong credentials', () => {
|
|
19
|
+
const mock = useMockWithApprovedWrites();
|
|
20
|
+
for (const operation of cases.operations()) {
|
|
21
|
+
const security = cases.security(operation);
|
|
22
|
+
if (!security.length) continue;
|
|
23
|
+
describe(`${operation.method} ${operation.path}`, () => {
|
|
24
|
+
for (const testCase of security) {
|
|
25
|
+
it(testCase.description, async () => {
|
|
26
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(testCase.request), testCase);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe('@security the API does not apply properties a client must not set', () => {
|
|
34
|
+
const mock = useMockWithApprovedWrites();
|
|
35
|
+
for (const operation of cases.operations()) {
|
|
36
|
+
const injected = cases.massAssignment(operation);
|
|
37
|
+
if (!injected.length) continue;
|
|
38
|
+
describe(`${operation.method} ${operation.path}`, () => {
|
|
39
|
+
for (const testCase of injected) {
|
|
40
|
+
it(testCase.description, async () => {
|
|
41
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(testCase.request), testCase);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
describe('@security the API refuses addresses it must not contact', () => {
|
|
49
|
+
const mock = useMockWithApprovedWrites();
|
|
50
|
+
for (const operation of cases.operations()) {
|
|
51
|
+
const addresses = cases.ssrf(operation);
|
|
52
|
+
if (!addresses.length) continue;
|
|
53
|
+
describe(`${operation.method} ${operation.path}`, () => {
|
|
54
|
+
for (const testCase of addresses) {
|
|
55
|
+
it(testCase.description, async () => {
|
|
56
|
+
assertCaseOutcome(await createApiClient(mock().baseUrl).request(testCase.request), testCase);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
});
|
|
@@ -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,15 +1,42 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { failedHooks, writeHtmlReport } from '@nikhil-qeas/api-core';
|
|
2
|
+
import { traceEnabled } from '../../src/environment.js';
|
|
3
|
+
import { coverage, currentTrace, metrics, results, startTrace } from '../../src/observability.js';
|
|
2
4
|
|
|
3
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Mocha root hooks. Before every test: a new trace (used when QE_TRACE=true). After every test: its final outcome is recorded for the
|
|
7
|
+
* HTML report (a test that is retried is recorded once, when the retries are over). After the whole run: the coverage report with an
|
|
8
|
+
* optional minimum, and reports/html/index.html.
|
|
9
|
+
*/
|
|
4
10
|
export const mochaHooks = {
|
|
5
|
-
|
|
11
|
+
beforeEach(): void {
|
|
12
|
+
startTrace(); // every request this test sends joins one trace
|
|
13
|
+
},
|
|
14
|
+
afterEach(this: Mocha.Context): void {
|
|
15
|
+
const test = this.currentTest;
|
|
16
|
+
if (!test) return;
|
|
17
|
+
// The id to search for in the API's tracing backend to see what the server did during a failed test.
|
|
18
|
+
if (traceEnabled() && test.state === 'failed') console.log(` trace id of the failed test: ${currentTrace() ?? 'none'}`);
|
|
19
|
+
results.record(test, traceEnabled() ? { traceId: currentTrace() } : {});
|
|
20
|
+
},
|
|
21
|
+
async afterAll(this: Mocha.Context): Promise<void> {
|
|
6
22
|
await coverage.write('reports/coverage/api.md', 'markdown');
|
|
7
23
|
await coverage.write('reports/coverage/api.json');
|
|
8
24
|
const { operations, responses } = coverage.report();
|
|
9
|
-
const { total, retries } = metrics.summary();
|
|
25
|
+
const { total, retries, p95Ms } = metrics.summary();
|
|
26
|
+
// A failed before or after hook is not a test, so no test record shows it: say so, or the report would look green on a red run.
|
|
27
|
+
const root = this.test?.parent;
|
|
28
|
+
const brokenHooks = root ? failedHooks(root) : [];
|
|
29
|
+
await writeHtmlReport('reports/html/index.html', results.results(), {
|
|
30
|
+
facts: [
|
|
31
|
+
['API coverage', `${operations.covered} of ${operations.total} operations (${operations.percent}%), ${responses.covered} of ${responses.total} documented responses`],
|
|
32
|
+
['Requests', `${total} sent, ${retries} retried, 95th percentile ${p95Ms} ms`]
|
|
33
|
+
],
|
|
34
|
+
problems: brokenHooks.length ? [`${brokenHooks.length} hook${brokenHooks.length === 1 ? '' : 's'} failed, so the tests they guard did not run and are not listed here: ${brokenHooks.slice(0, 5).join('; ')}`] : [],
|
|
35
|
+
messages: true // the messages are scrubbed and shortened, and the console and JUnit report already show them
|
|
36
|
+
});
|
|
10
37
|
console.log(
|
|
11
38
|
`\nAPI coverage: ${operations.covered}/${operations.total} operations (${operations.percent}%), ` +
|
|
12
|
-
`${responses.covered}/${responses.total} documented responses. Requests: ${total}, retries: ${retries}.
|
|
39
|
+
`${responses.covered}/${responses.total} documented responses. Requests: ${total}, retries: ${retries}. Reports: reports/coverage/api.md, reports/html/index.html`
|
|
13
40
|
);
|
|
14
41
|
const minimum = process.env.QE_COVERAGE_MIN_OPERATIONS;
|
|
15
42
|
if (minimum) coverage.assertCoverage({ minOperations: Number(minimum), failOnUndocumented: true });
|
|
@@ -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,48 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { expectStatus, parseTraceparent } from '@nikhil-qeas/api-core';
|
|
3
|
+
import { createApiClient } from '../../src/clients/api.js';
|
|
4
|
+
import { currentTrace } from '../../src/observability.js';
|
|
5
|
+
import { startMockApi } from '../support/mock-api.js';
|
|
6
|
+
import type { MockApi } from '../support/mock-api.js';
|
|
7
|
+
|
|
8
|
+
// With QE_TRACE=true every request carries a W3C `traceparent` header and all requests of one test share one trace id, so a failed
|
|
9
|
+
// test can be found in the API's tracing backend: its trace id is printed right after it. The suite switches tracing on for itself.
|
|
10
|
+
describe('@smoke tracing', () => {
|
|
11
|
+
let mock: MockApi;
|
|
12
|
+
let saved: string | undefined;
|
|
13
|
+
let traceOfFirstTest: string | undefined;
|
|
14
|
+
before(async () => {
|
|
15
|
+
mock = await startMockApi();
|
|
16
|
+
saved = process.env.QE_TRACE;
|
|
17
|
+
process.env.QE_TRACE = 'true';
|
|
18
|
+
});
|
|
19
|
+
after(async () => {
|
|
20
|
+
if (saved === undefined) delete process.env.QE_TRACE;
|
|
21
|
+
else process.env.QE_TRACE = saved;
|
|
22
|
+
await mock.close();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const lastTrace = (): string | undefined => {
|
|
26
|
+
const sent = mock.traceparents();
|
|
27
|
+
const header = sent[sent.length - 1];
|
|
28
|
+
return header === undefined ? undefined : parseTraceparent(header)?.traceId;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
it('sends one trace id with every request of a test, and a new span for each request', async () => {
|
|
32
|
+
const api = createApiClient(mock.baseUrl);
|
|
33
|
+
expectStatus(await api.request({ method: 'GET', path: '/health' }), 200);
|
|
34
|
+
expectStatus(await api.request({ method: 'GET', path: '/health' }), 200);
|
|
35
|
+
const sent = mock.traceparents().map(header => parseTraceparent(header));
|
|
36
|
+
assert.equal(sent.length, 2, 'both requests carried a valid traceparent');
|
|
37
|
+
assert.equal(sent[0]?.traceId, currentTrace());
|
|
38
|
+
assert.equal(sent[1]?.traceId, currentTrace());
|
|
39
|
+
assert.notEqual(sent[0]?.spanId, sent[1]?.spanId);
|
|
40
|
+
traceOfFirstTest = currentTrace();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('puts the next test in a trace of its own', async () => {
|
|
44
|
+
expectStatus(await createApiClient(mock.baseUrl).request({ method: 'GET', path: '/health' }), 200);
|
|
45
|
+
assert.equal(lastTrace(), currentTrace());
|
|
46
|
+
assert.notEqual(lastTrace(), traceOfFirstTest);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -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,6 +1,7 @@
|
|
|
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
|
+
import { isIP } from 'node:net';
|
|
4
5
|
import type { AddressInfo } from 'node:net';
|
|
5
6
|
|
|
6
7
|
/** A local stand-in for an API and its OAuth2 token endpoint, so the sample tests run anywhere without a real environment. */
|
|
@@ -13,33 +14,179 @@ export interface MockApi {
|
|
|
13
14
|
revokeTokens(): void;
|
|
14
15
|
/** Every request the server received, as "METHOD /path". Shows that a refused request was never sent. */
|
|
15
16
|
requests(): readonly string[];
|
|
17
|
+
/** The `traceparent` header of every request that carried one, in order. Shows what the client propagates when QE_TRACE=true. */
|
|
18
|
+
traceparents(): readonly string[];
|
|
16
19
|
close(): Promise<void>;
|
|
17
20
|
}
|
|
18
21
|
|
|
22
|
+
const CURRENCIES = ['USD', 'EUR', 'GBP'];
|
|
23
|
+
/** Test identities the mock knows: GET /admin/stats is for admins only. Any other token is unknown. */
|
|
24
|
+
const ROLES = new Map([['admin-token', 'admin'], ['user-token', 'user']]);
|
|
25
|
+
|
|
19
26
|
function send(res: ServerResponse, status: number, body: unknown): void {
|
|
20
27
|
res.statusCode = status;
|
|
21
28
|
res.setHeader('content-type', 'application/json');
|
|
29
|
+
res.setHeader('x-content-type-options', 'nosniff');
|
|
30
|
+
res.setHeader('cache-control', 'no-store');
|
|
22
31
|
res.end(JSON.stringify(body));
|
|
23
32
|
}
|
|
24
33
|
|
|
34
|
+
/** True for an http or https address on the public internet: not a file, localhost, a private network or the cloud metadata service. */
|
|
35
|
+
function isPublicAddress(value: string): boolean {
|
|
36
|
+
let url: URL;
|
|
37
|
+
try {
|
|
38
|
+
url = new URL(value);
|
|
39
|
+
} catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
|
43
|
+
const host = url.hostname.replace(/^\[|\]$/g, '');
|
|
44
|
+
if (host === 'localhost' || host.endsWith('.localhost')) return false;
|
|
45
|
+
if (isIP(host) === 6) return !(host === '::1' || /^(fc|fd|fe80)/i.test(host));
|
|
46
|
+
if (isIP(host) === 4) {
|
|
47
|
+
const [first = 0, second = 0] = host.split('.').map(Number);
|
|
48
|
+
return !(first === 0 || first === 10 || first === 127 || (first === 169 && second === 254) || (first === 172 && second >= 16 && second <= 31) || (first === 192 && second === 168));
|
|
49
|
+
}
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Why a POST /accounts body is invalid, or undefined when it is valid. Mirrors NewAccount in openapi/openapi.json.
|
|
55
|
+
* `accountNumber` is read-only: the API accepts it and ignores it (it never applies, or returns, a value a client sends).
|
|
56
|
+
* `webhookUrl` must be a public address, so the API cannot be pointed at internal systems.
|
|
57
|
+
*/
|
|
58
|
+
function newAccountProblem(body: unknown): string | undefined {
|
|
59
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) return 'the body must be an object';
|
|
60
|
+
const fields = body as Record<string, unknown>;
|
|
61
|
+
const unexpected = Object.keys(fields).find(key => !['name', 'currency', 'initialDeposit', 'webhookUrl', 'accountNumber'].includes(key));
|
|
62
|
+
if (unexpected !== undefined) return 'unexpected property';
|
|
63
|
+
const { name, currency, initialDeposit, webhookUrl } = fields;
|
|
64
|
+
if (typeof name !== 'string' || name.length < 1 || name.length > 50) return 'name must be 1 to 50 characters';
|
|
65
|
+
if (typeof currency !== 'string' || !CURRENCIES.includes(currency)) return 'currency must be USD, EUR or GBP';
|
|
66
|
+
if (initialDeposit !== undefined && (typeof initialDeposit !== 'number' || initialDeposit < 0)) return 'initialDeposit must be a number of at least 0';
|
|
67
|
+
if (webhookUrl !== undefined && (typeof webhookUrl !== 'string' || !isPublicAddress(webhookUrl))) return 'webhookUrl must be a public http or https address';
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Reads a form or multipart body the way a server framework does (here: the platform's own parser).
|
|
73
|
+
* 'unsupported' when it is neither, 'malformed' when it does not parse.
|
|
74
|
+
*/
|
|
75
|
+
async function readForm(req: IncomingMessage, body: Buffer): Promise<FormData | 'unsupported' | 'malformed'> {
|
|
76
|
+
const contentType = req.headers['content-type'] ?? '';
|
|
77
|
+
const kind = contentType.split(';', 1)[0]?.trim().toLowerCase();
|
|
78
|
+
if (kind !== 'application/x-www-form-urlencoded' && kind !== 'multipart/form-data') return 'unsupported';
|
|
79
|
+
try {
|
|
80
|
+
return await new Request('http://localhost/', { method: 'POST', headers: { 'content-type': contentType }, body: body.length ? new Uint8Array(body) : null }).formData();
|
|
81
|
+
} catch {
|
|
82
|
+
return 'malformed';
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The one text value of a field, or undefined when it is missing, repeated, or a file. */
|
|
87
|
+
function textField(form: FormData, name: string): string | undefined {
|
|
88
|
+
const values = form.getAll(name);
|
|
89
|
+
const [value] = values;
|
|
90
|
+
return values.length === 1 && typeof value === 'string' ? value : undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Why a POST /oauth/token form is invalid, or undefined when it is valid. Mirrors TokenRequest in openapi/openapi.json. */
|
|
94
|
+
function tokenRequestProblem(form: FormData): string | undefined {
|
|
95
|
+
for (const name of form.keys()) if (!['grant_type', 'client_id', 'client_secret', 'scope'].includes(name)) return 'unexpected field';
|
|
96
|
+
if (textField(form, 'grant_type') !== 'client_credentials') return 'grant_type must be client_credentials';
|
|
97
|
+
const clientId = textField(form, 'client_id');
|
|
98
|
+
if (clientId === undefined || clientId.length < 1 || clientId.length > 100) return 'client_id must be 1 to 100 characters';
|
|
99
|
+
const clientSecret = textField(form, 'client_secret');
|
|
100
|
+
if (clientSecret === undefined || clientSecret.length < 1 || clientSecret.length > 200) return 'client_secret must be 1 to 200 characters';
|
|
101
|
+
if (form.has('scope') && (textField(form, 'scope') ?? 'x'.repeat(201)).length > 200) return 'scope must be at most 200 characters';
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Why a document upload is invalid, or undefined when it is valid. Mirrors DocumentUpload in openapi/openapi.json. */
|
|
106
|
+
function documentProblem(form: FormData): string | undefined {
|
|
107
|
+
for (const name of form.keys()) if (!['file', 'kind', 'note'].includes(name)) return 'unexpected field';
|
|
108
|
+
const files = form.getAll('file');
|
|
109
|
+
if (files.length !== 1 || !(files[0] instanceof File)) return 'file must be exactly one file';
|
|
110
|
+
const kind = textField(form, 'kind');
|
|
111
|
+
if (kind === undefined || !['statement', 'identity', 'other'].includes(kind)) return 'kind must be statement, identity or other';
|
|
112
|
+
if (form.has('note') && (textField(form, 'note') ?? 'x'.repeat(101)).length > 100) return 'note must be at most 100 characters';
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
25
116
|
export async function startMockApi(): Promise<MockApi> {
|
|
26
117
|
let issued = 0;
|
|
118
|
+
let created = 0;
|
|
27
119
|
let validToken: string | undefined;
|
|
28
120
|
const received: string[] = [];
|
|
29
|
-
const
|
|
30
|
-
|
|
121
|
+
const traces: string[] = [];
|
|
122
|
+
|
|
123
|
+
let uploaded = 0;
|
|
124
|
+
|
|
125
|
+
const route = async (req: IncomingMessage, res: ServerResponse, body: Buffer): Promise<void> => {
|
|
126
|
+
const rawBody = body.toString('utf8');
|
|
31
127
|
const { pathname } = new URL(req.url ?? '/', 'http://localhost');
|
|
32
128
|
received.push(`${req.method ?? ''} ${pathname}`);
|
|
129
|
+
if (typeof req.headers.traceparent === 'string') traces.push(req.headers.traceparent);
|
|
33
130
|
if (req.method === 'POST' && pathname === '/oauth/token') {
|
|
131
|
+
const form = await readForm(req, body);
|
|
132
|
+
if (form === 'unsupported') {
|
|
133
|
+
send(res, 415, { error: 'unsupported_media_type' });
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (form === 'malformed' || tokenRequestProblem(form) !== undefined) {
|
|
137
|
+
send(res, 400, { error: 'invalid_request' });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
34
140
|
issued++;
|
|
35
141
|
validToken = `tok-${issued}`;
|
|
36
142
|
send(res, 200, { access_token: validToken, token_type: 'Bearer', expires_in: 3600 });
|
|
37
143
|
return;
|
|
38
144
|
}
|
|
145
|
+
const documents = /^\/accounts\/([^/]+)\/documents$/.exec(pathname);
|
|
146
|
+
if (req.method === 'POST' && documents) {
|
|
147
|
+
const form = await readForm(req, body);
|
|
148
|
+
if (form === 'unsupported') {
|
|
149
|
+
send(res, 415, { error: 'unsupported_media_type' });
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (form === 'malformed' || documentProblem(form) !== undefined) {
|
|
153
|
+
send(res, 400, { error: 'invalid_request' });
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (decodeURIComponent(documents[1] ?? '') === 'missing') {
|
|
157
|
+
send(res, 404, { error: 'not_found' });
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
uploaded++;
|
|
161
|
+
const file = form.get('file') as File;
|
|
162
|
+
send(res, 201, { id: `doc-${uploaded}`, kind: textField(form, 'kind'), size: file.size });
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
39
165
|
if (req.method === 'GET' && pathname === '/health') {
|
|
40
166
|
send(res, 200, { status: 'ok' });
|
|
41
167
|
return;
|
|
42
168
|
}
|
|
169
|
+
if (req.method === 'POST' && pathname === '/accounts') {
|
|
170
|
+
if (!(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) {
|
|
171
|
+
send(res, 415, { error: 'unsupported_media_type' });
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
let body: unknown;
|
|
175
|
+
try {
|
|
176
|
+
body = JSON.parse(rawBody);
|
|
177
|
+
} catch {
|
|
178
|
+
send(res, 400, { error: 'malformed_json' });
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
const problem = newAccountProblem(body);
|
|
182
|
+
if (problem !== undefined) {
|
|
183
|
+
send(res, 400, { error: 'invalid_request' });
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
created++;
|
|
187
|
+
send(res, 201, { id: `acc-${created}`, status: 'open', balance: (body as { initialDeposit?: number }).initialDeposit ?? 0 });
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
43
190
|
const account = /^\/accounts\/([^/]+)$/.exec(pathname);
|
|
44
191
|
if (req.method === 'GET' && account) {
|
|
45
192
|
const id = decodeURIComponent(account[1] ?? '');
|
|
@@ -47,12 +194,27 @@ export async function startMockApi(): Promise<MockApi> {
|
|
|
47
194
|
else send(res, 200, { id, status: 'open', balance: 12.5 });
|
|
48
195
|
return;
|
|
49
196
|
}
|
|
197
|
+
if (req.method === 'GET' && pathname === '/admin/stats') {
|
|
198
|
+
const role = ROLES.get((req.headers.authorization ?? '').replace(/^Bearer /, ''));
|
|
199
|
+
if (role === undefined) send(res, 401, { error: 'invalid_token' });
|
|
200
|
+
else if (role !== 'admin') send(res, 403, { error: 'forbidden' });
|
|
201
|
+
else send(res, 200, { accounts: created });
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
50
204
|
if (req.method === 'GET' && pathname === '/secure/profile') {
|
|
51
205
|
if (validToken !== undefined && req.headers.authorization === `Bearer ${validToken}`) send(res, 200, { user: 'qa-bot' });
|
|
52
206
|
else send(res, 401, { error: 'invalid_token' });
|
|
53
207
|
return;
|
|
54
208
|
}
|
|
55
209
|
send(res, 404, { error: 'not_found' });
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const server = createServer((req, res) => {
|
|
213
|
+
const chunks: Buffer[] = [];
|
|
214
|
+
req.on('data', (chunk: Buffer) => chunks.push(chunk));
|
|
215
|
+
req.on('end', () => {
|
|
216
|
+
route(req, res, Buffer.concat(chunks)).catch(() => { send(res, 500, { error: 'internal_error' }); });
|
|
217
|
+
});
|
|
56
218
|
});
|
|
57
219
|
server.listen(0, '127.0.0.1');
|
|
58
220
|
await once(server, 'listening');
|
|
@@ -63,6 +225,7 @@ export async function startMockApi(): Promise<MockApi> {
|
|
|
63
225
|
tokensIssued: () => issued,
|
|
64
226
|
revokeTokens: () => { validToken = undefined; },
|
|
65
227
|
requests: () => received,
|
|
228
|
+
traceparents: () => traces,
|
|
66
229
|
close: () => new Promise<void>(resolve => {
|
|
67
230
|
server.closeAllConnections();
|
|
68
231
|
server.close(() => resolve());
|