@specific.dev/spectest 0.39.0 → 0.43.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/dist/browser.d.ts +21 -8
- package/dist/browser.js +78 -36
- package/dist/components/supabase.d.ts +87 -27
- package/dist/components/supabase.js +352 -69
- package/dist/daemon.d.ts +38 -0
- package/dist/daemon.js +464 -987
- package/dist/harness/build-context.d.ts +82 -0
- package/dist/harness/build-context.js +113 -0
- package/dist/harness/buildkit-progress.d.ts +37 -0
- package/dist/harness/buildkit-progress.js +66 -0
- package/dist/harness/container-run.d.ts +89 -0
- package/dist/harness/container-run.js +118 -0
- package/dist/harness/file-mounts.d.ts +91 -0
- package/dist/harness/file-mounts.js +119 -0
- package/dist/harness/hostmatch.d.ts +65 -0
- package/dist/harness/hostmatch.js +108 -0
- package/dist/harness/http-proxy.d.ts +62 -0
- package/dist/harness/http-proxy.js +104 -0
- package/dist/harness/ingress-table.d.ts +148 -0
- package/dist/harness/ingress-table.js +129 -0
- package/dist/harness/log-delta.d.ts +54 -0
- package/dist/harness/log-delta.js +83 -0
- package/dist/harness/main.d.ts +47 -0
- package/dist/harness/main.js +164 -0
- package/dist/harness/methods.d.ts +54 -0
- package/dist/harness/methods.js +65 -0
- package/dist/harness/names-registry.d.ts +63 -0
- package/dist/harness/names-registry.js +90 -0
- package/dist/harness/protocol.d.ts +88 -0
- package/dist/harness/protocol.js +96 -0
- package/dist/harness/ready-poll.d.ts +47 -0
- package/dist/harness/ready-poll.js +67 -0
- package/dist/harness/service-graph.d.ts +29 -0
- package/dist/harness/service-graph.js +92 -0
- package/dist/harness/volume-paths.d.ts +70 -0
- package/dist/harness/volume-paths.js +81 -0
- package/dist/index.d.ts +58 -16
- package/dist/ingress.d.ts +1 -1
- package/dist/mobile.d.ts +9 -5
- package/dist/mobile.js +7 -6
- package/dist/recorder.d.ts +10 -0
- package/dist/resolver.js +5 -8
- package/dist/vendor/rrweb-plugin-console-record.umd.js +521 -0
- package/dist/vendor/rrweb-record.min.js +5061 -0
- package/package.json +7 -1
- package/src/aws-sigv4.ts +218 -0
- package/src/browser.ts +2095 -0
- package/src/components/aws.ts +554 -0
- package/src/components/email.ts +398 -0
- package/src/components/expo.ts +167 -0
- package/src/components/index.ts +81 -0
- package/src/components/k3s.ts +2061 -0
- package/src/components/postgres.ts +132 -0
- package/src/components/replayFake.ts +1015 -0
- package/src/components/s3.ts +132 -0
- package/src/components/supabase.ts +1699 -0
- package/src/daemon.ts +5537 -0
- package/src/harness/build-context.test.ts +0 -0
- package/src/harness/build-context.ts +146 -0
- package/src/harness/buildkit-progress.test.ts +98 -0
- package/src/harness/buildkit-progress.ts +74 -0
- package/src/harness/container-run.test.ts +209 -0
- package/src/harness/container-run.ts +158 -0
- package/src/harness/file-mounts.test.ts +185 -0
- package/src/harness/file-mounts.ts +145 -0
- package/src/harness/hostmatch.test.ts +148 -0
- package/src/harness/hostmatch.ts +109 -0
- package/src/harness/http-proxy.test.ts +156 -0
- package/src/harness/http-proxy.ts +119 -0
- package/src/harness/ingress-rebind.test.ts +125 -0
- package/src/harness/ingress-table.test.ts +172 -0
- package/src/harness/ingress-table.ts +186 -0
- package/src/harness/log-delta.test.ts +125 -0
- package/src/harness/log-delta.ts +100 -0
- package/src/harness/main.test.ts +211 -0
- package/src/harness/main.ts +196 -0
- package/src/harness/methods.test.ts +63 -0
- package/src/harness/methods.ts +92 -0
- package/src/harness/names-registry.test.ts +137 -0
- package/src/harness/names-registry.ts +108 -0
- package/src/harness/protocol.test.ts +148 -0
- package/src/harness/protocol.ts +163 -0
- package/src/harness/ready-poll.test.ts +172 -0
- package/src/harness/ready-poll.ts +93 -0
- package/src/harness/service-graph.test.ts +97 -0
- package/src/harness/service-graph.ts +97 -0
- package/src/harness/volume-paths.test.ts +102 -0
- package/src/harness/volume-paths.ts +112 -0
- package/src/ids.ts +89 -0
- package/src/index.ts +2767 -0
- package/src/ingress.ts +305 -0
- package/src/inspect.ts +739 -0
- package/src/locator.ts +716 -0
- package/src/mobile.ts +138 -0
- package/src/record-secrets.ts +41 -0
- package/src/recorder.ts +856 -0
- package/src/redis.ts +202 -0
- package/src/replay-bundle.ts +108 -0
- package/src/resolver.ts +348 -0
- package/src/s3.ts +333 -0
- package/src/sql.ts +243 -0
- package/src/terminal.ts +740 -0
- package/src/url-match.ts +67 -0
- package/src/vendor/rrweb-plugin-console-record.umd.js +521 -0
- package/src/vendor/rrweb-record.min.js +5061 -0
|
@@ -0,0 +1,1015 @@
|
|
|
1
|
+
// Record/replay fake — a VCR-style cassette fake.
|
|
2
|
+
//
|
|
3
|
+
// `replayFake({...})` returns a plain `FakeDefinition`, so it drops
|
|
4
|
+
// straight into `fakes: { stripe: replayFake({...}) }` and inherits all
|
|
5
|
+
// the existing fakes machinery: ingress lowering mints the TLS leaf cert
|
|
6
|
+
// and registers the hostname, dispatch routes by `Host` header to the
|
|
7
|
+
// generated `handler`, and `state` forks per test like any fake.
|
|
8
|
+
//
|
|
9
|
+
// You fake the REAL host directly — `host: "api.stripe.com"`, not a
|
|
10
|
+
// stand-in. The fake answers for that name on both `http://` (:80) and
|
|
11
|
+
// `https://` (:443, in-VM-CA leaf cert), and the SAME name is what gets
|
|
12
|
+
// forwarded to the real upstream in record mode. The two modes:
|
|
13
|
+
//
|
|
14
|
+
// - REPLAY (hermetic): the request is matched against the cassette the
|
|
15
|
+
// test EXPLICITLY loaded (`ctx.fakes.<name>.replay(file)`) and the
|
|
16
|
+
// recorded response is returned. No network. Nothing is auto-loaded:
|
|
17
|
+
// a test that loads no cassette gets a fail-loud 599 on every request.
|
|
18
|
+
// This is what runs under `spectest test`.
|
|
19
|
+
// - RECORD (MITM): the request is forwarded to the REAL host and the
|
|
20
|
+
// request/response pair is captured (decoded, redacted), and the real
|
|
21
|
+
// response is returned to the app so a manual session behaves like
|
|
22
|
+
// production. This runs under `spectest env eval` against a manual env.
|
|
23
|
+
//
|
|
24
|
+
// Because the fake's hostname IS the real host, the in-VM resolver points
|
|
25
|
+
// that name at the daemon — so a naive `fetch("https://api.stripe.com")`
|
|
26
|
+
// from the record-mode forwarder would loop straight back into us. The
|
|
27
|
+
// forwarder therefore resolves the real IP itself against an EXTERNAL DNS
|
|
28
|
+
// server (default 1.1.1.1, `SPECTEST_UPSTREAM_DNS`), then opens a real TLS
|
|
29
|
+
// connection to that IP with the correct SNI/`Host` (validating the real
|
|
30
|
+
// public cert). This is a transparent MITM: the app's leg is terminated
|
|
31
|
+
// with our in-VM-CA leaf; the upstream leg is a genuine public-cert TLS
|
|
32
|
+
// handshake to the real host.
|
|
33
|
+
//
|
|
34
|
+
// Mode is chosen by `isRecording()`: it is true only inside an active
|
|
35
|
+
// recorder (a `spectest test` case), false in eval/manual. So `auto`
|
|
36
|
+
// (the default) replays under test and records under eval — no new
|
|
37
|
+
// control-plane mode flag. `mode: "record" | "replay"` overrides it.
|
|
38
|
+
//
|
|
39
|
+
// Credential brokering (per-fake): `inject` rules set
|
|
40
|
+
// headers on the egress forward — overwriting whatever the app sent — so
|
|
41
|
+
// app code never holds the credential. Header values embed `{{secret:REF}}`
|
|
42
|
+
// tokens; each REF is resolved server-side from the platform Secrets store
|
|
43
|
+
// and pushed eval-scoped from the control plane (via {@link getRecordSecret}).
|
|
44
|
+
// The real value lives only on the outbound wire to the real upstream and
|
|
45
|
+
// is redacted from the cassette (fail-closed) — it never enters project
|
|
46
|
+
// code, the tarball, the warm-cache hash, or any snapshot a hermetic run
|
|
47
|
+
// could fork.
|
|
48
|
+
//
|
|
49
|
+
// AWS SigV4 (`sign: { type: "awsSigv4", ... }`): static header injection
|
|
50
|
+
// can't broker AWS auth — the `Authorization` value is a keyed HMAC over the
|
|
51
|
+
// entire request, not a static token. So the forward instead RE-SIGNS: the
|
|
52
|
+
// app signs with throwaway dummy creds (any AWS SDK refuses to build a request
|
|
53
|
+
// with none), we strip that signature and re-sign the exact outbound request
|
|
54
|
+
// with the real credentials (also direct secret refs, same eval-scoped push +
|
|
55
|
+
// redaction). Region/service are inferred from the request. See
|
|
56
|
+
// `../aws-sigv4.ts`.
|
|
57
|
+
|
|
58
|
+
import { createSocket } from "node:dgram";
|
|
59
|
+
import { createHash } from "node:crypto";
|
|
60
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
61
|
+
import { request as httpsRequest } from "node:https";
|
|
62
|
+
import path from "node:path";
|
|
63
|
+
import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
|
|
64
|
+
import * as dnsPacket from "dns-packet";
|
|
65
|
+
|
|
66
|
+
import type { FakeContext, FakeDefinition } from "../index.js";
|
|
67
|
+
import { isRecording } from "../recorder.js";
|
|
68
|
+
import { getRecordSecret } from "../record-secrets.js";
|
|
69
|
+
import {
|
|
70
|
+
inferSigV4Scope,
|
|
71
|
+
signAwsV4Request,
|
|
72
|
+
type SigV4Credentials,
|
|
73
|
+
} from "../aws-sigv4.js";
|
|
74
|
+
|
|
75
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
76
|
+
// Options + cassette format
|
|
77
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
78
|
+
|
|
79
|
+
/** Which parts of a request define a match against the cassette. */
|
|
80
|
+
export interface ReplayMatch {
|
|
81
|
+
/** Match on HTTP method. Default `true`. */
|
|
82
|
+
method?: boolean;
|
|
83
|
+
/** Match on path (no query). Default `true`. */
|
|
84
|
+
path?: boolean;
|
|
85
|
+
/** Match on normalized query string. Default `true`. */
|
|
86
|
+
query?: boolean;
|
|
87
|
+
/** Match on body: `true` = exact decoded body, `"hash"` = sha256 only.
|
|
88
|
+
* Default off. */
|
|
89
|
+
body?: boolean | "hash";
|
|
90
|
+
/** Header names (lowercase) to include in the match. Default none. */
|
|
91
|
+
headers?: string[];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Match one request dimension. A bare string is an exact match; the
|
|
95
|
+
* object forms cover prefix and regex matching. */
|
|
96
|
+
export type StringMatch =
|
|
97
|
+
| string
|
|
98
|
+
| { exact: string }
|
|
99
|
+
| { startsWith: string }
|
|
100
|
+
| { regex: string };
|
|
101
|
+
|
|
102
|
+
/** Request matchers for a credential-injection rule. A rule applies only
|
|
103
|
+
* when EVERY specified dimension matches; omit `match` to always apply. */
|
|
104
|
+
export interface InjectMatch {
|
|
105
|
+
/** Match the request path (no query). */
|
|
106
|
+
path?: StringMatch;
|
|
107
|
+
/** HTTP method(s) — any one matching satisfies it. */
|
|
108
|
+
method?: string | string[];
|
|
109
|
+
/** Query-param matchers (ANDed); each key's value(s) must match. */
|
|
110
|
+
query?: Record<string, StringMatch>;
|
|
111
|
+
/** Header matchers (ANDed; header names case-insensitive). */
|
|
112
|
+
headers?: Record<string, StringMatch>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** One credential-brokering rule. When it matches a request, these headers
|
|
116
|
+
* are SET on the egress forward — overwriting whatever the app sent (so app
|
|
117
|
+
* code can't smuggle a different value past the broker). Header VALUES may
|
|
118
|
+
* embed `{{secret:REF}}` tokens; each `REF` is resolved server-side from the
|
|
119
|
+
* project's Secrets store and pushed eval-scoped — the real value never
|
|
120
|
+
* enters project code, the
|
|
121
|
+
* tarball, the warm-cache hash, or a cassette (it's redacted, fail-closed). */
|
|
122
|
+
export interface InjectRule {
|
|
123
|
+
match?: InjectMatch;
|
|
124
|
+
headers: Record<string, string>;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** SigV4 request-signing broker. Unlike `inject` (which SETs a static header
|
|
128
|
+
* value), this RE-SIGNS the outbound request: the app signs with throwaway
|
|
129
|
+
* dummy credentials, we strip that signature and re-sign the exact outbound
|
|
130
|
+
* request with the real credentials — the only way to broker AWS auth, whose
|
|
131
|
+
* signature is a keyed HMAC over the whole request, not a static token.
|
|
132
|
+
*
|
|
133
|
+
* The three fields are **secret refs, resolved directly** from the project's
|
|
134
|
+
* Secrets store (NOT `{{secret:}}` templates) — same eval-scoped push and
|
|
135
|
+
* fail-closed redaction as `inject`. Region + service are inferred from the
|
|
136
|
+
* incoming request (its credential scope, else the host); the app never
|
|
137
|
+
* configures them. */
|
|
138
|
+
export interface AwsSigV4Sign {
|
|
139
|
+
type: "awsSigv4";
|
|
140
|
+
/** Secret ref for the AWS access key id. */
|
|
141
|
+
accessKeyId: string;
|
|
142
|
+
/** Secret ref for the AWS secret access key. */
|
|
143
|
+
secretAccessKey: string;
|
|
144
|
+
/** Optional secret ref for a session token (temporary credentials). */
|
|
145
|
+
sessionToken?: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export type SignConfig = AwsSigV4Sign;
|
|
149
|
+
|
|
150
|
+
export interface ReplayFakeOptions {
|
|
151
|
+
/** Stable name — the `ctx.fakes` key. */
|
|
152
|
+
name: string;
|
|
153
|
+
/** The REAL host to fake, e.g. `"api.stripe.com"`. The fake answers for
|
|
154
|
+
* this name on both `http://` (:80) and `https://` (:443), and the same
|
|
155
|
+
* name is forwarded to the real upstream in record mode (over HTTPS,
|
|
156
|
+
* resolved via an external DNS server — see the module header). Your
|
|
157
|
+
* app points at this real host directly; no separate stand-in. */
|
|
158
|
+
host: string;
|
|
159
|
+
/** What defines a request match. Default `{ method, path, query }`. */
|
|
160
|
+
match?: ReplayMatch;
|
|
161
|
+
/** Per-fake credential brokering. Rules are evaluated in
|
|
162
|
+
* order; the first whose `match` matches wins (a rule without `match`
|
|
163
|
+
* matches everything and shadows later rules). Applied at the
|
|
164
|
+
* record-mode egress forward; resolved secret values are redacted from
|
|
165
|
+
* the cassette (fail-closed). */
|
|
166
|
+
inject?: InjectRule[];
|
|
167
|
+
/** SigV4 request signing (AWS). When set, the record-mode forward strips the
|
|
168
|
+
* app's dummy signature and re-signs the outbound request with the brokered
|
|
169
|
+
* credentials. Point your AWS SDK at the real host with any dummy static
|
|
170
|
+
* creds (e.g. `AWS_ACCESS_KEY_ID=test`) — the dummies are stripped and the
|
|
171
|
+
* real ones live only on the outbound wire (redacted from the cassette). */
|
|
172
|
+
sign?: SignConfig;
|
|
173
|
+
/** Extra substrings/patterns to scrub from stored request/response
|
|
174
|
+
* bodies and queries (every injected secret value is always scrubbed). */
|
|
175
|
+
redactPatterns?: (string | RegExp)[];
|
|
176
|
+
/** `"auto"` (default) records under eval and replays under test;
|
|
177
|
+
* `"record"` / `"replay"` force a mode. */
|
|
178
|
+
mode?: "auto" | "record" | "replay";
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface CassetteRequest {
|
|
182
|
+
method: string;
|
|
183
|
+
path: string;
|
|
184
|
+
/** Normalized: keys + repeated values sorted, so matching is order-free. */
|
|
185
|
+
query: Record<string, string[]>;
|
|
186
|
+
/** Matched/readable header subset only — never `authorization`/`cookie`. */
|
|
187
|
+
headers: Record<string, string>;
|
|
188
|
+
bodyHash?: string;
|
|
189
|
+
/** Request body (omitted when empty): decoded + redacted UTF-8 text, or
|
|
190
|
+
* base64 for binary payloads (S3 object PUTs, protobuf, …). */
|
|
191
|
+
body?: string;
|
|
192
|
+
/** Encoding of `body`. Absent = `"utf8"` (back-compat with old cassettes). */
|
|
193
|
+
bodyEncoding?: "utf8" | "base64";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export interface CassetteResponse {
|
|
197
|
+
status: number;
|
|
198
|
+
headers: Record<string, string>;
|
|
199
|
+
/** Decoded + redacted response body. */
|
|
200
|
+
body: string;
|
|
201
|
+
bodyEncoding: "utf8" | "base64";
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export interface CassetteInteraction {
|
|
205
|
+
request: CassetteRequest;
|
|
206
|
+
response: CassetteResponse;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export interface Cassette {
|
|
210
|
+
version: 1;
|
|
211
|
+
fake: string;
|
|
212
|
+
/** The real host this cassette mirrors (e.g. `api.stripe.com`). */
|
|
213
|
+
host: string;
|
|
214
|
+
interactions: CassetteInteraction[];
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Forked-per-test state for one replay fake. */
|
|
218
|
+
export interface CassetteState {
|
|
219
|
+
cassette: Cassette;
|
|
220
|
+
/** Per-match-signature replay cursor (call-order sequencing). */
|
|
221
|
+
cursor: Map<string, number>;
|
|
222
|
+
/** Interactions captured this record session. */
|
|
223
|
+
recorded: CassetteInteraction[];
|
|
224
|
+
dirty: boolean;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** What `replay(...)` returns — a small summary that surfaces in the test
|
|
228
|
+
* timeline (recorded as a `fake` event) so the run shows exactly which
|
|
229
|
+
* cassette a test loaded and how many interactions it carried. */
|
|
230
|
+
export interface ReplaySummary {
|
|
231
|
+
/** Filename loaded (under `spectest/recordings/`) or `"(inline)"`. */
|
|
232
|
+
cassette: string;
|
|
233
|
+
/** The real host the cassette mirrors. */
|
|
234
|
+
host: string;
|
|
235
|
+
/** Number of interactions now available for replay. */
|
|
236
|
+
interactions: number;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export interface ReplayHelpers extends Record<string, unknown> {
|
|
240
|
+
/** Load a cassette into THIS fork's replay set and replay from it,
|
|
241
|
+
* replacing whatever was loaded before and resetting the replay cursor.
|
|
242
|
+
* Cassettes are NOT auto-loaded — call this at the top of a test. Pass a
|
|
243
|
+
* path relative to `spectest/tests/` (e.g. `"recordings/stripe.json"`; it
|
|
244
|
+
* must stay under `spectest/tests/`) or a cassette object; a missing file
|
|
245
|
+
* throws. The returned summary is recorded as a step, so the UI timeline
|
|
246
|
+
* shows what was loaded. */
|
|
247
|
+
replay(file: string | Cassette): ReplaySummary;
|
|
248
|
+
/** Full cassette JSON (loaded interactions + newly recorded, redacted)
|
|
249
|
+
* — the MVP delivery channel: `export default ctx.fakes.<name>.dump()`,
|
|
250
|
+
* then write the result to `spectest/recordings/<name>.json`. */
|
|
251
|
+
dump(): Cassette;
|
|
252
|
+
/** Interactions captured this record session. */
|
|
253
|
+
recorded(): CassetteInteraction[];
|
|
254
|
+
/** Count of interactions captured this record session. */
|
|
255
|
+
count(): number;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
259
|
+
// Helpers
|
|
260
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
261
|
+
|
|
262
|
+
const SENSITIVE_HEADERS = new Set([
|
|
263
|
+
"authorization",
|
|
264
|
+
"cookie",
|
|
265
|
+
"set-cookie",
|
|
266
|
+
"proxy-authorization",
|
|
267
|
+
"x-api-key",
|
|
268
|
+
"x-amz-security-token",
|
|
269
|
+
]);
|
|
270
|
+
|
|
271
|
+
/** Hop-by-hop + body-framing headers never forwarded / never replayed
|
|
272
|
+
* (we decompress on the way through, so the encoding/length no longer
|
|
273
|
+
* describe the bytes the app receives). */
|
|
274
|
+
const STRIP_FORWARD_HEADERS = new Set([
|
|
275
|
+
"host",
|
|
276
|
+
"connection",
|
|
277
|
+
"keep-alive",
|
|
278
|
+
"proxy-authenticate",
|
|
279
|
+
"proxy-authorization",
|
|
280
|
+
"te",
|
|
281
|
+
"trailers",
|
|
282
|
+
"transfer-encoding",
|
|
283
|
+
"upgrade",
|
|
284
|
+
"content-length",
|
|
285
|
+
"content-encoding",
|
|
286
|
+
// We force `accept-encoding: identity` on the forward and decompress any
|
|
287
|
+
// residual encoding, so the app never sees a stale accept-encoding.
|
|
288
|
+
"accept-encoding",
|
|
289
|
+
]);
|
|
290
|
+
|
|
291
|
+
/** External resolver used to find the REAL upstream IP, bypassing the in-VM
|
|
292
|
+
* resolver (which points the faked host back at the daemon). */
|
|
293
|
+
const EXTERNAL_DNS = process.env.SPECTEST_UPSTREAM_DNS ?? "1.1.1.1";
|
|
294
|
+
const EXTERNAL_DNS_PORT = Number(process.env.SPECTEST_UPSTREAM_PORT ?? "53");
|
|
295
|
+
|
|
296
|
+
function defaultMatch(m: ReplayMatch | undefined): Required<Omit<ReplayMatch, "body" | "headers">> &
|
|
297
|
+
Pick<ReplayMatch, "body" | "headers"> {
|
|
298
|
+
return {
|
|
299
|
+
method: m?.method ?? true,
|
|
300
|
+
path: m?.path ?? true,
|
|
301
|
+
query: m?.query ?? true,
|
|
302
|
+
body: m?.body,
|
|
303
|
+
headers: m?.headers,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** SigV4 puts per-request signing params (`X-Amz-Signature`, `X-Amz-Date`, …)
|
|
308
|
+
* in the query for presigned URLs — they change every call and would poison
|
|
309
|
+
* query matching, so they're dropped from both the match key and the forward
|
|
310
|
+
* when signing is active. */
|
|
311
|
+
function isAmzParam(key: string): boolean {
|
|
312
|
+
return key.toLowerCase().startsWith("x-amz-");
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function stripAmzParams(search: URLSearchParams): URLSearchParams {
|
|
316
|
+
const out = new URLSearchParams();
|
|
317
|
+
for (const [k, v] of search) if (!isAmzParam(k)) out.append(k, v);
|
|
318
|
+
return out;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function normalizeQuery(search: URLSearchParams, stripAmz: boolean): Record<string, string[]> {
|
|
322
|
+
const out: Record<string, string[]> = {};
|
|
323
|
+
for (const key of [...search.keys()].sort()) {
|
|
324
|
+
if (stripAmz && isAmzParam(key)) continue;
|
|
325
|
+
out[key] = search.getAll(key).slice().sort();
|
|
326
|
+
}
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function sha256Bytes(bytes: Uint8Array): string {
|
|
331
|
+
return "sha256:" + createHash("sha256").update(Buffer.from(bytes)).digest("hex");
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function recordable(headers: Headers, want: string[]): Record<string, string> {
|
|
335
|
+
const out: Record<string, string> = {};
|
|
336
|
+
for (const name of want) {
|
|
337
|
+
const lower = name.toLowerCase();
|
|
338
|
+
if (SENSITIVE_HEADERS.has(lower)) continue;
|
|
339
|
+
const v = headers.get(lower);
|
|
340
|
+
if (v !== null) out[lower] = v;
|
|
341
|
+
}
|
|
342
|
+
return out;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Canonical match signature for an interaction's request, used as both
|
|
346
|
+
* the replay-cursor key and the equality basis (two requests match iff
|
|
347
|
+
* their signatures are equal). Computed identically for an incoming
|
|
348
|
+
* request and a stored `CassetteRequest`. */
|
|
349
|
+
function signature(req: CassetteRequest, match: ReturnType<typeof defaultMatch>): string {
|
|
350
|
+
const sig: Record<string, unknown> = {};
|
|
351
|
+
if (match.method) sig.method = req.method.toUpperCase();
|
|
352
|
+
if (match.path) sig.path = req.path;
|
|
353
|
+
if (match.query) sig.query = req.query;
|
|
354
|
+
if (match.body === true) sig.body = req.body ?? "";
|
|
355
|
+
else if (match.body === "hash") sig.bodyHash = req.bodyHash ?? "";
|
|
356
|
+
if (match.headers && match.headers.length > 0) {
|
|
357
|
+
const h: Record<string, string> = {};
|
|
358
|
+
for (const name of match.headers.map((n) => n.toLowerCase()).sort()) {
|
|
359
|
+
h[name] = req.headers[name] ?? "";
|
|
360
|
+
}
|
|
361
|
+
sig.headers = h;
|
|
362
|
+
}
|
|
363
|
+
return JSON.stringify(sig);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** The project's `spectest/tests/` dir — cassettes live alongside the
|
|
367
|
+
* tests, and a `replay(path)` argument is a path relative to here. Keeping
|
|
368
|
+
* them under `tests/` means re-recording is picked up on the next run with
|
|
369
|
+
* no environment rebuild (that subtree is re-imported with the tests). */
|
|
370
|
+
function cassetteRoot(): string {
|
|
371
|
+
const spectestDir =
|
|
372
|
+
process.env.SPECTEST_PROJECT_DIR ??
|
|
373
|
+
path.join(process.env.SPECTEST_APP_DIR ?? "/opt/spectest/app", "spectest");
|
|
374
|
+
return path.join(spectestDir, "tests");
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function emptyCassette(name: string, host: string): Cassette {
|
|
378
|
+
return { version: 1, fake: name, host, interactions: [] };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Validate + normalize a parsed cassette (from a file or passed inline). */
|
|
382
|
+
function coerceCassette(parsed: Cassette, name: string, host: string): Cassette {
|
|
383
|
+
if (!parsed || !Array.isArray(parsed.interactions)) {
|
|
384
|
+
throw new Error(`replayFake(${name}): cassette has no \`interactions\` array`);
|
|
385
|
+
}
|
|
386
|
+
return {
|
|
387
|
+
version: 1,
|
|
388
|
+
fake: parsed.fake ?? name,
|
|
389
|
+
host: parsed.host ?? host,
|
|
390
|
+
interactions: parsed.interactions,
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Read a cassette by its path relative to `spectest/tests/` (e.g.
|
|
395
|
+
* `"recordings/stripe.json"`). The path must stay under `spectest/tests/`,
|
|
396
|
+
* and explicit loads must point at a real file — a missing one throws (fail
|
|
397
|
+
* loud) rather than silently replaying nothing. */
|
|
398
|
+
function readCassetteFile(name: string, file: string, host: string): Cassette {
|
|
399
|
+
const base = cassetteRoot();
|
|
400
|
+
const p = path.resolve(base, file);
|
|
401
|
+
if (p !== base && !p.startsWith(base + path.sep)) {
|
|
402
|
+
throw new Error(
|
|
403
|
+
`replayFake(${name}): cassette path ${JSON.stringify(file)} must be under spectest/tests/`,
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
if (!existsSync(p)) {
|
|
407
|
+
throw new Error(
|
|
408
|
+
`replayFake(${name}): cassette not found at ${p} — record one first, or pass a cassette object.`,
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
let parsed: Cassette;
|
|
412
|
+
try {
|
|
413
|
+
parsed = JSON.parse(readFileSync(p, "utf8")) as Cassette;
|
|
414
|
+
} catch (err) {
|
|
415
|
+
throw new Error(
|
|
416
|
+
`replayFake(${name}): failed to read cassette ${p}: ${(err as Error).message}`,
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
return coerceCassette(parsed, name, host);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Decode response bytes to a string, falling back to base64 for binary. */
|
|
423
|
+
function decodeBody(bytes: Uint8Array): { body: string; bodyEncoding: "utf8" | "base64" } {
|
|
424
|
+
try {
|
|
425
|
+
const text = new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
426
|
+
return { body: text, bodyEncoding: "utf8" };
|
|
427
|
+
} catch {
|
|
428
|
+
return { body: Buffer.from(bytes).toString("base64"), bodyEncoding: "base64" };
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** One resolved secret value and the ref it came from (for the redaction
|
|
433
|
+
* placeholder). */
|
|
434
|
+
interface ResolvedSecret {
|
|
435
|
+
ref: string;
|
|
436
|
+
value: string;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function makeRedactor(
|
|
440
|
+
secrets: ResolvedSecret[],
|
|
441
|
+
patterns: (string | RegExp)[] | undefined,
|
|
442
|
+
): (s: string) => string {
|
|
443
|
+
return (s: string): string => {
|
|
444
|
+
let out = s;
|
|
445
|
+
for (const { ref, value } of secrets) {
|
|
446
|
+
if (value.length > 0) out = out.split(value).join(`<REDACTED:${ref}>`);
|
|
447
|
+
}
|
|
448
|
+
for (const p of patterns ?? []) {
|
|
449
|
+
if (typeof p === "string") {
|
|
450
|
+
if (p.length > 0) out = out.split(p).join("<REDACTED>");
|
|
451
|
+
} else {
|
|
452
|
+
const g = p.flags.includes("g") ? p : new RegExp(p.source, p.flags + "g");
|
|
453
|
+
out = out.replace(g, "<REDACTED>");
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return out;
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
461
|
+
// Credential brokering: matchers + secret-token resolution
|
|
462
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
463
|
+
|
|
464
|
+
/** `{{secret:REF}}` template token embedded in an injected header value. */
|
|
465
|
+
const SECRET_TOKEN = /\{\{secret:([A-Za-z0-9_]+)\}\}/g;
|
|
466
|
+
|
|
467
|
+
/** Every secret ref referenced by any inject rule's header templates plus the
|
|
468
|
+
* SigV4 signing credentials (direct refs, not templates). */
|
|
469
|
+
function collectSecretRefs(rules: InjectRule[], sign: SignConfig | undefined): string[] {
|
|
470
|
+
const refs = new Set<string>();
|
|
471
|
+
for (const rule of rules) {
|
|
472
|
+
for (const value of Object.values(rule.headers)) {
|
|
473
|
+
for (const m of value.matchAll(SECRET_TOKEN)) refs.add(m[1]);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (sign?.type === "awsSigv4") {
|
|
477
|
+
refs.add(sign.accessKeyId);
|
|
478
|
+
refs.add(sign.secretAccessKey);
|
|
479
|
+
if (sign.sessionToken) refs.add(sign.sessionToken);
|
|
480
|
+
}
|
|
481
|
+
return [...refs];
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function matchString(m: StringMatch, value: string): boolean {
|
|
485
|
+
if (typeof m === "string") return value === m;
|
|
486
|
+
if ("exact" in m) return value === m.exact;
|
|
487
|
+
if ("startsWith" in m) return value.startsWith(m.startsWith);
|
|
488
|
+
if ("regex" in m) return new RegExp(m.regex).test(value);
|
|
489
|
+
return false;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
interface IncomingRequest {
|
|
493
|
+
method: string;
|
|
494
|
+
path: string;
|
|
495
|
+
query: URLSearchParams;
|
|
496
|
+
headers: Headers;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** True if every dimension the matcher specifies is satisfied (AND across
|
|
500
|
+
* dimensions). No `match` → always true. */
|
|
501
|
+
function ruleMatches(match: InjectMatch | undefined, req: IncomingRequest): boolean {
|
|
502
|
+
if (!match) return true;
|
|
503
|
+
if (match.path !== undefined && !matchString(match.path, req.path)) return false;
|
|
504
|
+
if (match.method !== undefined) {
|
|
505
|
+
const methods = (Array.isArray(match.method) ? match.method : [match.method]).map((s) =>
|
|
506
|
+
s.toUpperCase(),
|
|
507
|
+
);
|
|
508
|
+
if (!methods.includes(req.method.toUpperCase())) return false;
|
|
509
|
+
}
|
|
510
|
+
if (match.query) {
|
|
511
|
+
for (const [k, m] of Object.entries(match.query)) {
|
|
512
|
+
if (!req.query.getAll(k).some((v) => matchString(m, v))) return false;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
if (match.headers) {
|
|
516
|
+
for (const [k, m] of Object.entries(match.headers)) {
|
|
517
|
+
const v = req.headers.get(k.toLowerCase());
|
|
518
|
+
if (v === null || !matchString(m, v)) return false;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
return true;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
interface BrokeredHeaders {
|
|
525
|
+
/** Lowercased header → resolved value, to SET on the forward. */
|
|
526
|
+
headers: Record<string, string>;
|
|
527
|
+
/** Resolved secrets (for redaction). */
|
|
528
|
+
secrets: ResolvedSecret[];
|
|
529
|
+
/** Refs referenced but not supplied by the control plane. */
|
|
530
|
+
missing: string[];
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** Resolve a rule's header templates, substituting every `{{secret:REF}}`
|
|
534
|
+
* with the eval-scoped value. Collects resolved secrets (for redaction)
|
|
535
|
+
* and any refs the control plane didn't supply (fail loud). */
|
|
536
|
+
function brokerHeaders(rule: InjectRule): BrokeredHeaders {
|
|
537
|
+
const headers: Record<string, string> = {};
|
|
538
|
+
const secrets: ResolvedSecret[] = [];
|
|
539
|
+
const missing: string[] = [];
|
|
540
|
+
const seen = new Set<string>();
|
|
541
|
+
for (const [name, template] of Object.entries(rule.headers)) {
|
|
542
|
+
headers[name.toLowerCase()] = template.replace(SECRET_TOKEN, (_full, ref: string) => {
|
|
543
|
+
const value = getRecordSecret(ref);
|
|
544
|
+
if (value === undefined) {
|
|
545
|
+
missing.push(ref);
|
|
546
|
+
return "";
|
|
547
|
+
}
|
|
548
|
+
if (!seen.has(ref)) {
|
|
549
|
+
seen.add(ref);
|
|
550
|
+
secrets.push({ ref, value });
|
|
551
|
+
}
|
|
552
|
+
return value;
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
return { headers, secrets, missing };
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
559
|
+
// Record-mode egress: resolve the real host externally, then MITM-forward
|
|
560
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
561
|
+
|
|
562
|
+
/** Resolve a host's A records against an EXTERNAL DNS server, bypassing the
|
|
563
|
+
* in-VM resolver (which would answer with the daemon's own gateway for a
|
|
564
|
+
* faked host). Mirrors spectest-resolver's own upstream-forward transport
|
|
565
|
+
* (dns-packet over UDP) so it works identically in-VM. */
|
|
566
|
+
function resolveExternalA(host: string): Promise<string[]> {
|
|
567
|
+
const query = dnsPacket.encode({
|
|
568
|
+
type: "query",
|
|
569
|
+
id: 1,
|
|
570
|
+
flags: dnsPacket.RECURSION_DESIRED,
|
|
571
|
+
questions: [{ type: "A", name: host }],
|
|
572
|
+
});
|
|
573
|
+
return new Promise((resolve) => {
|
|
574
|
+
const sock = createSocket("udp4");
|
|
575
|
+
let done = false;
|
|
576
|
+
const finish = (ips: string[]): void => {
|
|
577
|
+
if (done) return;
|
|
578
|
+
done = true;
|
|
579
|
+
try {
|
|
580
|
+
sock.close();
|
|
581
|
+
} catch {
|
|
582
|
+
// ignore
|
|
583
|
+
}
|
|
584
|
+
resolve(ips);
|
|
585
|
+
};
|
|
586
|
+
sock.on("message", (msg) => {
|
|
587
|
+
try {
|
|
588
|
+
const res = dnsPacket.decode(msg);
|
|
589
|
+
const ips = (res.answers ?? []).flatMap((a) =>
|
|
590
|
+
a.type === "A" && typeof a.data === "string" && a.data.length > 0 ? [a.data] : [],
|
|
591
|
+
);
|
|
592
|
+
finish(ips);
|
|
593
|
+
} catch {
|
|
594
|
+
finish([]);
|
|
595
|
+
}
|
|
596
|
+
});
|
|
597
|
+
sock.on("error", () => finish([]));
|
|
598
|
+
sock.send(query, EXTERNAL_DNS_PORT, EXTERNAL_DNS, (err) => {
|
|
599
|
+
if (err) finish([]);
|
|
600
|
+
});
|
|
601
|
+
setTimeout(() => finish([]), 3_000);
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
interface UpstreamResponse {
|
|
606
|
+
status: number;
|
|
607
|
+
headers: Record<string, string>;
|
|
608
|
+
/** Decompressed body bytes. */
|
|
609
|
+
bytes: Uint8Array;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** Open a real HTTPS connection to `ip` but with SNI + `Host` = `host`, so
|
|
613
|
+
* the public certificate validates against the real hostname (the in-VM CA
|
|
614
|
+
* is not involved on this leg). Decompresses the response so the stored and
|
|
615
|
+
* returned bytes are the plain payload. */
|
|
616
|
+
function forwardToRealUpstream(args: {
|
|
617
|
+
ip: string;
|
|
618
|
+
host: string;
|
|
619
|
+
method: string;
|
|
620
|
+
pathWithQuery: string;
|
|
621
|
+
headers: Record<string, string>;
|
|
622
|
+
body: Uint8Array;
|
|
623
|
+
}): Promise<UpstreamResponse> {
|
|
624
|
+
return new Promise((resolve, reject) => {
|
|
625
|
+
const req = httpsRequest(
|
|
626
|
+
{
|
|
627
|
+
host: args.ip,
|
|
628
|
+
port: 443,
|
|
629
|
+
method: args.method,
|
|
630
|
+
path: args.pathWithQuery,
|
|
631
|
+
servername: args.host,
|
|
632
|
+
headers: { ...args.headers, host: args.host, "accept-encoding": "identity" },
|
|
633
|
+
},
|
|
634
|
+
(res) => {
|
|
635
|
+
const chunks: Buffer[] = [];
|
|
636
|
+
res.on("data", (c: Buffer) => chunks.push(c));
|
|
637
|
+
res.on("end", () => {
|
|
638
|
+
let bytes: Uint8Array = Buffer.concat(chunks);
|
|
639
|
+
const enc = String(res.headers["content-encoding"] ?? "").toLowerCase();
|
|
640
|
+
try {
|
|
641
|
+
if (enc.includes("br")) bytes = brotliDecompressSync(bytes);
|
|
642
|
+
else if (enc.includes("gzip")) bytes = gunzipSync(bytes);
|
|
643
|
+
else if (enc.includes("deflate")) bytes = inflateSync(bytes);
|
|
644
|
+
} catch {
|
|
645
|
+
// Leave the bytes as-is if decompression fails.
|
|
646
|
+
}
|
|
647
|
+
const headers: Record<string, string> = {};
|
|
648
|
+
for (const [k, v] of Object.entries(res.headers)) {
|
|
649
|
+
if (typeof v === "string") headers[k.toLowerCase()] = v;
|
|
650
|
+
else if (Array.isArray(v)) headers[k.toLowerCase()] = v.join(", ");
|
|
651
|
+
}
|
|
652
|
+
resolve({ status: res.statusCode ?? 0, headers, bytes });
|
|
653
|
+
});
|
|
654
|
+
res.on("error", reject);
|
|
655
|
+
},
|
|
656
|
+
);
|
|
657
|
+
req.on("error", reject);
|
|
658
|
+
if (args.body.length > 0) req.write(Buffer.from(args.body));
|
|
659
|
+
req.end();
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
664
|
+
// replayFake
|
|
665
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
666
|
+
|
|
667
|
+
export function replayFake(
|
|
668
|
+
opts: ReplayFakeOptions,
|
|
669
|
+
): FakeDefinition<CassetteState, ReplayHelpers> {
|
|
670
|
+
if (!opts.name) throw new Error("replayFake: `name` is required");
|
|
671
|
+
if (!opts.host || typeof opts.host !== "string") {
|
|
672
|
+
throw new Error(`replayFake(${opts.name}): "host" (the real hostname) is required`);
|
|
673
|
+
}
|
|
674
|
+
const host = opts.host.toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
|
|
675
|
+
const match = defaultMatch(opts.match);
|
|
676
|
+
const injectRules = opts.inject ?? [];
|
|
677
|
+
// Refs every header template references — the control plane resolves these
|
|
678
|
+
// server-side and pushes them eval-scoped (see the daemon's
|
|
679
|
+
// /record-secret-refs endpoint, which reads `def.secretRefs`).
|
|
680
|
+
const secretRefs = collectSecretRefs(injectRules, opts.sign);
|
|
681
|
+
|
|
682
|
+
const resolveMode = (): "record" | "replay" => {
|
|
683
|
+
if (opts.mode === "record") return "record";
|
|
684
|
+
if (opts.mode === "replay") return "replay";
|
|
685
|
+
return isRecording() ? "replay" : "record";
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
// ── REPLAY ──────────────────────────────────────────────────────────
|
|
689
|
+
function replay(reqLike: CassetteRequest, state: CassetteState): Response {
|
|
690
|
+
const sig = signature(reqLike, match);
|
|
691
|
+
const matches: CassetteInteraction[] = [];
|
|
692
|
+
for (const it of state.cassette.interactions) {
|
|
693
|
+
if (signature(it.request, match) === sig) matches.push(it);
|
|
694
|
+
}
|
|
695
|
+
const idx = state.cursor.get(sig) ?? 0;
|
|
696
|
+
const hit = matches[idx];
|
|
697
|
+
if (!hit) {
|
|
698
|
+
const body =
|
|
699
|
+
`replayFake(${opts.name}): no cassette interaction for ` +
|
|
700
|
+
`${reqLike.method} ${reqLike.path} (matched ${matches.length}, wanted #${idx + 1}). ` +
|
|
701
|
+
`Re-record the cassette, or relax \`match\`.\n`;
|
|
702
|
+
return new Response(body, {
|
|
703
|
+
status: 599,
|
|
704
|
+
headers: { "content-type": "text/plain" },
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
state.cursor.set(sig, idx + 1);
|
|
708
|
+
const headers = new Headers(hit.response.headers);
|
|
709
|
+
const payload =
|
|
710
|
+
hit.response.bodyEncoding === "base64"
|
|
711
|
+
? Buffer.from(hit.response.body, "base64")
|
|
712
|
+
: hit.response.body;
|
|
713
|
+
return new Response(payload, { status: hit.response.status, headers });
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// ── RECORD (MITM) ───────────────────────────────────────────────────
|
|
717
|
+
async function record(
|
|
718
|
+
req: Request,
|
|
719
|
+
url: URL,
|
|
720
|
+
reqLike: CassetteRequest,
|
|
721
|
+
bodyBytes: Uint8Array,
|
|
722
|
+
state: CassetteState,
|
|
723
|
+
): Promise<Response> {
|
|
724
|
+
// Credential brokering (static header inject): first matching rule wins.
|
|
725
|
+
// Resolve its `{{secret:REF}}` tokens from the eval-scoped store.
|
|
726
|
+
const rule = injectRules.find((r) =>
|
|
727
|
+
ruleMatches(r.match, {
|
|
728
|
+
method: reqLike.method,
|
|
729
|
+
path: reqLike.path,
|
|
730
|
+
query: url.searchParams,
|
|
731
|
+
headers: req.headers,
|
|
732
|
+
}),
|
|
733
|
+
);
|
|
734
|
+
const brokered = rule ? brokerHeaders(rule) : { headers: {}, secrets: [], missing: [] };
|
|
735
|
+
|
|
736
|
+
// SigV4 signing: resolve the credential secret refs (direct refs, not
|
|
737
|
+
// `{{secret:}}` templates). Missing required refs fail loud alongside any
|
|
738
|
+
// missing inject refs.
|
|
739
|
+
let signCreds: SigV4Credentials | undefined;
|
|
740
|
+
const signMissing: string[] = [];
|
|
741
|
+
if (opts.sign?.type === "awsSigv4") {
|
|
742
|
+
const s = opts.sign;
|
|
743
|
+
const accessKeyId = getRecordSecret(s.accessKeyId);
|
|
744
|
+
const secretAccessKey = getRecordSecret(s.secretAccessKey);
|
|
745
|
+
const sessionToken = s.sessionToken ? getRecordSecret(s.sessionToken) : undefined;
|
|
746
|
+
if (accessKeyId === undefined) signMissing.push(s.accessKeyId);
|
|
747
|
+
if (secretAccessKey === undefined) signMissing.push(s.secretAccessKey);
|
|
748
|
+
if (s.sessionToken && sessionToken === undefined) signMissing.push(s.sessionToken);
|
|
749
|
+
if (accessKeyId !== undefined && secretAccessKey !== undefined) {
|
|
750
|
+
signCreds = { accessKeyId, secretAccessKey, sessionToken };
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
const missing = [...brokered.missing, ...signMissing];
|
|
755
|
+
if (missing.length > 0) {
|
|
756
|
+
const refs = [...new Set(missing)];
|
|
757
|
+
return new Response(
|
|
758
|
+
`replayFake(${opts.name}): secret(s) ${JSON.stringify(refs)} were not supplied ` +
|
|
759
|
+
`(configure them on the project's Secrets page, and record via \`spectest env eval\`).\n`,
|
|
760
|
+
{ status: 599, headers: { "content-type": "text/plain" } },
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// Resolve the REAL host's IP via an external resolver so we don't loop
|
|
765
|
+
// back into the daemon (the in-VM resolver answers our own gateway for
|
|
766
|
+
// this faked name). See the module header.
|
|
767
|
+
const ips = await resolveExternalA(host);
|
|
768
|
+
if (ips.length === 0) {
|
|
769
|
+
return new Response(
|
|
770
|
+
`replayFake(${opts.name}): could not resolve real upstream ${JSON.stringify(host)} ` +
|
|
771
|
+
`via external DNS ${EXTERNAL_DNS} (is the VM online?).\n`,
|
|
772
|
+
{ status: 599, headers: { "content-type": "text/plain" } },
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// Forward headers: drop hop-by-hop/encoding, then SET the brokered
|
|
777
|
+
// headers — overwriting whatever the app sent (so the credential can't
|
|
778
|
+
// be smuggled or spoofed by app code). The real values only ever appear
|
|
779
|
+
// on this outbound wire.
|
|
780
|
+
const fwdHeaders: Record<string, string> = {};
|
|
781
|
+
req.headers.forEach((v, k) => {
|
|
782
|
+
if (!STRIP_FORWARD_HEADERS.has(k.toLowerCase())) fwdHeaders[k.toLowerCase()] = v;
|
|
783
|
+
});
|
|
784
|
+
for (const [k, v] of Object.entries(brokered.headers)) fwdHeaders[k] = v;
|
|
785
|
+
|
|
786
|
+
// SigV4 re-signing: strip the app's dummy signature and re-sign the exact
|
|
787
|
+
// outbound request (method/path/query/signed-headers/body-hash) with the
|
|
788
|
+
// brokered credentials, so `authorization`/`x-amz-date`/`x-amz-content-sha256`
|
|
789
|
+
// are internally consistent.
|
|
790
|
+
const signSecrets: ResolvedSecret[] = [];
|
|
791
|
+
let wireQuery = url.searchParams.toString();
|
|
792
|
+
if (opts.sign?.type === "awsSigv4" && signCreds) {
|
|
793
|
+
const scope = inferSigV4Scope({
|
|
794
|
+
authorization: req.headers.get("authorization"),
|
|
795
|
+
credentialParam: url.searchParams.get("X-Amz-Credential"),
|
|
796
|
+
host,
|
|
797
|
+
});
|
|
798
|
+
if (!scope) {
|
|
799
|
+
return new Response(
|
|
800
|
+
`replayFake(${opts.name}): could not infer the AWS region/service to sign ` +
|
|
801
|
+
`${reqLike.method} ${reqLike.path} (no SigV4 Credential on the request, and host ` +
|
|
802
|
+
`${JSON.stringify(host)} is not a <service>.<region>.amazonaws.com name).\n`,
|
|
803
|
+
{ status: 599, headers: { "content-type": "text/plain" } },
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
// Drop the app's own (dummy-signed) signing headers before re-signing.
|
|
807
|
+
for (const h of ["authorization", "x-amz-date", "x-amz-content-sha256", "x-amz-security-token"]) {
|
|
808
|
+
delete fwdHeaders[h];
|
|
809
|
+
}
|
|
810
|
+
// Fold the app's remaining `x-amz-*`/content-type headers (e.g.
|
|
811
|
+
// `x-amz-target`) into the signature; they stay on the outbound wire.
|
|
812
|
+
const additionalHeaders: Record<string, string> = {};
|
|
813
|
+
for (const [k, v] of Object.entries(fwdHeaders)) {
|
|
814
|
+
if (
|
|
815
|
+
k === "content-type" ||
|
|
816
|
+
(k.startsWith("x-amz-") &&
|
|
817
|
+
k !== "x-amz-date" &&
|
|
818
|
+
k !== "x-amz-content-sha256" &&
|
|
819
|
+
k !== "x-amz-security-token")
|
|
820
|
+
) {
|
|
821
|
+
additionalHeaders[k] = v;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
const forwardParams = stripAmzParams(url.searchParams);
|
|
825
|
+
const signed = signAwsV4Request({
|
|
826
|
+
method: reqLike.method,
|
|
827
|
+
path: reqLike.path,
|
|
828
|
+
query: forwardParams,
|
|
829
|
+
host,
|
|
830
|
+
body: bodyBytes,
|
|
831
|
+
credentials: signCreds,
|
|
832
|
+
scope,
|
|
833
|
+
additionalHeaders,
|
|
834
|
+
});
|
|
835
|
+
for (const [k, v] of Object.entries(signed.headers)) fwdHeaders[k] = v;
|
|
836
|
+
// Send the canonical query we signed (URLSearchParams' `+`-for-space
|
|
837
|
+
// encoding would diverge from the signed `%20`).
|
|
838
|
+
wireQuery = signed.canonicalQuery;
|
|
839
|
+
signSecrets.push(
|
|
840
|
+
{ ref: opts.sign.accessKeyId, value: signCreds.accessKeyId },
|
|
841
|
+
{ ref: opts.sign.secretAccessKey, value: signCreds.secretAccessKey },
|
|
842
|
+
);
|
|
843
|
+
if (signCreds.sessionToken && opts.sign.sessionToken) {
|
|
844
|
+
signSecrets.push({ ref: opts.sign.sessionToken, value: signCreds.sessionToken });
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
const pathWithQuery = reqLike.path + (wireQuery ? `?${wireQuery}` : "");
|
|
849
|
+
|
|
850
|
+
let upstream: UpstreamResponse;
|
|
851
|
+
try {
|
|
852
|
+
upstream = await forwardToRealUpstream({
|
|
853
|
+
ip: ips[0],
|
|
854
|
+
host,
|
|
855
|
+
method: reqLike.method,
|
|
856
|
+
pathWithQuery,
|
|
857
|
+
headers: fwdHeaders,
|
|
858
|
+
body: bodyBytes,
|
|
859
|
+
});
|
|
860
|
+
} catch (err) {
|
|
861
|
+
return new Response(
|
|
862
|
+
`replayFake(${opts.name}): forward to real ${host} (${ips[0]}) failed: ${(err as Error).message}\n`,
|
|
863
|
+
{ status: 599, headers: { "content-type": "text/plain" } },
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// Decode + redact for storage; return the real (un-redacted) bytes to
|
|
868
|
+
// the app so the manual session behaves like production.
|
|
869
|
+
const redactSecrets = [...brokered.secrets, ...signSecrets];
|
|
870
|
+
const redact = makeRedactor(redactSecrets, opts.redactPatterns);
|
|
871
|
+
const decoded = decodeBody(upstream.bytes);
|
|
872
|
+
const respHeaders: Record<string, string> = {};
|
|
873
|
+
for (const [k, v] of Object.entries(upstream.headers)) {
|
|
874
|
+
if (SENSITIVE_HEADERS.has(k) || STRIP_FORWARD_HEADERS.has(k)) continue;
|
|
875
|
+
respHeaders[k] = v;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
const redactedQuery: Record<string, string[]> = {};
|
|
879
|
+
for (const [k, vs] of Object.entries(reqLike.query)) {
|
|
880
|
+
redactedQuery[k] = vs.map(redact);
|
|
881
|
+
}
|
|
882
|
+
const interaction: CassetteInteraction = {
|
|
883
|
+
request: {
|
|
884
|
+
method: reqLike.method,
|
|
885
|
+
path: reqLike.path,
|
|
886
|
+
query: redactedQuery,
|
|
887
|
+
headers: reqLike.headers,
|
|
888
|
+
...(reqLike.body !== undefined
|
|
889
|
+
? {
|
|
890
|
+
bodyHash: reqLike.bodyHash,
|
|
891
|
+
// Redact text bodies; leave base64 (binary) bodies verbatim — a
|
|
892
|
+
// secret is vanishingly unlikely to survive base64, and the
|
|
893
|
+
// fail-closed check below still catches it if it does.
|
|
894
|
+
body: reqLike.bodyEncoding === "base64" ? reqLike.body : redact(reqLike.body),
|
|
895
|
+
bodyEncoding: reqLike.bodyEncoding,
|
|
896
|
+
}
|
|
897
|
+
: {}),
|
|
898
|
+
},
|
|
899
|
+
response: {
|
|
900
|
+
status: upstream.status,
|
|
901
|
+
headers: respHeaders,
|
|
902
|
+
body: decoded.bodyEncoding === "utf8" ? redact(decoded.body) : decoded.body,
|
|
903
|
+
bodyEncoding: decoded.bodyEncoding,
|
|
904
|
+
},
|
|
905
|
+
};
|
|
906
|
+
|
|
907
|
+
// Fail-closed: never persist a cassette that still carries any raw
|
|
908
|
+
// secret value (a missed redaction is a leak, not a warning).
|
|
909
|
+
const serialized = JSON.stringify(interaction);
|
|
910
|
+
for (const { ref, value } of redactSecrets) {
|
|
911
|
+
if (value.length > 0 && serialized.includes(value)) {
|
|
912
|
+
throw new Error(
|
|
913
|
+
`replayFake(${opts.name}): refusing to record — the value for secret ${JSON.stringify(ref)} ` +
|
|
914
|
+
`survived redaction into the interaction for ${reqLike.method} ${reqLike.path}. ` +
|
|
915
|
+
`Add a redactPatterns entry.`,
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
state.recorded.push(interaction);
|
|
921
|
+
state.dirty = true;
|
|
922
|
+
|
|
923
|
+
return new Response(upstream.bytes as unknown as BodyInit, {
|
|
924
|
+
status: upstream.status,
|
|
925
|
+
headers: new Headers(respHeaders),
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// ── handler ─────────────────────────────────────────────────────────
|
|
930
|
+
const handler = async (
|
|
931
|
+
req: Request,
|
|
932
|
+
state: CassetteState,
|
|
933
|
+
_ctx: FakeContext,
|
|
934
|
+
): Promise<Response> => {
|
|
935
|
+
const url = new URL(req.url);
|
|
936
|
+
const bodyBytes =
|
|
937
|
+
req.method === "GET" || req.method === "HEAD"
|
|
938
|
+
? new Uint8Array(0)
|
|
939
|
+
: new Uint8Array(await req.arrayBuffer());
|
|
940
|
+
const decodedBody = bodyBytes.length > 0 ? decodeBody(bodyBytes) : undefined;
|
|
941
|
+
const reqLike: CassetteRequest = {
|
|
942
|
+
method: req.method.toUpperCase(),
|
|
943
|
+
path: url.pathname,
|
|
944
|
+
// Strip SigV4 `x-amz-*` query params from the match key when signing —
|
|
945
|
+
// presigned URLs carry a per-request signature there.
|
|
946
|
+
query: normalizeQuery(url.searchParams, opts.sign !== undefined),
|
|
947
|
+
headers: recordable(req.headers, ["content-type", ...(match.headers ?? [])]),
|
|
948
|
+
...(decodedBody
|
|
949
|
+
? {
|
|
950
|
+
bodyHash: sha256Bytes(bodyBytes),
|
|
951
|
+
body: decodedBody.body,
|
|
952
|
+
bodyEncoding: decodedBody.bodyEncoding,
|
|
953
|
+
}
|
|
954
|
+
: {}),
|
|
955
|
+
};
|
|
956
|
+
|
|
957
|
+
if (resolveMode() === "replay") return replay(reqLike, state);
|
|
958
|
+
return record(req, url, reqLike, bodyBytes, state);
|
|
959
|
+
};
|
|
960
|
+
|
|
961
|
+
const def: FakeDefinition<CassetteState, ReplayHelpers> = {
|
|
962
|
+
name: opts.name,
|
|
963
|
+
// Fake = real: we answer for the real host on :80 and :443.
|
|
964
|
+
hostnames: [host],
|
|
965
|
+
secretRefs,
|
|
966
|
+
// Cassettes are NOT auto-loaded — a fork starts with an empty replay
|
|
967
|
+
// set, so a test that loads nothing fails loud (599). Tests call
|
|
968
|
+
// `replay(...)` to populate it.
|
|
969
|
+
state: (): CassetteState => ({
|
|
970
|
+
cassette: emptyCassette(opts.name, host),
|
|
971
|
+
cursor: new Map(),
|
|
972
|
+
recorded: [],
|
|
973
|
+
dirty: false,
|
|
974
|
+
}),
|
|
975
|
+
handler,
|
|
976
|
+
helpers: ({ state }): ReplayHelpers => ({
|
|
977
|
+
replay(file: string | Cassette): ReplaySummary {
|
|
978
|
+
let loaded: Cassette;
|
|
979
|
+
let label: string;
|
|
980
|
+
if (file && typeof file === "object") {
|
|
981
|
+
loaded = coerceCassette(file, opts.name, host);
|
|
982
|
+
label = file.fake || "(inline)";
|
|
983
|
+
} else if (typeof file === "string" && file.length > 0) {
|
|
984
|
+
label = file;
|
|
985
|
+
loaded = readCassetteFile(opts.name, file, host);
|
|
986
|
+
} else {
|
|
987
|
+
throw new Error(
|
|
988
|
+
`replayFake(${opts.name}): replay(...) needs a cassette path under spectest/tests/ ` +
|
|
989
|
+
`(e.g. "recordings/${opts.name}.json").`,
|
|
990
|
+
);
|
|
991
|
+
}
|
|
992
|
+
// Mutate the live state object (the handler reads the same
|
|
993
|
+
// reference); reset the cursor so replay starts from the top.
|
|
994
|
+
state.cassette = loaded;
|
|
995
|
+
state.cursor = new Map();
|
|
996
|
+
return { cassette: label, host: loaded.host, interactions: loaded.interactions.length };
|
|
997
|
+
},
|
|
998
|
+
dump(): Cassette {
|
|
999
|
+
return {
|
|
1000
|
+
version: 1,
|
|
1001
|
+
fake: opts.name,
|
|
1002
|
+
host,
|
|
1003
|
+
interactions: [...state.cassette.interactions, ...state.recorded],
|
|
1004
|
+
};
|
|
1005
|
+
},
|
|
1006
|
+
recorded(): CassetteInteraction[] {
|
|
1007
|
+
return state.recorded.slice();
|
|
1008
|
+
},
|
|
1009
|
+
count(): number {
|
|
1010
|
+
return state.recorded.length;
|
|
1011
|
+
},
|
|
1012
|
+
}),
|
|
1013
|
+
};
|
|
1014
|
+
return def;
|
|
1015
|
+
}
|