@testsprite/testsprite-cli 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -30
- package/dist/commands/agent.js +44 -42
- package/dist/commands/doctor.d.ts +1 -1
- package/dist/commands/doctor.js +4 -7
- package/dist/commands/project.js +3 -2
- package/dist/commands/schedule.d.ts +120 -0
- package/dist/commands/schedule.js +487 -0
- package/dist/commands/test.d.ts +55 -1
- package/dist/commands/test.js +714 -183
- package/dist/commands/testlist.d.ts +88 -0
- package/dist/commands/testlist.js +747 -0
- package/dist/index.js +6 -2
- package/dist/lib/agent-targets.d.ts +13 -4
- package/dist/lib/agent-targets.js +11 -2
- package/dist/lib/conflict-reason.d.ts +30 -0
- package/dist/lib/conflict-reason.js +45 -0
- package/dist/lib/credentials.js +42 -1
- package/dist/lib/cron.d.ts +40 -0
- package/dist/lib/cron.js +190 -0
- package/dist/lib/dry-run/samples.js +177 -55
- package/dist/lib/errors.d.ts +9 -0
- package/dist/lib/errors.js +11 -0
- package/dist/lib/gh-output.d.ts +51 -4
- package/dist/lib/gh-output.js +149 -19
- package/dist/lib/http.d.ts +25 -0
- package/dist/lib/http.js +201 -3
- package/dist/lib/junit-report.d.ts +20 -2
- package/dist/lib/junit-report.js +38 -5
- package/dist/lib/poll.js +72 -36
- package/dist/lib/proxy.d.ts +16 -0
- package/dist/lib/proxy.js +19 -1
- package/dist/lib/response-schemas.d.ts +7 -0
- package/dist/lib/response-schemas.js +46 -14
- package/dist/lib/runs.types.d.ts +8 -3
- package/dist/lib/secret-file.d.ts +15 -0
- package/dist/lib/secret-file.js +82 -0
- package/dist/lib/target-url-preflight.d.ts +91 -0
- package/dist/lib/target-url-preflight.js +259 -0
- package/dist/lib/target-url.d.ts +22 -5
- package/dist/lib/target-url.js +60 -28
- package/dist/lib/testlist.types.d.ts +77 -0
- package/dist/lib/testlist.types.js +9 -0
- package/dist/lib/v3-advisory.d.ts +37 -4
- package/dist/lib/v3-advisory.js +47 -4
- package/dist/lib/wait-exit.d.ts +29 -0
- package/dist/lib/wait-exit.js +103 -0
- package/dist/version-guard.d.ts +10 -7
- package/dist/version-guard.js +37 -9
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -1
|
@@ -92,24 +92,34 @@ export const RUN_RESPONSE_SCHEMA = v.looseObject({
|
|
|
92
92
|
videoUrl: v.nullish(v.string(), null),
|
|
93
93
|
stepSummary: RUN_STEP_SUMMARY_SCHEMA,
|
|
94
94
|
retryAfterSeconds: v.optional(v.number()),
|
|
95
|
-
// Portal link.
|
|
96
|
-
//
|
|
97
|
-
//
|
|
98
|
-
//
|
|
99
|
-
//
|
|
100
|
-
//
|
|
101
|
-
// `
|
|
95
|
+
// Portal link. Three-state wire contract (pinned): **absent** — an older
|
|
96
|
+
// backend that predates this field, and cannot have produced a V3-native/
|
|
97
|
+
// unmirrored entity either (that capability and this field ship together)
|
|
98
|
+
// — the CLI computes its own legacy V2-shaped link. **Present + string** —
|
|
99
|
+
// the backend built a correct link (it alone knows which store answered
|
|
100
|
+
// and this environment's portal origin) — use it verbatim. **Present +
|
|
101
|
+
// `null`** — the backend deliberately has no correct link to offer (e.g. a
|
|
102
|
+
// V3-native entity with no DynamoDB mirror row for the client's V2-shaped
|
|
103
|
+
// guess to land on) — suppress the link entirely; a client-side guess here
|
|
104
|
+
// would be exactly the dead link the server declined to emit. The backend
|
|
105
|
+
// always includes the key going forward (typed `string | null`, never
|
|
106
|
+
// omitted when it has an opinion) — an earlier revision of this comment
|
|
107
|
+
// described the backend as omitting the key on "no correct link", which
|
|
108
|
+
// was the actual production defect this contract closes: the client's
|
|
109
|
+
// absent-branch fallback was firing on real V3-native no-link responses
|
|
110
|
+
// and printing the dead legacy URL this whole feature exists to remove.
|
|
102
111
|
//
|
|
103
112
|
// The `undefined` default (NOT `null`, unlike every field above) is load-bearing
|
|
104
113
|
// and measured: valibot applies a default only when the key is absent, and
|
|
105
114
|
// skips the assignment entirely when that default is `undefined` — so an
|
|
106
115
|
// omitted field stays an ABSENT key, which is exactly what
|
|
107
|
-
// `withRunDashboardUrl`'s `'dashboardUrl' in run` test
|
|
108
|
-
//
|
|
109
|
-
// `nullish(..., null)` fields above
|
|
110
|
-
//
|
|
111
|
-
// null here (nullable passes it
|
|
112
|
-
// consumer, not in the schema.
|
|
116
|
+
// `withRunDashboardUrl`'s `'dashboardUrl' in run` test (via the shared
|
|
117
|
+
// `resolveDashboardUrl` helper) reads to decide "old backend, compute the
|
|
118
|
+
// link myself". Aligning this with the `nullish(..., null)` fields above
|
|
119
|
+
// would materialize the key on every response and silently kill that
|
|
120
|
+
// fallback. A wire `null` is preserved as null here (nullable passes it
|
|
121
|
+
// through untouched) and normalized at the consumer, not in the schema.
|
|
122
|
+
// Locked by tests in response-schemas.test.ts.
|
|
113
123
|
dashboardUrl: v.nullish(v.string(), undefined),
|
|
114
124
|
// Absence means "steps not requested" and drives command branching, so no
|
|
115
125
|
// default is applied (rule 3, optional branch).
|
|
@@ -210,11 +220,33 @@ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
|
|
|
210
220
|
enqueuedAt: v.string(),
|
|
211
221
|
dashboardUrl: v.optional(v.string()),
|
|
212
222
|
})),
|
|
213
|
-
conflicts: v.array(v.looseObject({
|
|
223
|
+
conflicts: v.array(v.looseObject({
|
|
224
|
+
testId: v.string(),
|
|
225
|
+
currentRunId: v.optional(v.string()),
|
|
226
|
+
reason: v.optional(v.string()),
|
|
227
|
+
message: v.optional(v.string()),
|
|
228
|
+
})),
|
|
214
229
|
deferred: v.array(v.looseObject({ testId: v.string() })),
|
|
215
230
|
skippedFrontend: v.array(v.string()),
|
|
216
231
|
skippedIntegration: v.array(v.looseObject({ testId: v.string() })),
|
|
217
232
|
});
|
|
233
|
+
/**
|
|
234
|
+
* `POST /api/cli/v1/testlist/{listId}/run`. Mirrors the batch-run-fresh shape so
|
|
235
|
+
* the `--wait` fan-out reuses the same poll tail; `conflicts[]` additionally
|
|
236
|
+
* carry the in-flight `currentRunId`, and `reason` marks a nothing-dispatched run.
|
|
237
|
+
*/
|
|
238
|
+
export const TESTLIST_RUN_RESPONSE_SCHEMA = v.looseObject({
|
|
239
|
+
accepted: v.array(v.looseObject({ testId: v.string(), runId: v.string(), enqueuedAt: v.string() })),
|
|
240
|
+
conflicts: v.array(v.looseObject({
|
|
241
|
+
testId: v.string(),
|
|
242
|
+
currentRunId: v.optional(v.string()),
|
|
243
|
+
reason: v.optional(v.string()),
|
|
244
|
+
message: v.optional(v.string()),
|
|
245
|
+
})),
|
|
246
|
+
deferred: v.array(v.looseObject({ testId: v.string() })),
|
|
247
|
+
notFound: v.optional(v.array(v.string())),
|
|
248
|
+
reason: v.optional(v.string()),
|
|
249
|
+
});
|
|
218
250
|
// ---------------------------------------------------------------------------
|
|
219
251
|
// GET /tests/{testId}/runs
|
|
220
252
|
// ---------------------------------------------------------------------------
|
package/dist/lib/runs.types.d.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* Extended by M3.4 piece-5 — `test result --history` command.
|
|
5
5
|
|
|
6
6
|
*/
|
|
7
|
+
import type { RunConflict } from './conflict-reason.js';
|
|
7
8
|
/** Literal body sent to `POST /api/cli/v1/tests/{testId}/runs`. */
|
|
8
9
|
export interface TriggerRunBody {
|
|
9
10
|
/** Fixed source literal for CLI-triggered runs. */
|
|
@@ -385,9 +386,13 @@ export interface BatchRunFreshAccepted {
|
|
|
385
386
|
*/
|
|
386
387
|
export interface BatchRunFreshResponse {
|
|
387
388
|
accepted: BatchRunFreshAccepted[];
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
389
|
+
/**
|
|
390
|
+
* A run-slot conflict. `currentRunId`, when present, is the id of the run
|
|
391
|
+
* ALREADY in flight for this test — under `--wait` the CLI polls it to a
|
|
392
|
+
* verdict (auto-resume) instead of failing the batch. Absent ⇒ a hard
|
|
393
|
+
* conflict with no resolvable in-flight run (still fails the batch).
|
|
394
|
+
*/
|
|
395
|
+
conflicts: RunConflict[];
|
|
391
396
|
deferred: Array<{
|
|
392
397
|
testId: string;
|
|
393
398
|
}>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read a secret from `path`, surfacing every filesystem failure as a typed
|
|
3
|
+
* `VALIDATION_ERROR` (exit 5) attributed to `flag`.
|
|
4
|
+
*
|
|
5
|
+
* The returned value is trimmed, matching what the unguarded call sites did.
|
|
6
|
+
* Trimming also drops a leading UTF-8 BOM: `U+FEFF` is ECMAScript whitespace,
|
|
7
|
+
* so a file written by PowerShell 5.1's default `Set-Content -Encoding utf8`
|
|
8
|
+
* no longer smuggles an invisible character into the secret.
|
|
9
|
+
*
|
|
10
|
+
* @param flag - Flag name without the leading dashes, e.g. `'password-file'`.
|
|
11
|
+
* @param path - Path as supplied by the user; may be relative.
|
|
12
|
+
* @throws {ApiError} `VALIDATION_ERROR` when the path is missing, unreadable,
|
|
13
|
+
* or not a regular file.
|
|
14
|
+
*/
|
|
15
|
+
export declare function readSecretFileGuarded(flag: string, path: string): string;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guarded reader for the `--*-file` secret flags.
|
|
3
|
+
*
|
|
4
|
+
* Every one of these flags exists so a secret stays out of shell history, and
|
|
5
|
+
* every one of them is a path the user types by hand — so a typo is the
|
|
6
|
+
* expected failure, not an exceptional one. A bare
|
|
7
|
+
* `readFileSync(path, 'utf8').trim()` turns that typo into an unhandled Node
|
|
8
|
+
* exception: exit `1` instead of `5`, an `--output json` payload whose `error`
|
|
9
|
+
* is a bare string rather than the `{ code, message, nextAction }` envelope the
|
|
10
|
+
* rest of the CLI emits, and the absolute path plus errno leaked to stderr.
|
|
11
|
+
*
|
|
12
|
+
* This maps those failures onto the same typed `VALIDATION_ERROR` envelope the
|
|
13
|
+
* already-guarded file flags produce, mirroring `readCodeFileGuarded` in
|
|
14
|
+
* `src/commands/test.ts`. The payload cap is deliberately not carried over:
|
|
15
|
+
* secrets are small, and a size ceiling would be a behaviour change on a
|
|
16
|
+
* shipped flag rather than part of fixing the crash.
|
|
17
|
+
*
|
|
18
|
+
* Callers pass the flag name so the envelope names the flag the user actually
|
|
19
|
+
* typed — one helper serves `--password-file` today and the remaining
|
|
20
|
+
* credential/auto-auth file flags once they are migrated.
|
|
21
|
+
*/
|
|
22
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
23
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
24
|
+
import { localValidationError } from './errors.js';
|
|
25
|
+
/**
|
|
26
|
+
* Read a secret from `path`, surfacing every filesystem failure as a typed
|
|
27
|
+
* `VALIDATION_ERROR` (exit 5) attributed to `flag`.
|
|
28
|
+
*
|
|
29
|
+
* The returned value is trimmed, matching what the unguarded call sites did.
|
|
30
|
+
* Trimming also drops a leading UTF-8 BOM: `U+FEFF` is ECMAScript whitespace,
|
|
31
|
+
* so a file written by PowerShell 5.1's default `Set-Content -Encoding utf8`
|
|
32
|
+
* no longer smuggles an invisible character into the secret.
|
|
33
|
+
*
|
|
34
|
+
* @param flag - Flag name without the leading dashes, e.g. `'password-file'`.
|
|
35
|
+
* @param path - Path as supplied by the user; may be relative.
|
|
36
|
+
* @throws {ApiError} `VALIDATION_ERROR` when the path is missing, unreadable,
|
|
37
|
+
* or not a regular file.
|
|
38
|
+
*/
|
|
39
|
+
export function readSecretFileGuarded(flag, path) {
|
|
40
|
+
const absolute = isAbsolute(path) ? path : resolve(process.cwd(), path);
|
|
41
|
+
let stat;
|
|
42
|
+
try {
|
|
43
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- this is the guard itself: `absolute` is the user-supplied `--*-file` path after isAbsolute()/resolve() normalization, and this statSync().isFile() check (below) plus the try/catch mapping every errno to a typed VALIDATION_ERROR is exactly the mitigation for a non-literal fs path here.
|
|
44
|
+
stat = statSync(absolute);
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
throw secretFileError(flag, path, err, 'stat');
|
|
48
|
+
}
|
|
49
|
+
// A directory would otherwise reach readFileSync and throw EISDIR on Linux
|
|
50
|
+
// while resolving to an empty read on some platforms — reject it up front so
|
|
51
|
+
// the contract is the same everywhere.
|
|
52
|
+
if (!stat.isFile()) {
|
|
53
|
+
throw localValidationError(flag, `not a regular file: ${path}`);
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
// eslint-disable-next-line security/detect-non-literal-fs-filename -- same guarded path as the statSync() above: `absolute` already passed the isFile() regular-file check, so this read is the guard's intended purpose (reading a user-supplied secret path), not an unvalidated pass-through.
|
|
57
|
+
return readFileSync(absolute, 'utf8').trim();
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
throw secretFileError(flag, path, err, 'read');
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Translate a Node filesystem error into the CLI's validation envelope,
|
|
65
|
+
* reporting the path the user typed rather than the resolved absolute path so
|
|
66
|
+
* no directory layout leaks into output.
|
|
67
|
+
*/
|
|
68
|
+
function secretFileError(flag, path, err, verb) {
|
|
69
|
+
const code = err.code;
|
|
70
|
+
if (code === 'ENOENT') {
|
|
71
|
+
return localValidationError(flag, `file does not exist: ${path}`);
|
|
72
|
+
}
|
|
73
|
+
if (code === 'EACCES' || code === 'EPERM') {
|
|
74
|
+
return localValidationError(flag, `permission denied reading ${path}`);
|
|
75
|
+
}
|
|
76
|
+
if (code === 'EISDIR') {
|
|
77
|
+
return localValidationError(flag, `not a regular file: ${path}`);
|
|
78
|
+
}
|
|
79
|
+
const reason = err instanceof Error ? err.message : 'unknown error';
|
|
80
|
+
return localValidationError(flag, `cannot ${verb} ${path}: ${reason}`);
|
|
81
|
+
}
|
|
82
|
+
//# sourceMappingURL=secret-file.js.map
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-charge reachability preflight for a caller-supplied `--target-url`.
|
|
3
|
+
*
|
|
4
|
+
* A blocked-run analysis measured 1,003 blocked-with-URL CLI runs: 26%
|
|
5
|
+
* pointed at a third-party tunnel host (`*.trycloudflare.com`, `*.loca.lt`,
|
|
6
|
+
* ngrok), 55.5% of those were blocked, and every one of them was charged
|
|
7
|
+
* anyway — the run row and its credit spend happen before the Lambda ever
|
|
8
|
+
* discovers the target is dead. This probe runs BEFORE the trigger POST so
|
|
9
|
+
* an obviously-doomed run never gets a run row or a charge.
|
|
10
|
+
*
|
|
11
|
+
* **Honest limitation** (this must also be stated in `--help` and the PR
|
|
12
|
+
* body): the probe below runs from wherever this CLI process runs — the
|
|
13
|
+
* caller's laptop, a CI runner — while the actual test executes from a
|
|
14
|
+
* Lambda inside AWS. Reachability from one is not proof of reachability
|
|
15
|
+
* from the other. That asymmetry is why the refusal set is deliberately
|
|
16
|
+
* narrow (only the failure classes that analysis actually measured — a
|
|
17
|
+
* broader rule would not have prevented a single one of those 1,003 runs), why
|
|
18
|
+
* every ambiguous signal downgrades to a warning instead of a hard block,
|
|
19
|
+
* and why `--skip-preflight` exists as a full opt-out (zero network calls).
|
|
20
|
+
*
|
|
21
|
+
* Two injectable seams, mirroring the MCP plugin's `checkPortListening`
|
|
22
|
+
* shape (a cheap first check, then an HTTP-level fallback for the signal
|
|
23
|
+
* the first check can't see) rather than inventing a new one:
|
|
24
|
+
* - `dnsLookup` — a raw DNS resolution. Deliberately separate from the
|
|
25
|
+
* HTTP probe below: `proxy.ts` installs a proxy dispatcher that only
|
|
26
|
+
* `fetch()` honours, never a raw socket/DNS call, so behind a
|
|
27
|
+
* configured HTTP(S) proxy this step can fail locally (the real
|
|
28
|
+
* resolution happens at the proxy) even though the target is reachable
|
|
29
|
+
* — hence the proxy carve-out downgrades a negative *failure* result
|
|
30
|
+
* here. A resolved address landing in the private/loopback/link-local/
|
|
31
|
+
* metadata range is a different kind of signal (DNS rebinding, not
|
|
32
|
+
* ambiguity about where resolution happens) and always refuses — see
|
|
33
|
+
* the resolved-address check below.
|
|
34
|
+
* - `fetchImpl` — the actual HTTP probe (proxy-aware once a proxy
|
|
35
|
+
* dispatcher is installed), used for the 502/503/504 gateway-error
|
|
36
|
+
* signal a DNS/TCP-level check cannot see at all. Runs with
|
|
37
|
+
* `redirect: 'manual'`: a 3xx is treated as a live/reachable signal
|
|
38
|
+
* (a real app 302ing to a login page is healthy) but is never
|
|
39
|
+
* followed — the redirect target is unvalidated by everything above
|
|
40
|
+
* (`assertNotLocal` only ever inspected the literal `--target-url`
|
|
41
|
+
* string; the resolved-address check only covers *this* URL's host),
|
|
42
|
+
* so following it would hand an attacker-controlled Location header a
|
|
43
|
+
* live SSRF primitive running on the caller's machine or CI runner.
|
|
44
|
+
*/
|
|
45
|
+
export interface TargetUrlPreflightDeps {
|
|
46
|
+
/** DNS resolution hook. Defaults to `dns.promises.lookup`. Injectable for tests. */
|
|
47
|
+
dnsLookup?: (hostname: string) => Promise<unknown>;
|
|
48
|
+
/** HTTP probe hook. Defaults to the global `fetch`. Injectable for tests. */
|
|
49
|
+
fetchImpl?: typeof fetch;
|
|
50
|
+
/**
|
|
51
|
+
* Whether a proxy dispatcher is actually installed for this process.
|
|
52
|
+
* Defaults to `isProxyAgentActive()` (proxy.ts), which inspects the
|
|
53
|
+
* active global undici dispatcher — deliberately NOT an env-var check:
|
|
54
|
+
* an `HTTP(S)_PROXY` variable can be present in the environment (e.g. a
|
|
55
|
+
* CI runner exporting it for unrelated package-registry egress) without
|
|
56
|
+
* this CLI ever having installed a dispatcher for it, and gating the
|
|
57
|
+
* refuse→warn downgrade on the env var alone would silently soften every
|
|
58
|
+
* refusal in exactly that environment. Injectable for tests so they don't
|
|
59
|
+
* need to mutate the real global dispatcher to exercise the proxy path.
|
|
60
|
+
*/
|
|
61
|
+
proxyActive?: boolean;
|
|
62
|
+
}
|
|
63
|
+
export type TargetUrlPreflightOutcome = {
|
|
64
|
+
verdict: 'ok';
|
|
65
|
+
} | {
|
|
66
|
+
verdict: 'warn';
|
|
67
|
+
reason: string;
|
|
68
|
+
} | {
|
|
69
|
+
verdict: 'refuse';
|
|
70
|
+
reason: string;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Probe `rawUrl` for the narrow refusal set described in the module
|
|
74
|
+
* docstring. Pure decision function — never throws for a network failure
|
|
75
|
+
* (every reachable failure classifies to `warn` or `refuse`); a malformed
|
|
76
|
+
* URL degrades to `warn` rather than crashing (callers validate the URL
|
|
77
|
+
* shape via `assertNotLocal` before this runs).
|
|
78
|
+
*/
|
|
79
|
+
export declare function probeTargetUrl(rawUrl: string, deps?: TargetUrlPreflightDeps): Promise<TargetUrlPreflightOutcome>;
|
|
80
|
+
/**
|
|
81
|
+
* Run the preflight and either throw (refuse), print an `[advisory]` line
|
|
82
|
+
* (warn), or no-op (ok / skipped). This is the call-site integration point
|
|
83
|
+
* — wired at all four `--target-url` trigger paths, after `assertNotLocal`
|
|
84
|
+
* and before the trigger POST.
|
|
85
|
+
*
|
|
86
|
+
* `skipPreflight: true` makes this a pure no-op with ZERO network calls —
|
|
87
|
+
* neither `dnsLookup` nor `fetchImpl` is invoked.
|
|
88
|
+
*/
|
|
89
|
+
export declare function assertTargetUrlReachable(targetUrl: string, opts: {
|
|
90
|
+
skipPreflight?: boolean;
|
|
91
|
+
}, deps: TargetUrlPreflightDeps, stderrFn: (line: string) => void): Promise<void>;
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pre-charge reachability preflight for a caller-supplied `--target-url`.
|
|
3
|
+
*
|
|
4
|
+
* A blocked-run analysis measured 1,003 blocked-with-URL CLI runs: 26%
|
|
5
|
+
* pointed at a third-party tunnel host (`*.trycloudflare.com`, `*.loca.lt`,
|
|
6
|
+
* ngrok), 55.5% of those were blocked, and every one of them was charged
|
|
7
|
+
* anyway — the run row and its credit spend happen before the Lambda ever
|
|
8
|
+
* discovers the target is dead. This probe runs BEFORE the trigger POST so
|
|
9
|
+
* an obviously-doomed run never gets a run row or a charge.
|
|
10
|
+
*
|
|
11
|
+
* **Honest limitation** (this must also be stated in `--help` and the PR
|
|
12
|
+
* body): the probe below runs from wherever this CLI process runs — the
|
|
13
|
+
* caller's laptop, a CI runner — while the actual test executes from a
|
|
14
|
+
* Lambda inside AWS. Reachability from one is not proof of reachability
|
|
15
|
+
* from the other. That asymmetry is why the refusal set is deliberately
|
|
16
|
+
* narrow (only the failure classes that analysis actually measured — a
|
|
17
|
+
* broader rule would not have prevented a single one of those 1,003 runs), why
|
|
18
|
+
* every ambiguous signal downgrades to a warning instead of a hard block,
|
|
19
|
+
* and why `--skip-preflight` exists as a full opt-out (zero network calls).
|
|
20
|
+
*
|
|
21
|
+
* Two injectable seams, mirroring the MCP plugin's `checkPortListening`
|
|
22
|
+
* shape (a cheap first check, then an HTTP-level fallback for the signal
|
|
23
|
+
* the first check can't see) rather than inventing a new one:
|
|
24
|
+
* - `dnsLookup` — a raw DNS resolution. Deliberately separate from the
|
|
25
|
+
* HTTP probe below: `proxy.ts` installs a proxy dispatcher that only
|
|
26
|
+
* `fetch()` honours, never a raw socket/DNS call, so behind a
|
|
27
|
+
* configured HTTP(S) proxy this step can fail locally (the real
|
|
28
|
+
* resolution happens at the proxy) even though the target is reachable
|
|
29
|
+
* — hence the proxy carve-out downgrades a negative *failure* result
|
|
30
|
+
* here. A resolved address landing in the private/loopback/link-local/
|
|
31
|
+
* metadata range is a different kind of signal (DNS rebinding, not
|
|
32
|
+
* ambiguity about where resolution happens) and always refuses — see
|
|
33
|
+
* the resolved-address check below.
|
|
34
|
+
* - `fetchImpl` — the actual HTTP probe (proxy-aware once a proxy
|
|
35
|
+
* dispatcher is installed), used for the 502/503/504 gateway-error
|
|
36
|
+
* signal a DNS/TCP-level check cannot see at all. Runs with
|
|
37
|
+
* `redirect: 'manual'`: a 3xx is treated as a live/reachable signal
|
|
38
|
+
* (a real app 302ing to a login page is healthy) but is never
|
|
39
|
+
* followed — the redirect target is unvalidated by everything above
|
|
40
|
+
* (`assertNotLocal` only ever inspected the literal `--target-url`
|
|
41
|
+
* string; the resolved-address check only covers *this* URL's host),
|
|
42
|
+
* so following it would hand an attacker-controlled Location header a
|
|
43
|
+
* live SSRF primitive running on the caller's machine or CI runner.
|
|
44
|
+
*/
|
|
45
|
+
import * as dns from 'node:dns';
|
|
46
|
+
import { isIP } from 'node:net';
|
|
47
|
+
import { ApiError } from './errors.js';
|
|
48
|
+
import { isProxyAgentActive } from './proxy.js';
|
|
49
|
+
import { disallowedIpReason } from './target-url.js';
|
|
50
|
+
/** ~8s, matching the MCP plugin's `checkPortListening` TCP-probe budget. */
|
|
51
|
+
const PREFLIGHT_TIMEOUT_MS = 8_000;
|
|
52
|
+
const GATEWAY_ERROR_STATUSES = new Set([502, 503, 504]);
|
|
53
|
+
/** Pulls the string addresses out of a `dns.lookup` result, whether it's a
|
|
54
|
+
* single `{ address, family }` object (the no-options default) or an array
|
|
55
|
+
* of them (the `{ all: true }` shape the real default below requests, so a
|
|
56
|
+
* dual-stack host's A *and* AAAA records are both checked). */
|
|
57
|
+
function resolvedAddresses(lookupResult) {
|
|
58
|
+
const records = Array.isArray(lookupResult) ? lookupResult : [lookupResult];
|
|
59
|
+
return records
|
|
60
|
+
.map(r => r?.address)
|
|
61
|
+
.filter((a) => typeof a === 'string');
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* True when `err` (or a `cause` nested inside it — including an
|
|
65
|
+
* `AggregateError`'s `.errors[]`, the shape undici throws for a dual-stack
|
|
66
|
+
* host where one address family connects and the other refuses) carries
|
|
67
|
+
* one of `codes` as its `code`.
|
|
68
|
+
*/
|
|
69
|
+
function errorHasCode(err, codes) {
|
|
70
|
+
const top = err?.code;
|
|
71
|
+
if (typeof top === 'string' && codes.includes(top))
|
|
72
|
+
return true;
|
|
73
|
+
const cause = err?.cause;
|
|
74
|
+
const causeCode = cause?.code;
|
|
75
|
+
if (typeof causeCode === 'string' && codes.includes(causeCode))
|
|
76
|
+
return true;
|
|
77
|
+
const aggErrors = cause?.errors;
|
|
78
|
+
if (Array.isArray(aggErrors)) {
|
|
79
|
+
return aggErrors.some(e => {
|
|
80
|
+
const code = e?.code;
|
|
81
|
+
return typeof code === 'string' && codes.includes(code);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
function isTimeoutError(err) {
|
|
87
|
+
const name = err?.name;
|
|
88
|
+
return name === 'AbortError' || name === 'TimeoutError';
|
|
89
|
+
}
|
|
90
|
+
/** Strips the `[...]` bracket notation the WHATWG `URL.hostname` getter uses for IPv6 literals. */
|
|
91
|
+
function bareHost(hostname) {
|
|
92
|
+
return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Probe `rawUrl` for the narrow refusal set described in the module
|
|
96
|
+
* docstring. Pure decision function — never throws for a network failure
|
|
97
|
+
* (every reachable failure classifies to `warn` or `refuse`); a malformed
|
|
98
|
+
* URL degrades to `warn` rather than crashing (callers validate the URL
|
|
99
|
+
* shape via `assertNotLocal` before this runs).
|
|
100
|
+
*/
|
|
101
|
+
export async function probeTargetUrl(rawUrl, deps = {}) {
|
|
102
|
+
const proxied = deps.proxyActive ?? isProxyAgentActive();
|
|
103
|
+
let parsed;
|
|
104
|
+
try {
|
|
105
|
+
parsed = new URL(rawUrl);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return { verdict: 'warn', reason: 'could not parse --target-url for the reachability probe' };
|
|
109
|
+
}
|
|
110
|
+
const host = bareHost(parsed.hostname);
|
|
111
|
+
// Step 1 — DNS. Skipped for a literal IP host (nothing to resolve, and
|
|
112
|
+
// dns.lookup on a literal is a needless round trip through the resolver).
|
|
113
|
+
if (isIP(host) === 0) {
|
|
114
|
+
const dnsLookup = deps.dnsLookup ?? ((hostname) => dns.promises.lookup(hostname, { all: true }));
|
|
115
|
+
let lookupResult;
|
|
116
|
+
try {
|
|
117
|
+
lookupResult = await dnsLookup(host);
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
const code = err?.code;
|
|
121
|
+
if (code === 'ENOTFOUND' || code === 'EAI_NONAME') {
|
|
122
|
+
if (proxied) {
|
|
123
|
+
return {
|
|
124
|
+
verdict: 'warn',
|
|
125
|
+
reason: `DNS lookup for "${host}" failed locally (${code}) — not conclusive behind a configured proxy`,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
verdict: 'refuse',
|
|
130
|
+
reason: `--target-url host "${host}" does not resolve (${code})`,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
// Anything else (e.g. EAI_AGAIN — a transient resolver hiccup) is
|
|
134
|
+
// ambiguous, not a confirmed dead target — warn, never refuse.
|
|
135
|
+
return {
|
|
136
|
+
verdict: 'warn',
|
|
137
|
+
reason: `DNS lookup for "${host}" failed (${typeof code === 'string' ? code : 'unknown error'})`,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
// DNS rebinding: a public-looking hostname (e.g. an attacker-controlled
|
|
141
|
+
// domain, or a tunnel host with attacker-influenced DNS) whose A/AAAA
|
|
142
|
+
// record actually points at a private, loopback, link-local, or
|
|
143
|
+
// metadata-service address. `assertNotLocal` never catches this — it
|
|
144
|
+
// only ever inspected the literal `--target-url` *string*, and this
|
|
145
|
+
// hostname passed that check honestly (it doesn't LOOK private). Unlike
|
|
146
|
+
// the DNS-failure branch above, there is no proxy carve-out: resolving
|
|
147
|
+
// locally to a private address is a security signal, not an ambiguous
|
|
148
|
+
// "can't tell from here" result, and a false positive has a documented
|
|
149
|
+
// escape hatch (`--skip-preflight`) rather than a broken workflow.
|
|
150
|
+
for (const address of resolvedAddresses(lookupResult)) {
|
|
151
|
+
const blockedReason = disallowedIpReason(address);
|
|
152
|
+
if (blockedReason !== undefined) {
|
|
153
|
+
return {
|
|
154
|
+
verdict: 'refuse',
|
|
155
|
+
reason: `--target-url host "${host}" resolves to ${address} (${blockedReason})`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Step 2 — HTTP probe. Runs through the global `fetch`, which picks up
|
|
161
|
+
// the proxy dispatcher `proxy.ts` installs at startup when one is
|
|
162
|
+
// configured — so this step (unlike the DNS step above) is proxy-aware
|
|
163
|
+
// by construction, not just proxy-tolerant.
|
|
164
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
165
|
+
try {
|
|
166
|
+
const resp = await fetchImpl(rawUrl, {
|
|
167
|
+
method: 'GET',
|
|
168
|
+
// Never follow — see the module docstring. A 3xx is reachability
|
|
169
|
+
// proof on its own (handled immediately below); the redirect target
|
|
170
|
+
// is unvalidated and must not be dereferenced.
|
|
171
|
+
redirect: 'manual',
|
|
172
|
+
signal: AbortSignal.timeout(PREFLIGHT_TIMEOUT_MS),
|
|
173
|
+
});
|
|
174
|
+
// Never read the body — only the status matters here. Cancel it so the
|
|
175
|
+
// connection is released promptly instead of buffering a full page.
|
|
176
|
+
void resp.body?.cancel().catch(() => undefined);
|
|
177
|
+
if (resp.status >= 300 && resp.status < 400) {
|
|
178
|
+
// A redirect is a live-server signal (e.g. a real app 302ing an
|
|
179
|
+
// unauthenticated GET to a login page) — reachable, not refused. The
|
|
180
|
+
// Location header is deliberately never inspected or dereferenced.
|
|
181
|
+
return { verdict: 'ok' };
|
|
182
|
+
}
|
|
183
|
+
if (GATEWAY_ERROR_STATUSES.has(resp.status)) {
|
|
184
|
+
if (proxied) {
|
|
185
|
+
return {
|
|
186
|
+
verdict: 'warn',
|
|
187
|
+
reason: `--target-url responded HTTP ${resp.status} — not conclusive behind a configured proxy`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
verdict: 'refuse',
|
|
192
|
+
reason: `--target-url responded HTTP ${resp.status} (gateway error — the target is unreachable)`,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
if (resp.status >= 400) {
|
|
196
|
+
return { verdict: 'warn', reason: `--target-url responded HTTP ${resp.status}` };
|
|
197
|
+
}
|
|
198
|
+
return { verdict: 'ok' };
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
if (errorHasCode(err, ['ECONNREFUSED'])) {
|
|
202
|
+
if (proxied) {
|
|
203
|
+
return {
|
|
204
|
+
verdict: 'warn',
|
|
205
|
+
reason: 'connection to --target-url was refused — not conclusive behind a configured proxy',
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
return { verdict: 'refuse', reason: 'connection to --target-url was refused (ECONNREFUSED)' };
|
|
209
|
+
}
|
|
210
|
+
if (isTimeoutError(err)) {
|
|
211
|
+
return {
|
|
212
|
+
verdict: 'warn',
|
|
213
|
+
reason: `--target-url did not respond within ${PREFLIGHT_TIMEOUT_MS / 1000}s`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
// TLS errors and anything else unclassified: warn only — the refusal
|
|
217
|
+
// set stays narrow to exactly what that analysis measured.
|
|
218
|
+
return {
|
|
219
|
+
verdict: 'warn',
|
|
220
|
+
reason: `could not reach --target-url (${err instanceof Error ? err.message : String(err)})`,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** Shared wording so `--help` and every refuse/warn message agree on the escape hatch. */
|
|
225
|
+
const SKIP_HINT = 'Skip this check entirely with --skip-preflight.';
|
|
226
|
+
/**
|
|
227
|
+
* Run the preflight and either throw (refuse), print an `[advisory]` line
|
|
228
|
+
* (warn), or no-op (ok / skipped). This is the call-site integration point
|
|
229
|
+
* — wired at all four `--target-url` trigger paths, after `assertNotLocal`
|
|
230
|
+
* and before the trigger POST.
|
|
231
|
+
*
|
|
232
|
+
* `skipPreflight: true` makes this a pure no-op with ZERO network calls —
|
|
233
|
+
* neither `dnsLookup` nor `fetchImpl` is invoked.
|
|
234
|
+
*/
|
|
235
|
+
export async function assertTargetUrlReachable(targetUrl, opts, deps, stderrFn) {
|
|
236
|
+
if (opts.skipPreflight === true)
|
|
237
|
+
return;
|
|
238
|
+
const outcome = await probeTargetUrl(targetUrl, deps);
|
|
239
|
+
if (outcome.verdict === 'refuse') {
|
|
240
|
+
throw ApiError.fromEnvelope({
|
|
241
|
+
error: {
|
|
242
|
+
code: 'VALIDATION_ERROR',
|
|
243
|
+
message: `--target-url is not reachable: ${outcome.reason}.`,
|
|
244
|
+
nextAction: 'This CLI probes reachability from where the CLI runs, not from the Lambda that ' +
|
|
245
|
+
'executes the test — a false positive is possible (e.g. an IP allowlist that permits ' +
|
|
246
|
+
`the Lambda but not this machine). If you're confident the target is reachable from the ` +
|
|
247
|
+
`test runner, retry with --skip-preflight. ${SKIP_HINT}`,
|
|
248
|
+
requestId: 'local',
|
|
249
|
+
details: { field: 'targetUrl', reason: 'target-unreachable', probeReason: outcome.reason },
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
if (outcome.verdict === 'warn') {
|
|
254
|
+
stderrFn(`[advisory] --target-url may not be reachable (${outcome.reason}); proceeding anyway ` +
|
|
255
|
+
`(the CLI probes from where it runs, not from the Lambda that executes the test, so this ` +
|
|
256
|
+
`is not conclusive). ${SKIP_HINT}`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
//# sourceMappingURL=target-url-preflight.js.map
|
package/dist/lib/target-url.d.ts
CHANGED
|
@@ -2,10 +2,13 @@
|
|
|
2
2
|
* CLI-side pre-flight guard for `--target-url`.
|
|
3
3
|
*
|
|
4
4
|
* Defense-in-depth: the backend is the trust boundary and performs DNS
|
|
5
|
-
* resolution.
|
|
6
|
-
* fast, friendly error before sending the request
|
|
7
|
-
* DNS rebinding (a public hostname that resolves to a private
|
|
8
|
-
*
|
|
5
|
+
* resolution. `assertNotLocal` below does **string/literal-only** checks
|
|
6
|
+
* to give a fast, friendly error before sending the request — it cannot by
|
|
7
|
+
* itself detect DNS rebinding (a public hostname that resolves to a private
|
|
8
|
+
* IP). That gap is closed one layer up: `target-url-preflight.ts` reuses
|
|
9
|
+
* `disallowedIpReason` (exported below) against the actually-*resolved*
|
|
10
|
+
* address before probing, so the same range list guards both the literal
|
|
11
|
+
* string and the DNS answer — not two drifting copies of it.
|
|
9
12
|
*
|
|
10
13
|
* CLI-side target-url guard (exit 5 on any rejection):
|
|
11
14
|
* - Reject non-http(s) schemes
|
|
@@ -13,7 +16,6 @@
|
|
|
13
16
|
* - Reject `169.254.0.0/16` link-local and the `169.254.169.254` metadata address
|
|
14
17
|
* - Reject RFC1918 literal IPv4 (10.x, 172.16-31.x, 192.168.x)
|
|
15
18
|
* - Reject IPv4-mapped IPv6 (`::ffff:…`), IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`)
|
|
16
|
-
* - Hostnames that resolve to private IPs are the backend's concern.
|
|
17
19
|
*/
|
|
18
20
|
/**
|
|
19
21
|
* Throws a local `VALIDATION_ERROR` (exit 5) when `rawUrl` is a
|
|
@@ -23,3 +25,18 @@
|
|
|
23
25
|
* Silently returns on allowed URLs.
|
|
24
26
|
*/
|
|
25
27
|
export declare function assertNotLocal(rawUrl: string): void;
|
|
28
|
+
/**
|
|
29
|
+
* Classify a bare IP-address literal — IPv4 dotted form, or IPv6 optionally
|
|
30
|
+
* wrapped in the `[...]` bracket notation `URL.hostname` uses — against the
|
|
31
|
+
* private/loopback/link-local/metadata blocklist. Returns the disallowed
|
|
32
|
+
* reason string, or `undefined` when the address is allowed.
|
|
33
|
+
*
|
|
34
|
+
* This is the single source of truth for the range list: `assertNotLocal`
|
|
35
|
+
* calls it for the literal `--target-url` string above, and the reachability
|
|
36
|
+
* preflight (`target-url-preflight.ts`) calls it again for a DNS-*resolved*
|
|
37
|
+
* address — a public-looking hostname whose A/AAAA record actually points
|
|
38
|
+
* at a private or metadata IP (DNS rebinding) is a distinct bypass from a
|
|
39
|
+
* literal private IP typed on the command line, and both need the same
|
|
40
|
+
* range list, not two drifting copies of it.
|
|
41
|
+
*/
|
|
42
|
+
export declare function disallowedIpReason(host: string): string | undefined;
|