specshield 3.2.2 → 3.2.4
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 +75 -0
- package/README.md +468 -568
- package/package.json +4 -1
- package/src/cli.js +2 -0
- package/src/commands/bdct.js +180 -2
- package/src/commands/whoami.js +105 -0
- package/src/core/conformance/index.js +52 -0
- package/src/core/conformance/pathResolver.js +108 -0
- package/src/core/conformance/probeBuilder.js +92 -0
- package/src/core/conformance/responseValidator.js +114 -0
- package/src/core/conformance/runner.js +133 -0
- package/src/core/har/emitOpenapi.js +125 -0
- package/src/core/har/index.js +68 -0
- package/src/core/har/parseHar.js +136 -0
- package/src/core/har/pathTemplate.js +92 -0
- package/src/core/har/schemaInfer.js +100 -0
- package/src/util/versionStrip.js +24 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "specshield",
|
|
3
|
-
"version": "3.2.
|
|
3
|
+
"version": "3.2.4",
|
|
4
4
|
"description": "CLI for OpenAPI breaking change detection and bi-directional contract verification — with can-i-deploy gating, GitHub PR checks, and a first-run setup wizard.",
|
|
5
5
|
"main": "src/cli.js",
|
|
6
6
|
"bin": {
|
|
@@ -54,6 +54,9 @@
|
|
|
54
54
|
"LICENSE"
|
|
55
55
|
],
|
|
56
56
|
"dependencies": {
|
|
57
|
+
"@apidevtools/swagger-parser": "^10.1.1",
|
|
58
|
+
"ajv": "^8.20.0",
|
|
59
|
+
"ajv-formats": "^3.0.1",
|
|
57
60
|
"axios": "^1.6.7",
|
|
58
61
|
"chalk": "^4.1.2",
|
|
59
62
|
"commander": "^12.0.0",
|
package/src/cli.js
CHANGED
|
@@ -9,6 +9,7 @@ const logoutCommand = require('./commands/logout');
|
|
|
9
9
|
const bdctCommand = require('./commands/bdct');
|
|
10
10
|
const historyCommand = require('./commands/history');
|
|
11
11
|
const shareCommand = require('./commands/share');
|
|
12
|
+
const whoamiCommand = require('./commands/whoami');
|
|
12
13
|
|
|
13
14
|
const program = new Command();
|
|
14
15
|
|
|
@@ -28,6 +29,7 @@ program.addCommand(logoutCommand);
|
|
|
28
29
|
program.addCommand(bdctCommand);
|
|
29
30
|
program.addCommand(historyCommand);
|
|
30
31
|
program.addCommand(shareCommand);
|
|
32
|
+
program.addCommand(whoamiCommand);
|
|
31
33
|
|
|
32
34
|
program.parseAsync(process.argv).catch((err) => {
|
|
33
35
|
const logger = require('./utils/logger');
|
package/src/commands/bdct.js
CHANGED
|
@@ -70,6 +70,8 @@ function hr() {
|
|
|
70
70
|
return chalk.gray(' ─────────────────────────────────────────────────────');
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
const { stripVersionPrefix } = require('../util/versionStrip');
|
|
74
|
+
|
|
73
75
|
/**
|
|
74
76
|
* Flatten a verification result's mismatches.
|
|
75
77
|
* Current backend returns `resultJson` (JSON string of [{endpoint,status,mismatches:[...]}]).
|
|
@@ -275,6 +277,11 @@ const verifyCommand = new Command('verify')
|
|
|
275
277
|
const token = await resolveApiToken(opts);
|
|
276
278
|
requireToken(token);
|
|
277
279
|
|
|
280
|
+
// Tolerate a leading `v` on either version (see can-i-deploy for the
|
|
281
|
+
// full rationale — readers paste back display values like `v1.0.0`).
|
|
282
|
+
opts.consumerVersion = stripVersionPrefix(opts.consumerVersion);
|
|
283
|
+
opts.providerVersion = stripVersionPrefix(opts.providerVersion);
|
|
284
|
+
|
|
278
285
|
const spinner = opts.json ? null : ora(`Verifying ${opts.consumer} → ${opts.provider}...`).start();
|
|
279
286
|
|
|
280
287
|
try {
|
|
@@ -361,6 +368,13 @@ const canIDeployCommand = new Command('can-i-deploy')
|
|
|
361
368
|
const token = await resolveApiToken(opts);
|
|
362
369
|
requireToken(token);
|
|
363
370
|
|
|
371
|
+
// Both the UI and the CLI render versions as `v<version>` for readability.
|
|
372
|
+
// When a user reads that and pastes it back into `--version`, the query
|
|
373
|
+
// silently matches nothing (the stored value never has a leading `v`).
|
|
374
|
+
// Strip a `v` that's followed by a digit, then use the cleaned version
|
|
375
|
+
// for the network call AND the human display so we never print `vv…`.
|
|
376
|
+
opts.version = stripVersionPrefix(opts.version);
|
|
377
|
+
|
|
364
378
|
const spinner = opts.json ? null : ora(`Checking deployment safety for ${opts.service}@${opts.version}...`).start();
|
|
365
379
|
|
|
366
380
|
try {
|
|
@@ -380,11 +394,15 @@ const canIDeployCommand = new Command('can-i-deploy')
|
|
|
380
394
|
process.exit(deployable ? 0 : 1);
|
|
381
395
|
}
|
|
382
396
|
|
|
397
|
+
// Idempotent `v` prefix on display — don't double it when the stored
|
|
398
|
+
// version legitimately starts with `v` (e.g. `vendor-tag-99`). Mirrors
|
|
399
|
+
// the UI pill at `BdctCanIDeploy.jsx:392`.
|
|
400
|
+
const vDisplay = /^v/i.test(opts.version) ? opts.version : `v${opts.version}`;
|
|
383
401
|
process.stdout.write('\n');
|
|
384
402
|
if (deployable) {
|
|
385
|
-
process.stdout.write(chalk.green.bold(' ✔ PASS') + chalk.white(`: ${opts.service}
|
|
403
|
+
process.stdout.write(chalk.green.bold(' ✔ PASS') + chalk.white(`: ${opts.service} ${vDisplay} is deployable${envLabel}\n`));
|
|
386
404
|
} else {
|
|
387
|
-
process.stdout.write(chalk.red.bold(' ✖ FAIL') + chalk.white(`: ${opts.service}
|
|
405
|
+
process.stdout.write(chalk.red.bold(' ✖ FAIL') + chalk.white(`: ${opts.service} ${vDisplay} is NOT deployable${envLabel}\n`));
|
|
388
406
|
}
|
|
389
407
|
process.stdout.write(hr() + '\n');
|
|
390
408
|
|
|
@@ -689,6 +707,164 @@ const listConsumersCommand = new Command('list-consumers')
|
|
|
689
707
|
}
|
|
690
708
|
});
|
|
691
709
|
|
|
710
|
+
// ─── capture (Fix 2 — turn recorded traffic into a consumer contract) ────────
|
|
711
|
+
// Reads a HAR file (any browser/Cypress/Playwright/k6 can export one) and
|
|
712
|
+
// emits an OpenAPI 3.0 consumer-contract subset describing only the
|
|
713
|
+
// endpoints/fields the consumer actually called/read. Pure local CLI work —
|
|
714
|
+
// no API token required.
|
|
715
|
+
|
|
716
|
+
const captureFromHarCommand = new Command('from-har')
|
|
717
|
+
.description('Generate a consumer OpenAPI contract from a recorded HAR file')
|
|
718
|
+
.requiredOption('--in <path>', 'Input HAR file (HTTP Archive 1.2)')
|
|
719
|
+
.option('--out <path>', 'Output file (default: write to stdout)')
|
|
720
|
+
.option('--base-url <url>', 'Keep only entries matching this URL prefix (e.g. https://api.acme.com or https://api.acme.com/v1)')
|
|
721
|
+
.option('--method <verbs>', 'Comma-separated methods to include (e.g. GET,POST). Default: all')
|
|
722
|
+
.option('--title <title>', 'OpenAPI info.title', 'Captured consumer contract')
|
|
723
|
+
.option('--version <ver>', 'OpenAPI info.version', '0.1.0')
|
|
724
|
+
.option('--format <fmt>', 'Output format: yaml | json', 'yaml')
|
|
725
|
+
.option('--include-non-json', 'Keep entries with non-JSON bodies (default: drop them)')
|
|
726
|
+
.action(async (opts) => {
|
|
727
|
+
const { captureFromHarFile } = require('../core/har');
|
|
728
|
+
const inputPath = path.resolve(opts.in);
|
|
729
|
+
if (!fsExtra.existsSync(inputPath)) {
|
|
730
|
+
logger.error(`HAR file not found: ${inputPath}`);
|
|
731
|
+
process.exit(2);
|
|
732
|
+
}
|
|
733
|
+
const methods = opts.method
|
|
734
|
+
? opts.method.split(',').map(s => s.trim()).filter(Boolean)
|
|
735
|
+
: undefined;
|
|
736
|
+
|
|
737
|
+
let result;
|
|
738
|
+
try {
|
|
739
|
+
result = captureFromHarFile(inputPath, {
|
|
740
|
+
baseUrl: opts.baseUrl,
|
|
741
|
+
methods,
|
|
742
|
+
onlyJson: !opts.includeNonJson,
|
|
743
|
+
title: opts.title,
|
|
744
|
+
version: opts.version,
|
|
745
|
+
format: opts.format,
|
|
746
|
+
});
|
|
747
|
+
} catch (err) {
|
|
748
|
+
logger.error(err.message);
|
|
749
|
+
process.exit(1);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
if (opts.out) {
|
|
753
|
+
const outPath = path.resolve(opts.out);
|
|
754
|
+
fsExtra.outputFileSync(outPath, result.text);
|
|
755
|
+
process.stderr.write(chalk.green('✔ ') +
|
|
756
|
+
`Wrote ${chalk.cyan(opts.out)} ` +
|
|
757
|
+
chalk.gray(`(${result.summary.endpoints} endpoints, ${result.summary.operations} ops from ${result.summary.recordsKept}/${result.summary.harEntries} entries)`) + '\n');
|
|
758
|
+
} else {
|
|
759
|
+
process.stdout.write(result.text);
|
|
760
|
+
process.stderr.write(chalk.gray(
|
|
761
|
+
`# ${result.summary.endpoints} endpoints, ${result.summary.operations} ops from ${result.summary.recordsKept}/${result.summary.harEntries} HAR entries\n`
|
|
762
|
+
));
|
|
763
|
+
}
|
|
764
|
+
});
|
|
765
|
+
|
|
766
|
+
const captureCommand = new Command('capture')
|
|
767
|
+
.description('Capture a consumer OpenAPI contract from observed traffic (currently: HAR ingest)');
|
|
768
|
+
captureCommand.addCommand(captureFromHarCommand);
|
|
769
|
+
|
|
770
|
+
// ─── verify-provider (Fix 3 — spec-vs-production conformance) ─────────────────
|
|
771
|
+
// Fires probes derived from the OpenAPI spec at the running provider and
|
|
772
|
+
// validates that every response body actually matches its documented schema.
|
|
773
|
+
// Pure local CLI work (calls the customer's service directly); no API token.
|
|
774
|
+
// Safe-by-default: only GET/HEAD/OPTIONS unless --include-mutating.
|
|
775
|
+
|
|
776
|
+
const verifyProviderCommand = new Command('verify-provider')
|
|
777
|
+
.description('Check that a running provider service matches its OpenAPI spec')
|
|
778
|
+
.requiredOption('--spec <path>', 'Path to the provider OpenAPI spec (YAML or JSON)')
|
|
779
|
+
.requiredOption('--base-url <url>', 'Base URL of the running provider, e.g. https://staging.payments.acme.com')
|
|
780
|
+
.option('--include-mutating', 'Also probe POST/PUT/PATCH/DELETE (off by default for safety)')
|
|
781
|
+
.option('--path-params <kvList>', 'Resolve path params: name=val,other=val (overrides spec examples)', collectPathParams, {})
|
|
782
|
+
.option('--header <header>', 'Extra request header to send, e.g. "Authorization: Bearer X" (repeatable)', collectHeaders, {})
|
|
783
|
+
.option('--timeout-ms <ms>', 'Per-request timeout in ms', v => parseInt(v, 10), 8000)
|
|
784
|
+
.option('--json', 'Output raw JSON instead of the human report')
|
|
785
|
+
.action(async (opts) => {
|
|
786
|
+
const { verifyProvider } = require('../core/conformance');
|
|
787
|
+
const specPath = path.resolve(opts.spec);
|
|
788
|
+
if (!fsExtra.existsSync(specPath)) {
|
|
789
|
+
logger.error(`Spec file not found: ${specPath}`);
|
|
790
|
+
process.exit(2);
|
|
791
|
+
}
|
|
792
|
+
const spinner = opts.json ? null : ora('Probing provider…').start();
|
|
793
|
+
let report;
|
|
794
|
+
try {
|
|
795
|
+
report = await verifyProvider({
|
|
796
|
+
spec: specPath,
|
|
797
|
+
baseUrl: opts.baseUrl,
|
|
798
|
+
includeMutating: !!opts.includeMutating,
|
|
799
|
+
pathParams: opts.pathParams,
|
|
800
|
+
headers: opts.header,
|
|
801
|
+
timeoutMs: opts.timeoutMs,
|
|
802
|
+
});
|
|
803
|
+
} catch (err) {
|
|
804
|
+
if (spinner) spinner.fail('Conformance run failed');
|
|
805
|
+
logger.error(err.message);
|
|
806
|
+
process.exit(1);
|
|
807
|
+
}
|
|
808
|
+
if (spinner) spinner.stop();
|
|
809
|
+
|
|
810
|
+
if (opts.json) {
|
|
811
|
+
process.stdout.write(JSON.stringify(report, null, 2) + '\n');
|
|
812
|
+
process.exit(report.summary.fail + report.summary.error > 0 ? 1 : 0);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// Human report.
|
|
816
|
+
process.stdout.write('\n' + chalk.bold(' Provider conformance — spec vs ') + chalk.cyan(opts.baseUrl) + '\n');
|
|
817
|
+
process.stdout.write(' ' + '─'.repeat(60) + '\n');
|
|
818
|
+
for (const r of report.results) {
|
|
819
|
+
const label = `${r.method.padEnd(6)} ${r.routePath}`;
|
|
820
|
+
const tag =
|
|
821
|
+
r.status === 'PASS' ? chalk.green(' PASS ') :
|
|
822
|
+
r.status === 'FAIL' ? chalk.red(' FAIL ') :
|
|
823
|
+
r.status === 'ERROR' ? chalk.red(' ERROR ') :
|
|
824
|
+
chalk.yellow(' SKIP ');
|
|
825
|
+
process.stdout.write(` ${tag} ${label}` +
|
|
826
|
+
(r.httpStatus ? chalk.gray(` (${r.httpStatus})`) : '') + '\n');
|
|
827
|
+
if (r.status === 'FAIL' && r.mismatches && r.mismatches.length > 0) {
|
|
828
|
+
for (const m of r.mismatches.slice(0, 5)) {
|
|
829
|
+
process.stdout.write(chalk.gray(` ${m.path || '(root)'}: ${m.message}\n`));
|
|
830
|
+
}
|
|
831
|
+
if (r.mismatches.length > 5) {
|
|
832
|
+
process.stdout.write(chalk.gray(` …and ${r.mismatches.length - 5} more\n`));
|
|
833
|
+
}
|
|
834
|
+
} else if (r.status === 'FAIL' && r.reason) {
|
|
835
|
+
process.stdout.write(chalk.gray(` ${r.reason}\n`));
|
|
836
|
+
} else if (r.status === 'ERROR') {
|
|
837
|
+
process.stdout.write(chalk.gray(` ${r.error}\n`));
|
|
838
|
+
} else if (r.status === 'SKIPPED') {
|
|
839
|
+
process.stdout.write(chalk.gray(` ${r.reason}: ${r.skipReason}\n`));
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
const s = report.summary;
|
|
843
|
+
process.stdout.write(' ' + '─'.repeat(60) + '\n');
|
|
844
|
+
process.stdout.write(` ${s.pass} pass · ${s.fail} fail · ${s.error} error · ${s.skipped} skip (${s.total} probes)\n\n`);
|
|
845
|
+
process.exit(s.fail + s.error > 0 ? 1 : 0);
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
// Repeatable --header parser: collects into a map.
|
|
849
|
+
function collectHeaders(val, acc) {
|
|
850
|
+
const idx = val.indexOf(':');
|
|
851
|
+
if (idx < 0) return acc;
|
|
852
|
+
const k = val.slice(0, idx).trim();
|
|
853
|
+
const v = val.slice(idx + 1).trim();
|
|
854
|
+
if (k) acc[k] = v;
|
|
855
|
+
return acc;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// --path-params name=val,name=val parser: merges into the accumulator so the
|
|
859
|
+
// flag can be passed multiple times.
|
|
860
|
+
function collectPathParams(val, acc) {
|
|
861
|
+
for (const pair of String(val).split(',')) {
|
|
862
|
+
const [k, ...rest] = pair.split('=');
|
|
863
|
+
if (k && k.trim()) acc[k.trim()] = rest.join('=').trim();
|
|
864
|
+
}
|
|
865
|
+
return acc;
|
|
866
|
+
}
|
|
867
|
+
|
|
692
868
|
// ─── Parent bdct command ──────────────────────────────────────────────────────
|
|
693
869
|
|
|
694
870
|
const bdct = new Command('bdct')
|
|
@@ -702,5 +878,7 @@ bdct.addCommand(listCommand);
|
|
|
702
878
|
bdct.addCommand(matrixCommand);
|
|
703
879
|
bdct.addCommand(listProvidersCommand);
|
|
704
880
|
bdct.addCommand(listConsumersCommand);
|
|
881
|
+
bdct.addCommand(captureCommand);
|
|
882
|
+
bdct.addCommand(verifyProviderCommand);
|
|
705
883
|
|
|
706
884
|
module.exports = bdct;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `specshield whoami` — print the active customer's identity and the list of
|
|
5
|
+
* organizations they can use as `--org` values. Reuses /auth/validate-api-key
|
|
6
|
+
* (for the customer summary) and /me/orgs (for the org list) — the same two
|
|
7
|
+
* endpoints the init wizard hits.
|
|
8
|
+
*
|
|
9
|
+
* Why it exists: the dashboard now surfaces orgKey, but terminal-native users
|
|
10
|
+
* and CI engineers shouldn't have to open a browser to discover what their
|
|
11
|
+
* org_key is. This command makes it a one-line lookup.
|
|
12
|
+
*
|
|
13
|
+
* Resolves the API token the same way every other command does:
|
|
14
|
+
* --api-token flag > $SPECSHIELD_API_KEY > stored ~/.specshield/config.json
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const { Command } = require('commander');
|
|
18
|
+
const chalk = require('chalk');
|
|
19
|
+
const axios = require('axios');
|
|
20
|
+
const logger = require('../utils/logger');
|
|
21
|
+
const { getStoredApiKey } = require('../config/localConfig');
|
|
22
|
+
|
|
23
|
+
const DEFAULT_SERVER = 'https://specshield.io';
|
|
24
|
+
|
|
25
|
+
const whoami = new Command('whoami');
|
|
26
|
+
|
|
27
|
+
whoami
|
|
28
|
+
.description('Show the signed-in customer and the orgKeys you can use as --org')
|
|
29
|
+
.option('--api-token <key>', 'Override stored / env API token for this call')
|
|
30
|
+
.option('--server <url>', 'Override the SpecShield server URL', DEFAULT_SERVER)
|
|
31
|
+
.option('--json', 'Output machine-readable JSON instead of a table')
|
|
32
|
+
.action(async (opts) => {
|
|
33
|
+
const token = opts.apiToken
|
|
34
|
+
|| process.env.SPECSHIELD_API_KEY
|
|
35
|
+
|| (await getStoredApiKey());
|
|
36
|
+
if (!token) {
|
|
37
|
+
logger.error('Not logged in. Run: specshield login --api-key <KEY>');
|
|
38
|
+
process.exit(2);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const server = (opts.server || DEFAULT_SERVER).replace(/\/$/, '');
|
|
42
|
+
const headers = { 'X-Api-Key': token, 'X-SpecShield-Client': 'cli' };
|
|
43
|
+
|
|
44
|
+
let me, orgs;
|
|
45
|
+
try {
|
|
46
|
+
const meRes = await axios.post(`${server}/auth/validate-api-key`, {}, { headers, timeout: 8000 });
|
|
47
|
+
if (!meRes.data || !meRes.data.valid) {
|
|
48
|
+
logger.error('API key did not validate against ' + server);
|
|
49
|
+
process.exit(2);
|
|
50
|
+
}
|
|
51
|
+
me = meRes.data;
|
|
52
|
+
} catch (err) {
|
|
53
|
+
logger.error(err.response
|
|
54
|
+
? `Failed to validate token: ${err.response.status} ${JSON.stringify(err.response.data)}`
|
|
55
|
+
: `Could not reach ${server}: ${err.message}`);
|
|
56
|
+
process.exit(2);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
const orgsRes = await axios.get(`${server}/me/orgs`, { headers, timeout: 8000 });
|
|
61
|
+
orgs = Array.isArray(orgsRes.data) ? orgsRes.data : (orgsRes.data?.orgs || []);
|
|
62
|
+
} catch (err) {
|
|
63
|
+
// Org fetch is best-effort; the customer info already printed below
|
|
64
|
+
// is the more important part.
|
|
65
|
+
orgs = [];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (opts.json) {
|
|
69
|
+
process.stdout.write(JSON.stringify({
|
|
70
|
+
customer: { name: me.name, email: me.email, plan: me.plan, customerId: me.customerId },
|
|
71
|
+
server,
|
|
72
|
+
orgs: orgs.map(o => ({ orgKey: o.orgKey, name: o.name, role: o.myRole || o.role || null })),
|
|
73
|
+
}, null, 2) + '\n');
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Human-readable output. Two sections — identity, then orgs table.
|
|
78
|
+
process.stdout.write('\n');
|
|
79
|
+
process.stdout.write(` ${chalk.bold('Logged in as:')} ${me.name || '(no name)'} `);
|
|
80
|
+
if (me.email) process.stdout.write(chalk.gray(`(${me.email})`));
|
|
81
|
+
process.stdout.write(` ${chalk.gray('· plan:')} ${chalk.cyan(me.plan || 'FREE')}\n`);
|
|
82
|
+
process.stdout.write(` ${chalk.gray('Server:')} ${server}\n`);
|
|
83
|
+
process.stdout.write('\n');
|
|
84
|
+
|
|
85
|
+
if (orgs.length === 0) {
|
|
86
|
+
process.stdout.write(chalk.yellow(' You are not a member of any organization yet.\n'));
|
|
87
|
+
process.stdout.write(chalk.gray(` Create one at ${server}/account/team to get an org_key.\n\n`));
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
process.stdout.write(` ${chalk.bold('Organizations you can use as --org:')}\n`);
|
|
92
|
+
process.stdout.write(chalk.gray(' ─────────────────────────────────────────────────────\n'));
|
|
93
|
+
const widestKey = Math.max(...orgs.map(o => (o.orgKey || '').length), 8);
|
|
94
|
+
for (const o of orgs) {
|
|
95
|
+
const key = (o.orgKey || '').padEnd(widestKey);
|
|
96
|
+
const role = o.myRole || o.role || '';
|
|
97
|
+
process.stdout.write(
|
|
98
|
+
` ${chalk.cyan(key)} ${o.name || ''}` +
|
|
99
|
+
(role ? ` ${chalk.gray('(' + role + ')')}` : '') + '\n');
|
|
100
|
+
}
|
|
101
|
+
process.stdout.write('\n');
|
|
102
|
+
process.stdout.write(chalk.gray(` Tip: paste an org_key into --org on CLI commands or bdct.org in .specshield.yml\n\n`));
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
module.exports = whoami;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* One-call orchestrator for `specshield bdct verify-provider` — the
|
|
5
|
+
* "spec-vs-production conformance" check (Fix 3 of the BDCT fidelity
|
|
6
|
+
* roadmap).
|
|
7
|
+
*
|
|
8
|
+
* Loads + dereferences an OpenAPI spec, derives a probe list (safe methods
|
|
9
|
+
* only by default), fires the probes at the running provider, validates
|
|
10
|
+
* each response body against the spec's schema for that status, and
|
|
11
|
+
* returns a structured result + summary.
|
|
12
|
+
*
|
|
13
|
+
* Defaults are deliberately conservative — this tool is pointed at REAL
|
|
14
|
+
* customer services (typically staging, sometimes prod), so:
|
|
15
|
+
*
|
|
16
|
+
* - Only GET / HEAD / OPTIONS unless `includeMutating: true`.
|
|
17
|
+
* - Probes whose path params can't be resolved are SKIPPED, not guessed.
|
|
18
|
+
* - Network errors are reported as ERROR results — never thrown — so a
|
|
19
|
+
* single flaky endpoint doesn't kill the whole run.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const axios = require('axios');
|
|
23
|
+
const SwaggerParser = require('@apidevtools/swagger-parser');
|
|
24
|
+
const { buildProbes } = require('./probeBuilder');
|
|
25
|
+
const { runProbes } = require('./runner');
|
|
26
|
+
|
|
27
|
+
async function verifyProvider(opts) {
|
|
28
|
+
const spec = await SwaggerParser.dereference(opts.spec);
|
|
29
|
+
const probes = buildProbes(spec, { includeMutating: !!opts.includeMutating });
|
|
30
|
+
const http = opts.http || defaultHttpAdapter;
|
|
31
|
+
return runProbes(spec, probes, {
|
|
32
|
+
baseUrl: opts.baseUrl,
|
|
33
|
+
pathParams: opts.pathParams,
|
|
34
|
+
headers: opts.headers,
|
|
35
|
+
timeoutMs: opts.timeoutMs,
|
|
36
|
+
http,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Default HTTP adapter (axios). Returns { status, body } and rejects only
|
|
41
|
+
* on connection-level failures — HTTP error statuses come back as data. */
|
|
42
|
+
async function defaultHttpAdapter(method, url, { headers, timeoutMs }) {
|
|
43
|
+
const res = await axios.request({
|
|
44
|
+
method, url, headers, timeout: timeoutMs,
|
|
45
|
+
validateStatus: () => true, // never throw on 4xx/5xx; the validator decides
|
|
46
|
+
responseType: 'json',
|
|
47
|
+
transitional: { silentJSONParsing: true, forcedJSONParsing: true },
|
|
48
|
+
});
|
|
49
|
+
return { status: res.status, body: res.data };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
module.exports = { verifyProvider, defaultHttpAdapter };
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Resolve OpenAPI path-template parameters into concrete URL paths.
|
|
5
|
+
* Sources, in priority order:
|
|
6
|
+
* 1. caller-supplied overrides (e.g. CLI `--path-params paymentId=pay-123`)
|
|
7
|
+
* 2. the operation's `parameters[].example` for each path-param
|
|
8
|
+
* 3. the path-item-level `parameters[].example`
|
|
9
|
+
* 4. the parameter schema's `example`
|
|
10
|
+
*
|
|
11
|
+
* If a required path param can't be resolved, the probe is skipped (with a
|
|
12
|
+
* `missing` list so the runner can report it).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param template '/users/{userId}/orders/{orderId}'
|
|
17
|
+
* @param resolvedMap { userId: 'u-1', orderId: 'o-7' } (already-resolved)
|
|
18
|
+
* @returns { resolved: string, missing: string[] }
|
|
19
|
+
*/
|
|
20
|
+
function substitute(template, resolvedMap) {
|
|
21
|
+
const missing = [];
|
|
22
|
+
const resolved = template.replace(/\{([^}]+)\}/g, (_full, name) => {
|
|
23
|
+
const v = resolvedMap && Object.prototype.hasOwnProperty.call(resolvedMap, name)
|
|
24
|
+
? resolvedMap[name]
|
|
25
|
+
: undefined;
|
|
26
|
+
if (v === undefined || v === null || v === '') { missing.push(name); return `{${name}}`; }
|
|
27
|
+
return encodeURIComponent(String(v));
|
|
28
|
+
});
|
|
29
|
+
return { resolved, missing };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Walk the spec to gather examples for path params. Returns a map per-route:
|
|
34
|
+
* { '/users/{userId}': { GET: { userId: 'u-1' }, … }, … }
|
|
35
|
+
*
|
|
36
|
+
* Operation-level params override path-item-level params (standard OAS rule).
|
|
37
|
+
*/
|
|
38
|
+
function collectSpecExamples(spec) {
|
|
39
|
+
const out = {};
|
|
40
|
+
const paths = (spec && spec.paths) || {};
|
|
41
|
+
const METHODS = ['get','put','post','delete','options','head','patch','trace'];
|
|
42
|
+
|
|
43
|
+
for (const [routePath, item] of Object.entries(paths)) {
|
|
44
|
+
if (!item || typeof item !== 'object') continue;
|
|
45
|
+
out[routePath] = {};
|
|
46
|
+
|
|
47
|
+
const pathLevelParams = Array.isArray(item.parameters) ? item.parameters : [];
|
|
48
|
+
for (const method of METHODS) {
|
|
49
|
+
const op = item[method];
|
|
50
|
+
if (!op || typeof op !== 'object') continue;
|
|
51
|
+
const opParams = Array.isArray(op.parameters) ? op.parameters : [];
|
|
52
|
+
|
|
53
|
+
const merged = {};
|
|
54
|
+
for (const p of pathLevelParams) addExample(merged, p);
|
|
55
|
+
for (const p of opParams) addExample(merged, p); // op overrides
|
|
56
|
+
out[routePath][method.toUpperCase()] = merged;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function addExample(target, param) {
|
|
63
|
+
if (!param || param.in !== 'path' || !param.name) return;
|
|
64
|
+
const ex = param.example
|
|
65
|
+
?? (param.examples && firstExampleValue(param.examples))
|
|
66
|
+
?? (param.schema && param.schema.example);
|
|
67
|
+
if (ex !== undefined) target[param.name] = ex;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function firstExampleValue(examples) {
|
|
71
|
+
for (const v of Object.values(examples || {})) {
|
|
72
|
+
if (v && v.value !== undefined) return v.value;
|
|
73
|
+
}
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Resolve a single probe's path. CLI overrides win over spec examples.
|
|
79
|
+
*
|
|
80
|
+
* @param routePath '/users/{userId}'
|
|
81
|
+
* @param method 'GET'
|
|
82
|
+
* @param specExamples output of collectSpecExamples(spec)
|
|
83
|
+
* @param cliOverrides { userId: 'u-7', ... } (global)
|
|
84
|
+
*/
|
|
85
|
+
function resolveProbePath(routePath, method, specExamples, cliOverrides) {
|
|
86
|
+
const fromSpec = (specExamples[routePath] && specExamples[routePath][method.toUpperCase()]) || {};
|
|
87
|
+
const merged = { ...fromSpec, ...(cliOverrides || {}) };
|
|
88
|
+
return substitute(routePath, merged);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Parse a CLI string `paymentId=pay-123,userId=u-7` into a map.
|
|
93
|
+
* Multiple `--path-params` flags can be joined by the caller before parsing.
|
|
94
|
+
*/
|
|
95
|
+
function parsePathParamsArg(arg) {
|
|
96
|
+
if (!arg) return {};
|
|
97
|
+
const map = {};
|
|
98
|
+
for (const pair of String(arg).split(',')) {
|
|
99
|
+
const [k, ...rest] = pair.split('=');
|
|
100
|
+
if (!k) continue;
|
|
101
|
+
map[k.trim()] = rest.join('=').trim();
|
|
102
|
+
}
|
|
103
|
+
return map;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
module.exports = {
|
|
107
|
+
substitute, collectSpecExamples, resolveProbePath, parsePathParamsArg,
|
|
108
|
+
};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Build a flat list of conformance probes from a dereferenced OAS document.
|
|
5
|
+
*
|
|
6
|
+
* Probe = {
|
|
7
|
+
* routePath: '/users/{userId}',
|
|
8
|
+
* method: 'GET',
|
|
9
|
+
* operationId: string | undefined,
|
|
10
|
+
* expectedResponses: { '200': schema, '404': schema, default?: schema },
|
|
11
|
+
* responseHeadersForStatus: { '200': { 'X-RateLimit-Remaining': { schema } } },
|
|
12
|
+
* }
|
|
13
|
+
*
|
|
14
|
+
* Safety: by default we only probe **safe** methods (GET, HEAD, OPTIONS).
|
|
15
|
+
* Mutating verbs are opt-in via `includeMutating: true` so we never
|
|
16
|
+
* accidentally side-effect a customer's staging data.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const SAFE_METHODS = new Set(['get', 'head', 'options']);
|
|
20
|
+
const ALL_METHODS = ['get','put','post','delete','options','head','patch','trace'];
|
|
21
|
+
const JSON_MIME = /\bjson\b/i;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param spec dereferenced OAS document
|
|
25
|
+
* @param opts.includeMutating default false
|
|
26
|
+
* @returns Probe[]
|
|
27
|
+
*/
|
|
28
|
+
function buildProbes(spec, opts = {}) {
|
|
29
|
+
const includeMutating = opts.includeMutating === true;
|
|
30
|
+
const allowed = includeMutating ? new Set(ALL_METHODS) : SAFE_METHODS;
|
|
31
|
+
const out = [];
|
|
32
|
+
|
|
33
|
+
const paths = (spec && spec.paths) || {};
|
|
34
|
+
for (const [routePath, item] of Object.entries(paths)) {
|
|
35
|
+
if (!item || typeof item !== 'object') continue;
|
|
36
|
+
for (const method of ALL_METHODS) {
|
|
37
|
+
const op = item[method];
|
|
38
|
+
if (!op || typeof op !== 'object') continue;
|
|
39
|
+
if (!allowed.has(method)) continue;
|
|
40
|
+
|
|
41
|
+
out.push({
|
|
42
|
+
routePath,
|
|
43
|
+
method: method.toUpperCase(),
|
|
44
|
+
operationId: op.operationId,
|
|
45
|
+
expectedResponses: extractResponses(op.responses || {}),
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* { '200': { content: { 'application/json': { schema } } }, '4XX': … }
|
|
54
|
+
* →
|
|
55
|
+
* { '200': schema | null, '4XX': schema | null, default?: schema | null }
|
|
56
|
+
*
|
|
57
|
+
* Pulls the JSON-content schema only (other content types deferred).
|
|
58
|
+
*/
|
|
59
|
+
function extractResponses(responses) {
|
|
60
|
+
const out = {};
|
|
61
|
+
for (const [code, body] of Object.entries(responses)) {
|
|
62
|
+
if (!body) continue;
|
|
63
|
+
const content = body.content || {};
|
|
64
|
+
let schema = null;
|
|
65
|
+
for (const [mime, c] of Object.entries(content)) {
|
|
66
|
+
if (JSON_MIME.test(mime) && c && c.schema) { schema = c.schema; break; }
|
|
67
|
+
}
|
|
68
|
+
out[code] = schema; // null = "documented status, no JSON schema"
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Match an actual response status (e.g. 200) against the spec's response keys
|
|
75
|
+
* (which can be exact `"200"`, wildcard `"2XX"`, or `"default"`).
|
|
76
|
+
* Returns the matching schema (possibly null) or undefined if nothing matches.
|
|
77
|
+
*/
|
|
78
|
+
function pickResponseSchema(probe, actualStatus) {
|
|
79
|
+
const r = probe.expectedResponses;
|
|
80
|
+
const code = String(actualStatus);
|
|
81
|
+
if (Object.prototype.hasOwnProperty.call(r, code)) return r[code];
|
|
82
|
+
const wildcard = code[0] + 'XX';
|
|
83
|
+
if (Object.prototype.hasOwnProperty.call(r, wildcard)) return r[wildcard];
|
|
84
|
+
if (Object.prototype.hasOwnProperty.call(r, wildcard.toLowerCase())) return r[wildcard.toLowerCase()];
|
|
85
|
+
if (Object.prototype.hasOwnProperty.call(r, 'default')) return r['default'];
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
module.exports = {
|
|
90
|
+
buildProbes, extractResponses, pickResponseSchema,
|
|
91
|
+
SAFE_METHODS, ALL_METHODS,
|
|
92
|
+
};
|