@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
|
@@ -1,9 +1,41 @@
|
|
|
1
1
|
import type { TestCaseResult } from '../reporting/junit.js';
|
|
2
|
+
/** What the collector reads from a Mocha test: `Mocha.Test` fits, and so does a plain object in a test of your own. */
|
|
3
|
+
export interface MochaTestLike {
|
|
4
|
+
fullTitle(): string;
|
|
5
|
+
parent?: {
|
|
6
|
+
fullTitle(): string;
|
|
7
|
+
} | undefined;
|
|
8
|
+
/** 'passed', 'failed' or 'pending' once the test has its final outcome; undefined for an attempt that will be retried. */
|
|
9
|
+
state?: string | undefined;
|
|
10
|
+
duration?: number | undefined;
|
|
11
|
+
err?: unknown;
|
|
12
|
+
isPending?: (() => boolean) | undefined;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The hooks (before, after) that failed anywhere under a suite, as text. A failed hook is not a test, so no test record shows it, and the
|
|
16
|
+
* tests it guards never ran: a report built from tests alone would look green on a red run. Call it from a root `afterAll` hook with
|
|
17
|
+
* `this.test?.parent`. It reads Mocha's `getHooks`, which the Mocha type definitions do not declare, so it takes any suite.
|
|
18
|
+
*/
|
|
19
|
+
export declare function failedHooks(root: {
|
|
20
|
+
fullTitle(): string;
|
|
21
|
+
}): string[];
|
|
22
|
+
/** A failure as one short, printable text: control characters and colors removed, credentials masked, long output cut. */
|
|
23
|
+
export declare function failureText(error: unknown): string | undefined;
|
|
2
24
|
/** No dependency on Mocha itself; register this callback from mocha root hooks. */
|
|
3
25
|
export declare class MochaResultCollector {
|
|
4
26
|
private readonly rows;
|
|
5
27
|
private readonly starts;
|
|
6
28
|
start(fullTitle: string): void;
|
|
7
29
|
finish(fullTitle: string, suite: string, status: TestCaseResult['status']): void;
|
|
30
|
+
/**
|
|
31
|
+
* Records a test from a root `afterEach` hook, once, when it has its final outcome: Mocha runs `afterEach` after every attempt, and an
|
|
32
|
+
* attempt that will be retried has no state yet, so it returns false and nothing is recorded. A test that passed after retries is kept
|
|
33
|
+
* with the number of retries it needed (that is a flaky test, and it should not hide). A failure's text is kept scrubbed and shortened
|
|
34
|
+
* (see `failureText`); the reports leave it out unless asked. Tests marked `it.skip` never reach this hook.
|
|
35
|
+
*/
|
|
36
|
+
record(test: MochaTestLike, details?: {
|
|
37
|
+
traceId?: string | undefined;
|
|
38
|
+
retries?: number | undefined;
|
|
39
|
+
}): boolean;
|
|
8
40
|
results(): readonly TestCaseResult[];
|
|
9
41
|
}
|
|
@@ -1,4 +1,66 @@
|
|
|
1
1
|
import { performance } from 'node:perf_hooks';
|
|
2
|
+
import { scrubText } from '../reporting/redaction.js';
|
|
3
|
+
const MAX_MESSAGE_CHARS = 2000;
|
|
4
|
+
const MAX_MESSAGE_LINES = 40;
|
|
5
|
+
const ANSI_ESCAPE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, 'g');
|
|
6
|
+
// Mocha's own `currentRetry()` (0 for the first attempt, 1 after one retry) is read when it exists, but it is not part of this type: the Mocha type
|
|
7
|
+
// definitions declare it protected, which would make `this.currentTest` unassignable here.
|
|
8
|
+
function retriesOf(test) {
|
|
9
|
+
const retry = test.currentRetry;
|
|
10
|
+
const count = typeof retry === 'function' ? retry.call(test) : 0;
|
|
11
|
+
return typeof count === 'number' && Number.isInteger(count) && count > 0 ? count : 0;
|
|
12
|
+
}
|
|
13
|
+
const HOOK_KINDS = ['beforeAll', 'beforeEach', 'afterEach', 'afterAll'];
|
|
14
|
+
function isRecord(value) { return typeof value === 'object' && value !== null; }
|
|
15
|
+
/**
|
|
16
|
+
* The hooks (before, after) that failed anywhere under a suite, as text. A failed hook is not a test, so no test record shows it, and the
|
|
17
|
+
* tests it guards never ran: a report built from tests alone would look green on a red run. Call it from a root `afterAll` hook with
|
|
18
|
+
* `this.test?.parent`. It reads Mocha's `getHooks`, which the Mocha type definitions do not declare, so it takes any suite.
|
|
19
|
+
*/
|
|
20
|
+
export function failedHooks(root) {
|
|
21
|
+
const found = [];
|
|
22
|
+
const visit = (suite, depth) => {
|
|
23
|
+
if (!isRecord(suite) || depth > 100)
|
|
24
|
+
return;
|
|
25
|
+
const getHooks = suite.getHooks;
|
|
26
|
+
const title = typeof suite.fullTitle === 'function' ? suite.fullTitle.call(suite) : '';
|
|
27
|
+
if (typeof getHooks === 'function') {
|
|
28
|
+
for (const kind of HOOK_KINDS) {
|
|
29
|
+
const hooks = getHooks.call(suite, kind);
|
|
30
|
+
for (const hook of Array.isArray(hooks) ? hooks : []) {
|
|
31
|
+
if (isRecord(hook) && hook.state === 'failed')
|
|
32
|
+
found.push(`${typeof title === 'string' && title !== '' ? title : '(root)'}: ${typeof hook.title === 'string' ? hook.title : kind}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
for (const child of Array.isArray(suite.suites) ? suite.suites : [])
|
|
37
|
+
visit(child, depth + 1);
|
|
38
|
+
};
|
|
39
|
+
visit(root, 0);
|
|
40
|
+
return found;
|
|
41
|
+
}
|
|
42
|
+
/** A failure as one short, printable text: control characters and colors removed, credentials masked, long output cut. */
|
|
43
|
+
export function failureText(error) {
|
|
44
|
+
if (error === undefined || error === null)
|
|
45
|
+
return undefined;
|
|
46
|
+
let text;
|
|
47
|
+
if (error instanceof Error)
|
|
48
|
+
text = `${error.name}: ${error.message}`;
|
|
49
|
+
else if (typeof error === 'string')
|
|
50
|
+
text = error;
|
|
51
|
+
else if (typeof error === 'object' && 'message' in error && typeof error.message === 'string')
|
|
52
|
+
text = error.message;
|
|
53
|
+
else
|
|
54
|
+
text = 'A value that is not an error was thrown';
|
|
55
|
+
const printable = Array.from(text.replace(ANSI_ESCAPE, '').replace(/\r\n?/g, '\n')).filter(char => {
|
|
56
|
+
const code = char.charCodeAt(0);
|
|
57
|
+
return code === 9 || code === 10 || (code >= 32 && code !== 127);
|
|
58
|
+
}).join('');
|
|
59
|
+
const lines = scrubText(printable).split('\n');
|
|
60
|
+
const kept = lines.slice(0, MAX_MESSAGE_LINES).join('\n');
|
|
61
|
+
const more = lines.length > MAX_MESSAGE_LINES ? `\n... ${lines.length - MAX_MESSAGE_LINES} more lines` : '';
|
|
62
|
+
return kept.length > MAX_MESSAGE_CHARS ? `${kept.slice(0, MAX_MESSAGE_CHARS)}...` : `${kept}${more}`;
|
|
63
|
+
}
|
|
2
64
|
/** No dependency on Mocha itself; register this callback from mocha root hooks. */
|
|
3
65
|
export class MochaResultCollector {
|
|
4
66
|
rows = [];
|
|
@@ -9,5 +71,24 @@ export class MochaResultCollector {
|
|
|
9
71
|
this.starts.delete(fullTitle);
|
|
10
72
|
this.rows.push({ name: fullTitle, suite, status, durationMs: began === undefined ? 0 : Math.round(performance.now() - began) });
|
|
11
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Records a test from a root `afterEach` hook, once, when it has its final outcome: Mocha runs `afterEach` after every attempt, and an
|
|
76
|
+
* attempt that will be retried has no state yet, so it returns false and nothing is recorded. A test that passed after retries is kept
|
|
77
|
+
* with the number of retries it needed (that is a flaky test, and it should not hide). A failure's text is kept scrubbed and shortened
|
|
78
|
+
* (see `failureText`); the reports leave it out unless asked. Tests marked `it.skip` never reach this hook.
|
|
79
|
+
*/
|
|
80
|
+
record(test, details = {}) {
|
|
81
|
+
const pending = test.state === 'pending' || test.isPending?.() === true;
|
|
82
|
+
if (test.state !== 'passed' && test.state !== 'failed' && !pending)
|
|
83
|
+
return false;
|
|
84
|
+
const status = pending ? 'skipped' : test.state === 'passed' ? 'passed' : 'failed';
|
|
85
|
+
const retries = details.retries ?? retriesOf(test);
|
|
86
|
+
const message = status === 'failed' ? failureText(test.err) : undefined;
|
|
87
|
+
this.rows.push({
|
|
88
|
+
name: test.fullTitle(), suite: test.parent?.fullTitle() ?? '', status, durationMs: Math.round(test.duration ?? 0),
|
|
89
|
+
...(retries > 0 ? { retries } : {}), ...(message !== undefined ? { message } : {}), ...(details.traceId !== undefined ? { traceId: details.traceId } : {})
|
|
90
|
+
});
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
12
93
|
results() { return this.rows.map(row => ({ ...row })); }
|
|
13
94
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { TestCaseResult } from './junit.js';
|
|
2
|
+
export interface HtmlReportOptions {
|
|
3
|
+
/** Default "API test report". */
|
|
4
|
+
title?: string | undefined;
|
|
5
|
+
/** Name and value pairs under the summary, e.g. `['API coverage', '7 of 7 operations (100%)']`. */
|
|
6
|
+
facts?: ReadonlyArray<readonly [string, string]> | undefined;
|
|
7
|
+
/** Warnings shown above everything, e.g. that some tests did not run, so a green-looking report is never mistaken for a green run. */
|
|
8
|
+
notes?: readonly string[] | undefined;
|
|
9
|
+
/** Reasons the run failed that are not tests, such as a failed before hook (see `failedHooks`). Shown in red, and the verdict is FAILED whatever the tests say. */
|
|
10
|
+
problems?: readonly string[] | undefined;
|
|
11
|
+
/** Show each failure's message. The collector has already scrubbed and shortened it, but a message can still quote data, so the default is false. */
|
|
12
|
+
messages?: boolean | undefined;
|
|
13
|
+
/** Default: now. */
|
|
14
|
+
generatedAt?: Date | undefined;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* One self-contained HTML page: the verdict, failures first (with the trace id to look up and, when asked, the message), the tests that
|
|
18
|
+
* only passed after retries, the slowest tests, and every test by suite. No scripts and no external files: a content-security-policy
|
|
19
|
+
* forbids both, and every test title, message and fact is escaped. Failure messages are left out unless `messages` is true.
|
|
20
|
+
*/
|
|
21
|
+
export declare function renderHtmlReport(results: readonly TestCaseResult[], options?: HtmlReportOptions): string;
|
|
22
|
+
/** Writes the report (see `renderHtmlReport`) and creates its folder. The file is readable by its owner only, like the other reports. */
|
|
23
|
+
export declare function writeHtmlReport(path: string, results: readonly TestCaseResult[], options?: HtmlReportOptions): Promise<void>;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
const SLOWEST = 10;
|
|
4
|
+
const STYLE = `
|
|
5
|
+
:root{color-scheme:light dark;--bg:#fff;--fg:#1c2128;--muted:#656d76;--line:#d0d7de;--pass:#1a7f37;--fail:#cf222e;--skip:#6e7781;--flaky:#9a6700;--soft:#f6f8fa}
|
|
6
|
+
@media (prefers-color-scheme:dark){:root{--bg:#0d1117;--fg:#e6edf3;--muted:#8b949e;--line:#30363d;--pass:#3fb950;--fail:#f85149;--skip:#8b949e;--flaky:#d29922;--soft:#161b22}}
|
|
7
|
+
body{margin:0 auto;max-width:960px;padding:24px 16px;background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,sans-serif}
|
|
8
|
+
h1{font-size:22px;margin:0 0 4px}h2{font-size:17px;margin:28px 0 8px;border-bottom:1px solid var(--line);padding-bottom:4px}h3{font-size:14px;margin:18px 0 4px}
|
|
9
|
+
.muted{color:var(--muted)}.verdict{font-weight:600;font-size:16px;margin:12px 0}.pass{color:var(--pass)}.fail{color:var(--fail)}.skip{color:var(--skip)}.flaky{color:var(--flaky)}
|
|
10
|
+
.note{border-left:4px solid var(--flaky);background:var(--soft);padding:8px 12px;margin:8px 0}.note.problem{border-left-color:var(--fail)}
|
|
11
|
+
table{border-collapse:collapse;width:100%}td,th{padding:4px 8px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}th{color:var(--muted);font-weight:600}
|
|
12
|
+
td.s{width:56px;font-weight:600;font-size:12px}td.n{white-space:nowrap;text-align:right;color:var(--muted);width:80px}
|
|
13
|
+
details{border:1px solid var(--line);border-radius:6px;margin:8px 0;padding:6px 12px}summary{cursor:pointer;font-weight:600}
|
|
14
|
+
pre{background:var(--soft);padding:8px 12px;border-radius:6px;overflow-x:auto;white-space:pre-wrap;word-break:break-word}code{background:var(--soft);padding:1px 5px;border-radius:4px}
|
|
15
|
+
.stats{display:flex;flex-wrap:wrap;gap:8px 24px;margin:8px 0}.stats div{min-width:72px}.stats b{display:block;font-size:20px}
|
|
16
|
+
`;
|
|
17
|
+
function escapeHtml(text) {
|
|
18
|
+
return text.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character] ?? character);
|
|
19
|
+
}
|
|
20
|
+
function duration(ms) { return ms >= 1000 ? `${(ms / 1000).toFixed(1)} s` : `${Math.round(ms)} ms`; }
|
|
21
|
+
function plural(count, one, many) { return `${count} ${count === 1 ? one : many}`; }
|
|
22
|
+
const isFlaky = (result) => result.status === 'passed' && (result.retries ?? 0) > 0;
|
|
23
|
+
function verdictOf(result) {
|
|
24
|
+
if (result.status === 'failed')
|
|
25
|
+
return { word: 'FAIL', css: 'fail' };
|
|
26
|
+
if (result.status === 'skipped')
|
|
27
|
+
return { word: 'SKIP', css: 'skip' };
|
|
28
|
+
return isFlaky(result) ? { word: 'FLAKY', css: 'flaky' } : { word: 'PASS', css: 'pass' };
|
|
29
|
+
}
|
|
30
|
+
function shortName(result) {
|
|
31
|
+
return result.suite !== '' && result.name.startsWith(`${result.suite} `) ? result.name.slice(result.suite.length + 1) : result.name;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* One self-contained HTML page: the verdict, failures first (with the trace id to look up and, when asked, the message), the tests that
|
|
35
|
+
* only passed after retries, the slowest tests, and every test by suite. No scripts and no external files: a content-security-policy
|
|
36
|
+
* forbids both, and every test title, message and fact is escaped. Failure messages are left out unless `messages` is true.
|
|
37
|
+
*/
|
|
38
|
+
export function renderHtmlReport(results, options = {}) {
|
|
39
|
+
const title = options.title ?? 'API test report';
|
|
40
|
+
const failed = results.filter(result => result.status === 'failed');
|
|
41
|
+
const skipped = results.filter(result => result.status === 'skipped');
|
|
42
|
+
const flaky = results.filter(isFlaky);
|
|
43
|
+
const passed = results.filter(result => result.status === 'passed');
|
|
44
|
+
const totalMs = results.reduce((sum, result) => sum + result.durationMs, 0);
|
|
45
|
+
const out = [];
|
|
46
|
+
out.push(`<h1>${escapeHtml(title)}</h1>`, `<div class="muted">Generated ${escapeHtml((options.generatedAt ?? new Date()).toISOString())}</div>`);
|
|
47
|
+
const problems = options.problems ?? [];
|
|
48
|
+
for (const problem of problems)
|
|
49
|
+
out.push(`<div class="note problem">${escapeHtml(problem)}</div>`);
|
|
50
|
+
for (const note of options.notes ?? [])
|
|
51
|
+
out.push(`<div class="note">${escapeHtml(note)}</div>`);
|
|
52
|
+
if (failed.length || problems.length) {
|
|
53
|
+
const parts = [failed.length ? `${plural(failed.length, 'test', 'tests')} of ${results.length} failed` : '', problems.length ? `${plural(problems.length, 'problem', 'problems')} outside the tests` : ''].filter(Boolean);
|
|
54
|
+
out.push(`<div class="verdict fail">FAILED: ${parts.join(', and ')}</div>`);
|
|
55
|
+
}
|
|
56
|
+
else if (results.length === 0)
|
|
57
|
+
out.push('<div class="verdict muted">No tests were recorded</div>');
|
|
58
|
+
else
|
|
59
|
+
out.push(`<div class="verdict pass">PASSED: ${plural(passed.length, 'test', 'tests')}${flaky.length ? `, ${flaky.length} of them only after retries` : ''}</div>`);
|
|
60
|
+
out.push('<div class="stats">', `<div><b>${results.length}</b>tests</div>`, `<div><b class="pass">${passed.length}</b>passed</div>`, `<div><b class="fail">${failed.length}</b>failed</div>`, `<div><b class="skip">${skipped.length}</b>skipped</div>`, `<div><b class="flaky">${flaky.length}</b>flaky</div>`, `<div><b>${escapeHtml(duration(totalMs))}</b>in tests</div>`, '</div>');
|
|
61
|
+
if (options.facts?.length) {
|
|
62
|
+
out.push('<table>', ...options.facts.map(([name, value]) => `<tr><th>${escapeHtml(name)}</th><td>${escapeHtml(value)}</td></tr>`), '</table>');
|
|
63
|
+
}
|
|
64
|
+
if (failed.length) {
|
|
65
|
+
out.push('<h2>Failures</h2>');
|
|
66
|
+
for (const result of failed) {
|
|
67
|
+
out.push(`<details open><summary class="fail">FAIL <span class="muted">${escapeHtml(result.suite)}</span> ${escapeHtml(shortName(result))} <span class="muted">${escapeHtml(duration(result.durationMs))}</span></summary>`);
|
|
68
|
+
if ((result.retries ?? 0) > 0)
|
|
69
|
+
out.push(`<p>Still failing after ${plural(result.retries ?? 0, 'retry', 'retries')}.</p>`);
|
|
70
|
+
if (result.traceId !== undefined)
|
|
71
|
+
out.push(`<p>Trace id: <code>${escapeHtml(result.traceId)}</code></p>`);
|
|
72
|
+
if (options.messages === true && result.message !== undefined)
|
|
73
|
+
out.push(`<pre>${escapeHtml(result.message)}</pre>`);
|
|
74
|
+
else
|
|
75
|
+
out.push('<p class="muted">The failure message is not included in this report.</p>');
|
|
76
|
+
out.push('</details>');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (flaky.length) {
|
|
80
|
+
out.push('<h2>Passed only after retries</h2>', '<p class="muted">These tests failed at least once and then passed. A test that needs a retry is a flaky test: fix it instead of relying on the retry.</p>', '<table>');
|
|
81
|
+
for (const result of flaky)
|
|
82
|
+
out.push(`<tr><td class="s flaky">FLAKY</td><td>${escapeHtml(result.name)}${result.traceId === undefined ? '' : ` <code>${escapeHtml(result.traceId)}</code>`}</td><td class="n">${escapeHtml(plural(result.retries ?? 0, 'retry', 'retries'))}</td></tr>`);
|
|
83
|
+
out.push('</table>');
|
|
84
|
+
}
|
|
85
|
+
const slowest = results.filter(result => result.status !== 'skipped').sort((a, b) => b.durationMs - a.durationMs || a.name.localeCompare(b.name)).slice(0, SLOWEST);
|
|
86
|
+
if (slowest.length) {
|
|
87
|
+
out.push(`<h2>Slowest ${plural(slowest.length, 'test', 'tests')}</h2>`, '<table>');
|
|
88
|
+
for (const result of slowest)
|
|
89
|
+
out.push(`<tr><td>${escapeHtml(result.name)}</td><td class="n">${escapeHtml(duration(result.durationMs))}</td></tr>`);
|
|
90
|
+
out.push('</table>');
|
|
91
|
+
}
|
|
92
|
+
if (results.length) {
|
|
93
|
+
out.push('<h2>All tests</h2>');
|
|
94
|
+
const suites = new Map();
|
|
95
|
+
for (const result of results)
|
|
96
|
+
suites.set(result.suite, [...(suites.get(result.suite) ?? []), result]);
|
|
97
|
+
for (const [suite, members] of suites) {
|
|
98
|
+
out.push(`<h3>${escapeHtml(suite === '' ? '(no suite)' : suite)}</h3>`, '<table>');
|
|
99
|
+
for (const result of members) {
|
|
100
|
+
const { word, css } = verdictOf(result);
|
|
101
|
+
out.push(`<tr><td class="s ${css}">${word}</td><td>${escapeHtml(shortName(result))}${isFlaky(result) ? ` <span class="flaky">(${escapeHtml(plural(result.retries ?? 0, 'retry', 'retries'))})</span>` : ''}</td><td class="n">${escapeHtml(duration(result.durationMs))}</td></tr>`);
|
|
102
|
+
}
|
|
103
|
+
out.push('</table>');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return `<!doctype html>
|
|
107
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
108
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
|
|
109
|
+
<title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body>
|
|
110
|
+
${out.join('\n')}
|
|
111
|
+
</body></html>
|
|
112
|
+
`;
|
|
113
|
+
}
|
|
114
|
+
/** Writes the report (see `renderHtmlReport`) and creates its folder. The file is readable by its owner only, like the other reports. */
|
|
115
|
+
export async function writeHtmlReport(path, results, options = {}) {
|
|
116
|
+
await mkdir(dirname(path), { recursive: true });
|
|
117
|
+
await writeFile(path, renderHtmlReport(results, options), { encoding: 'utf8', mode: 0o600 });
|
|
118
|
+
}
|
|
@@ -3,7 +3,16 @@ export interface TestCaseResult {
|
|
|
3
3
|
suite: string;
|
|
4
4
|
durationMs: number;
|
|
5
5
|
status: 'passed' | 'failed' | 'skipped';
|
|
6
|
+
/** Why it failed. The collector keeps it scrubbed and shortened; reports leave it out unless asked. */
|
|
6
7
|
message?: string;
|
|
8
|
+
/** How many retries a test needed. A test that passed after retries is flaky. */
|
|
9
|
+
retries?: number;
|
|
10
|
+
/** The trace the test's requests joined, to look up what the server did. */
|
|
11
|
+
traceId?: string;
|
|
7
12
|
}
|
|
8
|
-
|
|
9
|
-
|
|
13
|
+
export interface JunitOptions {
|
|
14
|
+
/** Put each failure's message in the file. Default false: a failure says only "Test failed", because a message can quote data. */
|
|
15
|
+
messages?: boolean | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** Metadata-only JUnit writer; never include request payloads, secrets or response bodies in messages. Messages are opt-in. */
|
|
18
|
+
export declare function writeJunit(path: string, cases: readonly TestCaseResult[], options?: JunitOptions): Promise<void>;
|
package/dist/reporting/junit.js
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
3
|
function escapeXml(input) { return input.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); }
|
|
4
|
-
/** Metadata-only JUnit writer; never include request payloads, secrets or response bodies in messages. */
|
|
5
|
-
export async function writeJunit(path, cases) {
|
|
4
|
+
/** Metadata-only JUnit writer; never include request payloads, secrets or response bodies in messages. Messages are opt-in. */
|
|
5
|
+
export async function writeJunit(path, cases, options = {}) {
|
|
6
6
|
const failed = cases.filter(c => c.status === 'failed').length;
|
|
7
7
|
const skipped = cases.filter(c => c.status === 'skipped').length;
|
|
8
8
|
const rows = cases.map(c => {
|
|
9
|
-
|
|
9
|
+
let content = '';
|
|
10
|
+
if (c.status === 'skipped')
|
|
11
|
+
content = '<skipped/>';
|
|
12
|
+
else if (c.status === 'failed') {
|
|
13
|
+
const message = options.messages === true ? c.message : undefined;
|
|
14
|
+
content = message === undefined ? '<failure message="Test failed"/>' : `<failure message="${escapeXml(message.split('\n', 1)[0] ?? '')}">${escapeXml(message)}</failure>`;
|
|
15
|
+
}
|
|
10
16
|
return `<testcase classname="${escapeXml(c.suite)}" name="${escapeXml(c.name)}" time="${(c.durationMs / 1000).toFixed(3)}">${content}</testcase>`;
|
|
11
17
|
}).join('');
|
|
12
18
|
const xml = `<?xml version="1.0" encoding="UTF-8"?><testsuite name="qe-api" tests="${cases.length}" failures="${failed}" skipped="${skipped}">${rows}</testsuite>`;
|
|
@@ -1,2 +1,12 @@
|
|
|
1
|
+
/** Splits a property or header name into lowercase words: accountNumber, account_number and Account-Number all give [account, number]. */
|
|
2
|
+
export declare function keyWords(key: string): string[];
|
|
3
|
+
/** Names what a string looks like when it holds a credential, or undefined. Never returns the value itself. */
|
|
4
|
+
export declare function credentialIn(text: string): string | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* Masks credentials in free text that reaches a report, such as a failure message: everything `redact` masks in a string (Authorization
|
|
7
|
+
* values, JWTs, Luhn-valid card numbers) plus private key blocks and cloud access keys. It cannot know what else is private: a message
|
|
8
|
+
* that quotes data still quotes it, which is why reports leave messages out unless asked.
|
|
9
|
+
*/
|
|
10
|
+
export declare function scrubText(text: string): string;
|
|
1
11
|
/** For structured event metadata only. Never attach raw banking payloads to test reports. */
|
|
2
12
|
export declare function redact(value: unknown, depth?: number): unknown;
|
|
@@ -9,13 +9,17 @@ const SECRET_WORDS = new Set(['pin', 'otp', 'cvv', 'cvc', 'pan', 'iban', 'ssn'])
|
|
|
9
9
|
const BEARER_OR_BASIC = /\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/]+=*/gi;
|
|
10
10
|
const JWT = /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g;
|
|
11
11
|
const CARD_NUMBER = /\b[2-6](?:[ -]?\d){12,18}\b/g;
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
/** Splits a property or header name into lowercase words: accountNumber, account_number and Account-Number all give [account, number]. */
|
|
13
|
+
export function keyWords(key) {
|
|
14
|
+
return key
|
|
14
15
|
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
15
16
|
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
|
|
16
17
|
.toLowerCase()
|
|
17
18
|
.split(/[^a-z0-9]+/)
|
|
18
19
|
.filter(Boolean);
|
|
20
|
+
}
|
|
21
|
+
function isSecretKey(key) {
|
|
22
|
+
const words = keyWords(key);
|
|
19
23
|
if (words.some(word => SECRET_WORDS.has(word)))
|
|
20
24
|
return true;
|
|
21
25
|
const compact = words.join('');
|
|
@@ -36,6 +40,26 @@ function passesLuhn(digits) {
|
|
|
36
40
|
}
|
|
37
41
|
return sum % 10 === 0;
|
|
38
42
|
}
|
|
43
|
+
const BEARER_VALUE = /\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/]{16,}=*/i;
|
|
44
|
+
const PRIVATE_KEY = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
|
|
45
|
+
const CLOUD_KEY = /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/;
|
|
46
|
+
/** Names what a string looks like when it holds a credential, or undefined. Never returns the value itself. */
|
|
47
|
+
export function credentialIn(text) {
|
|
48
|
+
if (text.search(JWT) >= 0)
|
|
49
|
+
return 'a JSON Web Token';
|
|
50
|
+
if (PRIVATE_KEY.test(text))
|
|
51
|
+
return 'a private key';
|
|
52
|
+
if (CLOUD_KEY.test(text))
|
|
53
|
+
return 'a cloud access key';
|
|
54
|
+
if (BEARER_VALUE.test(text))
|
|
55
|
+
return 'an Authorization credential';
|
|
56
|
+
for (const found of text.matchAll(CARD_NUMBER)) {
|
|
57
|
+
const digits = found[0].replace(/[ -]/g, '');
|
|
58
|
+
if (digits.length >= 13 && digits.length <= 19 && passesLuhn(digits))
|
|
59
|
+
return 'a card number';
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
39
63
|
/** Masks credentials that appear inside free text: Authorization-style values, JWTs and Luhn-valid card numbers. */
|
|
40
64
|
function scrubString(text) {
|
|
41
65
|
return text
|
|
@@ -46,6 +70,16 @@ function scrubString(text) {
|
|
|
46
70
|
return digits.length >= 13 && digits.length <= 19 && passesLuhn(digits) ? REDACTED : match;
|
|
47
71
|
});
|
|
48
72
|
}
|
|
73
|
+
const PRIVATE_KEY_BLOCK = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g;
|
|
74
|
+
const CLOUD_ACCESS_KEY = /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g;
|
|
75
|
+
/**
|
|
76
|
+
* Masks credentials in free text that reaches a report, such as a failure message: everything `redact` masks in a string (Authorization
|
|
77
|
+
* values, JWTs, Luhn-valid card numbers) plus private key blocks and cloud access keys. It cannot know what else is private: a message
|
|
78
|
+
* that quotes data still quotes it, which is why reports leave messages out unless asked.
|
|
79
|
+
*/
|
|
80
|
+
export function scrubText(text) {
|
|
81
|
+
return scrubString(text.replace(PRIVATE_KEY_BLOCK, REDACTED).replace(CLOUD_ACCESS_KEY, REDACTED));
|
|
82
|
+
}
|
|
49
83
|
/** For structured event metadata only. Never attach raw banking payloads to test reports. */
|
|
50
84
|
export function redact(value, depth = 0) {
|
|
51
85
|
if (depth > 15)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { ApiRequest, ApiResult } from '../http/types.js';
|
|
2
|
+
/** Anything that sends requests as one identity: an `ApiClient` configured with that identity's credentials fits. */
|
|
3
|
+
export interface AuthorizationSubject {
|
|
4
|
+
request(request: ApiRequest): Promise<Pick<ApiResult, 'status'>>;
|
|
5
|
+
}
|
|
6
|
+
export interface AuthorizationRule {
|
|
7
|
+
/** Shown in reports. Default: "METHOD /path". */
|
|
8
|
+
name?: string | undefined;
|
|
9
|
+
request: ApiRequest;
|
|
10
|
+
/** Subjects that may do this. */
|
|
11
|
+
allow?: readonly string[] | undefined;
|
|
12
|
+
/** Subjects that must be refused. */
|
|
13
|
+
deny?: readonly string[] | undefined;
|
|
14
|
+
/** Statuses that count as "refused" for this rule. Default 401 and 403: add 404 when the API hides what exists. */
|
|
15
|
+
deniedStatuses?: readonly number[] | undefined;
|
|
16
|
+
}
|
|
17
|
+
export interface AuthorizationMatrixOptions {
|
|
18
|
+
/** Statuses that count as "refused" for every rule. Default 401 and 403. */
|
|
19
|
+
deniedStatuses?: readonly number[] | undefined;
|
|
20
|
+
/** Require every rule to say what happens for every subject. Default false: unlisted subjects are simply not tested. */
|
|
21
|
+
strict?: boolean | undefined;
|
|
22
|
+
}
|
|
23
|
+
export interface AuthorizationCell {
|
|
24
|
+
rule: string;
|
|
25
|
+
subject: string;
|
|
26
|
+
expectation: 'allow' | 'deny';
|
|
27
|
+
/** Undefined when the request itself failed. */
|
|
28
|
+
status?: number | undefined;
|
|
29
|
+
ok: boolean;
|
|
30
|
+
problem?: string | undefined;
|
|
31
|
+
}
|
|
32
|
+
export interface AuthorizationReport {
|
|
33
|
+
cells: AuthorizationCell[];
|
|
34
|
+
violations: AuthorizationCell[];
|
|
35
|
+
ok: boolean;
|
|
36
|
+
/** A table of rules by subjects: ✅ as expected, ❌ not, — not tested. Statuses only, never bodies. */
|
|
37
|
+
toMarkdown(): string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Checks who may do what: function-level authorization (can a user call an admin operation?) and object-level authorization
|
|
41
|
+
* (can user B read user A's account?). Each rule names the subjects that may and must not; the matrix sends the request as each one
|
|
42
|
+
* and compares the status. Refusals are tested before grants, so a destructive request that wrongly succeeds for a subject who
|
|
43
|
+
* must be denied is reported on its own cell instead of breaking the grants that follow. Use disposable resources for destructive rules.
|
|
44
|
+
*/
|
|
45
|
+
export declare class AuthorizationMatrix {
|
|
46
|
+
private readonly subjects;
|
|
47
|
+
private readonly options;
|
|
48
|
+
constructor(subjects: Readonly<Record<string, AuthorizationSubject>>, options?: AuthorizationMatrixOptions);
|
|
49
|
+
run(rules: readonly AuthorizationRule[]): Promise<AuthorizationReport>;
|
|
50
|
+
/** Runs the rules and throws, listing every violation, unless all behave as expected. Returns the report. */
|
|
51
|
+
assert(rules: readonly AuthorizationRule[]): Promise<AuthorizationReport>;
|
|
52
|
+
private plan;
|
|
53
|
+
private execute;
|
|
54
|
+
private table;
|
|
55
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
/**
|
|
3
|
+
* Checks who may do what: function-level authorization (can a user call an admin operation?) and object-level authorization
|
|
4
|
+
* (can user B read user A's account?). Each rule names the subjects that may and must not; the matrix sends the request as each one
|
|
5
|
+
* and compares the status. Refusals are tested before grants, so a destructive request that wrongly succeeds for a subject who
|
|
6
|
+
* must be denied is reported on its own cell instead of breaking the grants that follow. Use disposable resources for destructive rules.
|
|
7
|
+
*/
|
|
8
|
+
export class AuthorizationMatrix {
|
|
9
|
+
subjects;
|
|
10
|
+
options;
|
|
11
|
+
constructor(subjects, options = {}) {
|
|
12
|
+
this.subjects = subjects;
|
|
13
|
+
this.options = options;
|
|
14
|
+
if (!Object.keys(subjects).length)
|
|
15
|
+
throw new Error('An authorization matrix needs at least one subject');
|
|
16
|
+
}
|
|
17
|
+
async run(rules) {
|
|
18
|
+
const plans = this.plan(rules);
|
|
19
|
+
const results = new Map();
|
|
20
|
+
for (const plan of [...plans.filter(entry => entry.expectation === 'deny'), ...plans.filter(entry => entry.expectation === 'allow')]) {
|
|
21
|
+
results.set(plan, await this.execute(plan));
|
|
22
|
+
}
|
|
23
|
+
const cells = plans.map(plan => results.get(plan));
|
|
24
|
+
const violations = cells.filter(cell => !cell.ok);
|
|
25
|
+
return { cells, violations, ok: violations.length === 0, toMarkdown: () => this.table(rules, plans, results) };
|
|
26
|
+
}
|
|
27
|
+
/** Runs the rules and throws, listing every violation, unless all behave as expected. Returns the report. */
|
|
28
|
+
async assert(rules) {
|
|
29
|
+
const report = await this.run(rules);
|
|
30
|
+
if (!report.ok) {
|
|
31
|
+
const shown = report.violations.map(cell => `- ${cell.rule} as ${cell.subject}: ${cell.problem ?? 'unexpected result'}`);
|
|
32
|
+
assert.fail(`Authorization check failed in ${report.violations.length} of ${report.cells.length} cases:\n${shown.join('\n')}\n\n${report.toMarkdown()}`);
|
|
33
|
+
}
|
|
34
|
+
return report;
|
|
35
|
+
}
|
|
36
|
+
plan(rules) {
|
|
37
|
+
const known = Object.keys(this.subjects);
|
|
38
|
+
const plans = [];
|
|
39
|
+
rules.forEach((rule, ruleIndex) => {
|
|
40
|
+
const name = rule.name ?? `${rule.request.method} ${rule.request.path}`;
|
|
41
|
+
const allow = rule.allow ?? [];
|
|
42
|
+
const deny = rule.deny ?? [];
|
|
43
|
+
if (!allow.length && !deny.length)
|
|
44
|
+
throw new Error(`Rule "${name}" names no subjects`);
|
|
45
|
+
for (const subject of [...allow, ...deny])
|
|
46
|
+
if (!known.includes(subject))
|
|
47
|
+
throw new Error(`Rule "${name}" names an unknown subject "${subject}"`);
|
|
48
|
+
for (const subject of allow)
|
|
49
|
+
if (deny.includes(subject))
|
|
50
|
+
throw new Error(`Rule "${name}" both allows and denies "${subject}"`);
|
|
51
|
+
if (this.options.strict === true) {
|
|
52
|
+
const missing = known.filter(subject => !allow.includes(subject) && !deny.includes(subject));
|
|
53
|
+
if (missing.length)
|
|
54
|
+
throw new Error(`Rule "${name}" does not say what happens for: ${missing.join(', ')}`);
|
|
55
|
+
}
|
|
56
|
+
for (const subject of known) {
|
|
57
|
+
if (allow.includes(subject))
|
|
58
|
+
plans.push({ ruleIndex, rule, name, subject, expectation: 'allow' });
|
|
59
|
+
else if (deny.includes(subject))
|
|
60
|
+
plans.push({ ruleIndex, rule, name, subject, expectation: 'deny' });
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
return plans;
|
|
64
|
+
}
|
|
65
|
+
async execute(plan) {
|
|
66
|
+
const base = { rule: plan.name, subject: plan.subject, expectation: plan.expectation };
|
|
67
|
+
const subject = this.subjects[plan.subject];
|
|
68
|
+
if (!subject)
|
|
69
|
+
throw new Error(`Unknown subject "${plan.subject}"`);
|
|
70
|
+
let status;
|
|
71
|
+
try {
|
|
72
|
+
status = (await subject.request(plan.rule.request)).status;
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
return { ...base, ok: false, problem: `the request failed (${error instanceof Error ? error.name : 'error'})` };
|
|
76
|
+
}
|
|
77
|
+
const denied = plan.rule.deniedStatuses ?? this.options.deniedStatuses ?? [401, 403];
|
|
78
|
+
const granted = status >= 200 && status < 300;
|
|
79
|
+
if (status >= 500)
|
|
80
|
+
return { ...base, status, ok: false, problem: `the server failed with HTTP ${status} instead of ${plan.expectation === 'deny' ? 'refusing' : 'answering'}` };
|
|
81
|
+
if (plan.expectation === 'deny') {
|
|
82
|
+
if (denied.includes(status))
|
|
83
|
+
return { ...base, status, ok: true };
|
|
84
|
+
return { ...base, status, ok: false, problem: granted ? `access was granted (HTTP ${status}) but must be refused` : `refused with HTTP ${status}, not ${denied.join(' or ')} (if the API hides what exists, add ${status} to deniedStatuses)` };
|
|
85
|
+
}
|
|
86
|
+
if (status >= 200 && status < 300)
|
|
87
|
+
return { ...base, status, ok: true };
|
|
88
|
+
return { ...base, status, ok: false, problem: denied.includes(status) ? `access was refused (HTTP ${status}) but is allowed` : `unexpected HTTP ${status} for an allowed request` };
|
|
89
|
+
}
|
|
90
|
+
table(rules, plans, results) {
|
|
91
|
+
const names = Object.keys(this.subjects);
|
|
92
|
+
const rows = rules.map((rule, ruleIndex) => {
|
|
93
|
+
const cells = names.map(subject => {
|
|
94
|
+
const plan = plans.find(entry => entry.ruleIndex === ruleIndex && entry.subject === subject);
|
|
95
|
+
const cell = plan ? results.get(plan) : undefined;
|
|
96
|
+
return cell === undefined ? '—' : `${cell.ok ? '✅' : '❌'} ${cell.status ?? 'error'}`;
|
|
97
|
+
});
|
|
98
|
+
return `| ${rule.name ?? `${rule.request.method} ${rule.request.path}`} | ${cells.join(' | ')} |`;
|
|
99
|
+
});
|
|
100
|
+
return [`| Request | ${names.join(' | ')} |`, `|---|${names.map(() => '---').join('|')}|`, ...rows].join('\n');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ApiResult } from '../http/types.js';
|
|
2
|
+
export type Severity = 'high' | 'medium' | 'low';
|
|
3
|
+
export interface HeaderFinding {
|
|
4
|
+
header: string;
|
|
5
|
+
severity: Severity;
|
|
6
|
+
problem: string;
|
|
7
|
+
}
|
|
8
|
+
export interface SecurityHeaderOptions {
|
|
9
|
+
/** The API is served over https: require Strict-Transport-Security. Default false (a header sent over http has no effect). */
|
|
10
|
+
https?: boolean | undefined;
|
|
11
|
+
/** The response holds sensitive data: require `Cache-Control: no-store`. Default false. */
|
|
12
|
+
sensitive?: boolean | undefined;
|
|
13
|
+
/** For `expectSecurityHeaders`: the lowest severity that fails. Default 'medium'. */
|
|
14
|
+
failOn?: Severity | undefined;
|
|
15
|
+
/** Headers whose findings are accepted, e.g. ['x-powered-by']. */
|
|
16
|
+
ignore?: readonly string[] | undefined;
|
|
17
|
+
}
|
|
18
|
+
/** Header hygiene for an API response. Findings name the header and the problem; values are never quoted. */
|
|
19
|
+
export declare function checkSecurityHeaders(response: Pick<ApiResult, 'headers'>, options?: SecurityHeaderOptions): HeaderFinding[];
|
|
20
|
+
/** Fails when a finding at or above `failOn` (default medium) exists. */
|
|
21
|
+
export declare function expectSecurityHeaders(response: Pick<ApiResult, 'headers'>, options?: SecurityHeaderOptions): void;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
const RANK = { high: 3, medium: 2, low: 1 };
|
|
3
|
+
const SIX_MONTHS_SECONDS = 15_552_000;
|
|
4
|
+
/** Header hygiene for an API response. Findings name the header and the problem; values are never quoted. */
|
|
5
|
+
export function checkSecurityHeaders(response, options = {}) {
|
|
6
|
+
const headers = response.headers;
|
|
7
|
+
const found = [];
|
|
8
|
+
const add = (header, severity, problem) => { found.push({ header, severity, problem }); };
|
|
9
|
+
if (headers['x-content-type-options']?.toLowerCase() !== 'nosniff')
|
|
10
|
+
add('x-content-type-options', 'medium', 'should be "nosniff" so browsers do not guess the content type');
|
|
11
|
+
if (options.https === true) {
|
|
12
|
+
const hsts = headers['strict-transport-security'];
|
|
13
|
+
const maxAge = hsts === undefined ? undefined : /max-age\s*=\s*(\d+)/i.exec(hsts)?.[1];
|
|
14
|
+
if (hsts === undefined)
|
|
15
|
+
add('strict-transport-security', 'medium', 'is missing on an https API');
|
|
16
|
+
else if (maxAge === undefined || Number(maxAge) < SIX_MONTHS_SECONDS)
|
|
17
|
+
add('strict-transport-security', 'medium', 'max-age is missing or shorter than six months');
|
|
18
|
+
}
|
|
19
|
+
if (options.sensitive === true && !/\bno-store\b/i.test(headers['cache-control'] ?? ''))
|
|
20
|
+
add('cache-control', 'medium', 'should include "no-store" for a response with sensitive data');
|
|
21
|
+
const server = headers.server;
|
|
22
|
+
if (server !== undefined && /\d+\.\d+/.test(server))
|
|
23
|
+
add('server', 'low', 'reveals a software version number');
|
|
24
|
+
for (const name of ['x-powered-by', 'x-aspnet-version', 'x-aspnetmvc-version']) {
|
|
25
|
+
if (headers[name] !== undefined)
|
|
26
|
+
add(name, 'low', 'reveals the technology stack');
|
|
27
|
+
}
|
|
28
|
+
const origin = headers['access-control-allow-origin'];
|
|
29
|
+
if (origin === '*') {
|
|
30
|
+
if (headers['access-control-allow-credentials']?.toLowerCase() === 'true')
|
|
31
|
+
add('access-control-allow-origin', 'high', 'is "*" together with credentials allowed: any site can read authenticated responses');
|
|
32
|
+
else
|
|
33
|
+
add('access-control-allow-origin', 'low', 'is "*": any site can read this response');
|
|
34
|
+
}
|
|
35
|
+
const ignored = new Set((options.ignore ?? []).map(name => name.toLowerCase()));
|
|
36
|
+
return found.filter(finding => !ignored.has(finding.header));
|
|
37
|
+
}
|
|
38
|
+
/** Fails when a finding at or above `failOn` (default medium) exists. */
|
|
39
|
+
export function expectSecurityHeaders(response, options = {}) {
|
|
40
|
+
const threshold = RANK[options.failOn ?? 'medium'];
|
|
41
|
+
const failing = checkSecurityHeaders(response, options).filter(finding => RANK[finding.severity] >= threshold);
|
|
42
|
+
if (!failing.length)
|
|
43
|
+
return;
|
|
44
|
+
assert.fail(`Response headers have security problems:\n${failing.map(finding => `- ${finding.header}: ${finding.problem} (${finding.severity})`).join('\n')}`);
|
|
45
|
+
}
|