-
Notifications
You must be signed in to change notification settings - Fork 553
/
client.spec.ts
351 lines (314 loc) · 10.7 KB
/
client.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import assert from "assert";
import { Blob } from "buffer";
import http from "http";
import { text } from "stream/consumers";
import { ReadableStream, WritableStream } from "stream/web";
import util from "util";
import type { Fetcher } from "@cloudflare/workers-types/experimental";
import test, { ThrowsExpectation } from "ava";
import {
DeferredPromise,
File,
MessageEvent,
Miniflare,
ReplaceWorkersTypes,
Response,
WebSocketPair,
fetch,
} from "miniflare";
// This file tests API proxy edge cases. Cache, D1, Durable Object and R2 tests
// make extensive use of the API proxy, testing their specific special cases.
const nullScript =
'addEventListener("fetch", (event) => event.respondWith(new Response(null, { status: 404 })));';
test("ProxyClient: supports service bindings with WebSockets", async (t) => {
const mf = new Miniflare({
script: nullScript,
serviceBindings: {
CUSTOM() {
const { 0: webSocket1, 1: webSocket2 } = new WebSocketPair();
webSocket1.accept();
webSocket1.addEventListener("message", (event) => {
webSocket1.send(`echo:${event.data}`);
});
return new Response(null, { status: 101, webSocket: webSocket2 });
},
},
});
t.teardown(() => mf.dispose());
const { CUSTOM } = await mf.getBindings<{
CUSTOM: ReplaceWorkersTypes<Fetcher>;
}>();
const res = await CUSTOM.fetch("http://placeholder/", {
headers: { Upgrade: "websocket" },
});
assert(res.webSocket !== null);
const eventPromise = new DeferredPromise<MessageEvent>();
res.webSocket.addEventListener("message", eventPromise.resolve);
res.webSocket.accept();
res.webSocket.send("hello");
const event = await eventPromise;
t.is(event.data, "echo:hello");
});
test("ProxyClient: supports serialising multiple ReadableStreams, Blobs and Files", async (t) => {
// For testing proxy client serialisation, add an API that just returns its
// arguments. Note without the `.pipeThrough(new TransformStream())` below,
// we'll see `TypeError: Inter-TransformStream ReadableStream.pipeTo() is
// not implemented.`. `IdentityTransformStream` doesn't work here.
const mf = new Miniflare({
workers: [
{
name: "entry",
modules: true,
script: "",
wrappedBindings: { IDENTITY: "identity" },
},
{
name: "identity",
modules: true,
script: `
class Identity {
async asyncIdentity(...args) {
const i = args.findIndex((arg) => arg instanceof ReadableStream);
if (i !== -1) args[i] = args[i].pipeThrough(new TransformStream());
return args;
}
}
export default function() { return new Identity(); }
`,
},
],
});
t.teardown(() => mf.dispose());
const client = await mf._getProxyClient();
const IDENTITY = client.env["MINIFLARE_PROXY:core:entry:IDENTITY"] as {
asyncIdentity<Args extends any[]>(...args: Args): Promise<Args>;
};
// Test serialising multiple ReadableStreams
const streamResult = await IDENTITY.asyncIdentity(
new Blob(["hello"]).stream(),
new Blob(["abc"]).stream(),
new Blob(["123"]).stream()
);
const streamTexts = await Promise.all(streamResult.map(text));
t.deepEqual(streamTexts, ["hello", "abc", "123"]);
// Test serialising single Blob
const [blobResult] = await IDENTITY.asyncIdentity(
new Blob(["xyz"], { type: "text/plain" })
);
t.is(blobResult.type, "text/plain");
t.is(await blobResult.text(), "xyz");
// Test serialising ReadableStream, Blob and File
const allResult = await IDENTITY.asyncIdentity(
new Blob(["no type"]),
new Blob(["stream"]).stream(),
new File(["text file"], "text.txt", {
type: "text/plain",
lastModified: 1000,
})
);
t.false(allResult[0] instanceof File);
t.true(allResult[0] instanceof Blob);
t.is(await allResult[0].text(), "no type");
t.true(allResult[1] instanceof ReadableStream);
t.is(await text(allResult[1]), "stream");
t.true(allResult[2] instanceof File);
t.is(allResult[2].type, "text/plain");
t.is(allResult[2].lastModified, 1000);
t.is(await allResult[2].text(), "text file");
});
test("ProxyClient: poisons dependent proxies after setOptions()/dispose()", async (t) => {
const mf = new Miniflare({ script: nullScript });
let disposed = false;
t.teardown(() => {
if (!disposed) return mf.dispose();
});
let caches = await mf.getCaches();
let defaultCache = caches.default;
let namedCache = await caches.open("name");
const key = "http://localhost";
await defaultCache.match(key);
await mf.setOptions({ script: nullScript });
const expectations: ThrowsExpectation<Error> = {
message:
"Attempted to use poisoned stub. Stubs to runtime objects must be re-created after calling `Miniflare#setOptions()` or `Miniflare#dispose()`.",
};
t.throws(() => caches.default, expectations);
t.throws(() => defaultCache.match(key), expectations);
t.throws(() => namedCache.match(key), expectations);
caches = await mf.getCaches();
defaultCache = caches.default;
namedCache = await caches.open("name");
await defaultCache.match(key);
await mf.dispose();
disposed = true;
t.throws(() => caches.default, expectations);
t.throws(() => defaultCache.match(key), expectations);
t.throws(() => namedCache.match(key), expectations);
});
test("ProxyClient: logging proxies provides useful information", async (t) => {
const mf = new Miniflare({ script: nullScript });
t.teardown(() => mf.dispose());
const caches = await mf.getCaches();
const inspectOpts: util.InspectOptions = { colors: false };
t.is(
util.inspect(caches, inspectOpts),
"ProxyStub { name: 'CacheStorage', poisoned: false }"
);
t.is(util.inspect(caches.open, inspectOpts), "[Function: open]");
});
test("ProxyClient: stack traces don't include internal implementation", async (t) => {
function hasStack(value: unknown): value is { stack: string } {
return (
typeof value === "object" &&
value !== null &&
"stack" in value &&
typeof value.stack === "string"
);
}
const mf = new Miniflare({
modules: true,
script: `export class DurableObject {}
export default {
fetch() { return new Response(null, { status: 404 }); }
}`,
durableObjects: { OBJECT: "DurableObject" },
// Make sure asynchronous functions are rejecting, not throwing:
// https://developers.cloudflare.com/workers/configuration/compatibility-dates/#do-not-throw-from-async-functions
compatibilityFlags: ["capture_async_api_throws"],
});
t.teardown(() => mf.dispose());
const ns = await mf.getDurableObjectNamespace("OBJECT");
const caches = await mf.getCaches();
function syncUserFunction() {
try {
ns.idFromString("bad id");
} catch (e) {
assert(hasStack(e));
t.regex(e.stack, /syncUserFunction/);
t.notRegex(e.stack, /ProxyStubHandler/);
}
}
syncUserFunction();
async function asyncUserFunction() {
try {
await caches.default.match("bad url");
t.fail();
} catch (e) {
assert(hasStack(e));
t.regex(e.stack, /asyncUserFunction/);
t.notRegex(e.stack, /ProxyStubHandler/);
}
}
await asyncUserFunction();
});
test("ProxyClient: can access ReadableStream property multiple times", async (t) => {
const mf = new Miniflare({ script: nullScript, r2Buckets: ["BUCKET"] });
t.teardown(() => mf.dispose());
const bucket = await mf.getR2Bucket("BUCKET");
await bucket.put("key", "value");
const objectBody = await bucket.get("key");
assert(objectBody != null);
t.not(objectBody.body, null); // 1st access
t.is(await text(objectBody.body), "value"); // 2nd access
});
test("ProxyClient: returns empty ReadableStream synchronously", async (t) => {
const mf = new Miniflare({ script: nullScript, r2Buckets: ["BUCKET"] });
t.teardown(() => mf.dispose());
const bucket = await mf.getR2Bucket("BUCKET");
await bucket.put("key", "");
const objectBody = await bucket.get("key");
assert(objectBody != null);
t.is(await text(objectBody.body), ""); // Synchronous empty stream access
});
test("ProxyClient: returns multiple ReadableStreams in parallel", async (t) => {
const mf = new Miniflare({ script: nullScript, r2Buckets: ["BUCKET"] });
t.teardown(() => mf.dispose());
const logs: string[] = [];
const bucket = await mf.getR2Bucket("BUCKET");
const str = new Array(500000)
.fill(null)
.map(() => "test")
.join("");
const objectKeys = ["obj-1", "obj-2", "obj-3"];
for (const objectKey of objectKeys) {
await bucket.put(objectKey, str);
}
await Promise.all(
objectKeys.map((objectKey) =>
bucket.get(objectKey).then((obj) => readStream(objectKey, obj?.body))
)
);
async function readStream(objectKey: string, stream?: ReadableStream) {
logs.push(`[${objectKey}] stream start`);
if (!stream) return;
await stream.pipeTo(
new WritableStream({
write(_chunk) {
logs.push(`[${objectKey}] stream chunk`);
},
close() {
logs.push(`[${objectKey}] stream close`);
},
})
);
logs.push(`[${objectKey}] stream end`);
}
for (const objectKey of objectKeys) {
t.is(logs.includes(`[${objectKey}] stream start`), true);
t.is(logs.includes(`[${objectKey}] stream chunk`), true);
t.is(logs.includes(`[${objectKey}] stream close`), true);
t.is(logs.includes(`[${objectKey}] stream end`), true);
}
});
test("ProxyClient: can `JSON.stringify()` proxies", async (t) => {
const mf = new Miniflare({ script: nullScript, r2Buckets: ["BUCKET"] });
t.teardown(() => mf.dispose());
const bucket = await mf.getR2Bucket("BUCKET");
const object = await bucket.put("key", "value");
assert(object !== null);
t.is(Object.getPrototypeOf(object), null);
const plainObject = JSON.parse(JSON.stringify(object));
t.deepEqual(plainObject, {
checksums: {
md5: "2063c1608d6e0baf80249c42e2be5804",
},
customMetadata: {},
etag: "2063c1608d6e0baf80249c42e2be5804",
httpEtag: '"2063c1608d6e0baf80249c42e2be5804"',
httpMetadata: {},
key: "key",
size: 5,
uploaded: object.uploaded.toISOString(),
version: object.version,
});
});
test("ProxyServer: prevents unauthorised access", async (t) => {
const mf = new Miniflare({ script: nullScript });
t.teardown(() => mf.dispose());
const url = await mf.ready;
// Check validates `Host` header
const statusPromise = new DeferredPromise<number>();
const req = http.get(
url,
{ setHost: false, headers: { "MF-Op": "GET", Host: "localhost" } },
(res) => statusPromise.resolve(res.statusCode ?? 0)
);
req.on("error", (error) => statusPromise.reject(error));
t.is(await statusPromise, 401);
// Check validates `MF-Op-Secret` header
let res = await fetch(url, {
headers: { "MF-Op": "GET" }, // (missing)
});
t.is(res.status, 401);
await res.arrayBuffer(); // (drain)
res = await fetch(url, {
headers: { "MF-Op": "GET", "MF-Op-Secret": "aaaa" }, // (too short)
});
t.is(res.status, 401);
await res.arrayBuffer(); // (drain)
res = await fetch(url, {
headers: { "MF-Op": "GET", "MF-Op-Secret": "a".repeat(32) }, // (wrong)
});
t.is(res.status, 401);
await res.arrayBuffer(); // (drain)
});