Repository navigation
Expand file tree
/
Copy pathHttpFetchTest.cpp
More file actions
565 lines (505 loc) · 20.9 KB
/
Copy pathHttpFetchTest.cpp
File metadata and controls
565 lines (505 loc) · 20.9 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include "FakePlatform.h"
#include "http/Internal.h"
#include "ns/http/ModuleFetch.h"
using namespace nativescript::common::http;
using fake_platform::Ok;
using fake_platform::Transport;
using std::chrono::milliseconds;
using std::chrono::steady_clock;
namespace {
int failures = 0;
void Check(bool ok, const char* what, const std::string& detail = "") {
if (!ok) {
failures++;
std::fprintf(stderr, "FAIL %s: \"%s\"\n", what, detail.c_str());
}
}
void ExpectEqual(const std::string& actual, const std::string& expected,
const char* what) {
if (actual != expected) {
failures++;
std::fprintf(stderr, "FAIL %s:\n actual: \"%s\"\n expected: \"%s\"\n",
what, actual.c_str(), expected.c_str());
}
}
HttpLoaderConfig DebugConfig() {
HttpLoaderConfig config;
config.isDebug = true;
return config;
}
HttpLoaderConfig ReleaseConfig(
bool allowRemoteModules,
std::optional<std::vector<std::optional<std::string>>> allowlist =
std::nullopt) {
HttpLoaderConfig config;
config.allowRemoteModules = allowRemoteModules;
config.remoteModuleAllowlist = std::move(allowlist);
return config;
}
// Fresh loader state, fake transport and timing scaled down so retries and
// waits take milliseconds.
void Start(const HttpLoaderConfig& config) {
fake_platform::SetConfig(config);
testing::Reset();
testing::Timing timing;
timing.retryDelay = milliseconds(20);
testing::SetTiming(timing);
Transport().Reset();
fake_platform::ClearMessages();
}
AttemptOutcome TransportError() {
AttemptOutcome outcome;
outcome.errorDescription = "connection refused";
return outcome;
}
// The result of an async fetch, and how many times its completion ran.
struct AsyncResult {
ModuleFetchResult result;
int completions = 0;
};
AsyncResult FetchAsync(const std::string& url,
ModuleFetchDeadline deadline = std::nullopt) {
struct Shared {
std::mutex mutex;
std::condition_variable cv;
AsyncResult value;
};
auto shared = std::make_shared<Shared>();
FetchModuleBodyAsync(url, deadline, [shared](ModuleFetchResult result) {
std::lock_guard<std::mutex> lock(shared->mutex);
shared->value.result = std::move(result);
shared->value.completions++;
shared->cv.notify_all();
});
std::unique_lock<std::mutex> lock(shared->mutex);
shared->cv.wait_for(lock, std::chrono::seconds(10),
[&] { return shared->value.completions > 0; });
lock.unlock();
// A second completion would land within this window.
std::this_thread::sleep_for(milliseconds(50));
lock.lock();
return shared->value;
}
bool HasHeader(const AttemptRequest& request, const std::string& name,
const std::string& value) {
return std::any_of(request.headers.begin(), request.headers.end(),
[&](const RequestHeader& header) {
return header.name == name && header.value == value;
});
}
bool HasHeaderNamed(const AttemptRequest& request, const std::string& name) {
return std::any_of(
request.headers.begin(), request.headers.end(),
[&](const RequestHeader& header) { return header.name == name; });
}
// ── Gate ────────────────────────────────────────────────────────────────────
void TestGateRelease() {
Start(ReleaseConfig(false));
Check(!IsRemoteModulesAllowed(), "release default-denies remote modules");
ModuleFetchResult result;
Check(!HttpFetchModule("https://cdn.example.com/a.js", result),
"release blocks sync");
Check(result.status == 403, "blocked is 403");
ExpectEqual(result.failureReason,
"HTTP import blocked: remote module loading is not allowed for "
"https://cdn.example.com/a.js",
"blocked text");
AsyncResult async = FetchAsync("https://cdn.example.com/a.js");
Check(async.completions == 1 && async.result.status == 403,
"release blocks async");
Check(Transport().Requests().empty(), "blocked fetches never reach the net");
Start(ReleaseConfig(true));
Check(IsRemoteModulesAllowed(), "allowRemoteModules enables");
Check(HttpFetchModule("https://any.example/a.js", result),
"no allowlist allows any URL", result.failureReason);
Start(ReleaseConfig(true, std::vector<std::optional<std::string>>{
std::string("https://cdn.example.com")}));
Check(IsRemoteUrlAllowed("https://cdn.example.com/a.js"), "listed allowed");
Check(!IsRemoteUrlAllowed("https://cdn.example.com.evil/a.js"),
"lookalike refused");
Check(!HttpFetchModule("https://other.example/a.js", result) &&
result.status == 403,
"unlisted blocked");
Check(HttpFetchModule("https://cdn.example.com/a.js", result),
"listed fetched", result.failureReason);
Start(DebugConfig());
Check(IsRemoteUrlAllowed("https://anything.example/a.js"),
"debug always allows");
}
void TestRedirectGate() {
const auto allowlisted =
ReleaseConfig(true, std::vector<std::optional<std::string>>{
std::string("https://cdn.example.com")});
ModuleFetchResult result;
Start(allowlisted);
Transport().SetResponder([](const AttemptRequest&) {
return Ok("https://evil.example/x.js", "export {}");
});
Check(!HttpFetchModule("https://cdn.example.com/a.js", result),
"redirect off the allowlist is blocked");
Check(result.status == 403, "redirect block is 403");
ExpectEqual(result.failureReason,
"HTTP import blocked: remote module loading is not allowed for "
"https://evil.example/x.js (redirected from "
"https://cdn.example.com/a.js)",
"redirect block text");
AsyncResult async = FetchAsync("https://cdn.example.com/a.js");
Check(!async.result.ok && async.result.status == 403,
"async redirect off the allowlist is blocked");
Transport().SetResponder(
[](const AttemptRequest&) { return Ok("", "export {}"); });
Check(!HttpFetchModule("https://cdn.example.com/a.js", result),
"unreported final URL fails closed");
const auto logged = fake_platform::LoggedMessages();
Check(logged.size() == 1 &&
logged[0].find("did not report the final URL") != std::string::npos,
"an unreported final URL is logged once");
HttpFetchModule("https://cdn.example.com/a.js", result);
Check(fake_platform::LoggedMessages().size() == 1, "logged only once");
Transport().SetResponder([](const AttemptRequest&) {
return Ok("https://CDN.example.com/b.js", "export {}");
});
Check(HttpFetchModule("https://cdn.example.com/a.js", result),
"redirect within the allowlist is allowed", result.failureReason);
Start(DebugConfig());
Transport().SetResponder([](const AttemptRequest&) {
return Ok("https://evil.example/x.js", "export {}");
});
Check(HttpFetchModule("https://cdn.example.com/a.js", result),
"debug follows any redirect", result.failureReason);
Start(ReleaseConfig(true));
Transport().SetResponder(
[](const AttemptRequest&) { return Ok("", "export {}"); });
Check(HttpFetchModule("https://cdn.example.com/a.js", result),
"no allowlist needs no final URL", result.failureReason);
}
// ── Requests ────────────────────────────────────────────────────────────────
void TestRequestShape() {
Start(DebugConfig());
ModuleFetchResult result;
HttpFetchModule("http://localhost:5173/a.js", result);
FetchAsync("http://localhost:5173/b.js");
std::vector<AttemptRequest> requests = Transport().Requests();
Check(requests.size() == 2, "one attempt each");
for (const AttemptRequest& request : requests) {
Check(HasHeader(request, "Accept",
"application/javascript, text/javascript, */*;q=0.1"),
"Accept", request.url);
Check(HasHeader(request, "Accept-Encoding", "identity"), "Accept-Encoding",
request.url);
Check(HasHeader(request, "User-Agent", "NativeScript-HTTP-ESM"),
"User-Agent", request.url);
Check(!HasHeaderNamed(request, "Cache-Control") &&
!HasHeaderNamed(request, "Pragma"),
"no no-cache pair while cached", request.url);
Check(request.useCache, "cached", request.url);
Check(request.timeout == milliseconds(30000), "debug timeout", request.url);
}
Check(requests[0].path == FetchPath::kSynchronousFallback &&
requests[0].waitBound == milliseconds(35000),
"sync path waits timeout + margin");
Check(requests[1].path == FetchPath::kGraphWalk, "async path");
Start(ReleaseConfig(true));
SetModuleHttpCacheEnabled(false);
HttpFetchModule("https://cdn.example.com/a.js", result);
requests = Transport().Requests();
Check(requests.size() == 1 && requests[0].timeout == milliseconds(5000),
"release timeout");
Check(!requests[0].useCache &&
HasHeader(requests[0], "Cache-Control", "no-cache") &&
HasHeader(requests[0], "Pragma", "no-cache"),
"uncached carries the no-cache pair");
}
// ── Synchronous retry ───────────────────────────────────────────────────────
void TestSyncRetry() {
Start(DebugConfig());
ModuleFetchResult result;
std::atomic<int> calls{0};
Transport().SetResponder([&](const AttemptRequest& request) {
return calls++ == 0 ? TransportError() : Ok(request.url, "export {}");
});
Check(HttpFetchModule("http://h/a.js", result), "transport error retried",
result.failureReason);
Check(calls == 2, "one retry");
calls = 0;
Transport().SetResponder([&](const AttemptRequest&) {
calls++;
return TransportError();
});
Check(!HttpFetchModule("http://h/a.js", result), "second error fails");
Check(calls == 2, "only one retry");
ExpectEqual(result.failureReason,
"HTTP import failed: http://h/a.js (network error)",
"network error text");
calls = 0;
Transport().SetResponder([&](const AttemptRequest& request) {
calls++;
AttemptOutcome outcome = Ok(request.url, "");
outcome.status = 500;
return outcome;
});
Check(!HttpFetchModule("http://h/a.js", result) && calls == 1,
"an HTTP status is not retried");
calls = 0;
Transport().SetResponder([&](const AttemptRequest&) {
calls++;
AttemptOutcome outcome;
outcome.waitExpired = true;
return outcome;
});
Check(!HttpFetchModule("http://h/a.js", result) && calls == 1,
"an expired wait is not retried");
ExpectEqual(result.failureReason,
"HTTP import failed: http://h/a.js (no response within 35s)",
"expired wait text");
const auto logged = fake_platform::LoggedMessages();
Check(!logged.empty() &&
logged.back() ==
"NativeScript: synchronous module fetch of http://h/a.js got "
"no response within 35s",
"expired wait is logged");
calls = 0;
Transport().SetResponder([&](const AttemptRequest&) {
calls++;
AttemptOutcome outcome;
outcome.malformedUrl = true;
return outcome;
});
Check(!HttpFetchModule("http://h/a.js", result) && calls == 1,
"a malformed URL is not retried");
ExpectEqual(result.failureReason,
"HTTP import failed: http://h/a.js (malformed request URL)",
"malformed text");
calls = 0;
Transport().SetResponder(
[&](const AttemptRequest& request) -> AttemptOutcome {
if (calls++ == 0) {
throw std::runtime_error("jni");
}
return Ok(request.url, "export {}");
});
Check(HttpFetchModule("http://h/a.js", result) && calls == 2,
"a throwing transport is a retried transport error",
result.failureReason);
}
// ── Asynchronous fetches, both scheduling modes ─────────────────────────────
void TestAsync(bool schedulesItself) {
const char* mode = schedulesItself ? "self-scheduled" : "lanes";
Start(DebugConfig());
Transport().schedulesItself = schedulesItself;
AsyncResult r = FetchAsync("http://h/a.js");
Check(r.completions == 1 && r.result.ok && r.result.body == "export {}",
"async fetch", mode);
std::atomic<int> calls{0};
Transport().SetResponder([&](const AttemptRequest& request) {
return calls++ == 0 ? TransportError() : Ok(request.url, "export {}");
});
r = FetchAsync("http://h/a.js");
Check(r.completions == 1 && r.result.ok && calls == 2,
"async retries a transport error once", mode);
Check(Transport().postDelayedCalls == (schedulesItself ? 1 : 0),
"a self-scheduling transport times the retry delay", mode);
calls = 0;
Transport().SetResponder([&](const AttemptRequest&) {
calls++;
return TransportError();
});
r = FetchAsync("http://h/a.js");
Check(r.completions == 1 && !r.result.ok && calls == 2,
"async gives up after one retry", mode);
ExpectEqual(r.result.failureReason,
"HTTP import failed: http://h/a.js (network error)", mode);
calls = 0;
r = FetchAsync("http://h/a.js", steady_clock::now() - milliseconds(1));
Check(r.completions == 1 && calls == 0, "no attempt past the deadline", mode);
ExpectEqual(r.result.failureReason,
"HTTP import failed: http://h/a.js (module graph fetch deadline "
"exceeded)",
mode);
// A budget shorter than the retry delay: no retry.
calls = 0;
r = FetchAsync("http://h/a.js", steady_clock::now() + milliseconds(10));
Check(r.completions == 1 && calls == 1, "no retry past the deadline", mode);
Transport().Reset();
Transport().schedulesItself = schedulesItself;
r = FetchAsync("http://h/a.js", steady_clock::now() + milliseconds(1500));
const auto requests = Transport().Requests();
Check(requests.size() == 1 && requests[0].timeout <= milliseconds(1500) &&
requests[0].timeout > milliseconds(1000),
"attempt timeout clamps to the deadline", mode);
std::atomic<int> completionCalls{0};
FetchModuleBodyAsync("http://h/a.js", std::nullopt, [&](ModuleFetchResult) {
completionCalls++;
throw std::runtime_error("posted to a dead loop");
});
for (int i = 0; i < 200 && completionCalls == 0; i++) {
std::this_thread::sleep_for(milliseconds(5));
}
std::this_thread::sleep_for(milliseconds(20));
Check(completionCalls == 1, "a throwing completion is contained", mode);
}
void TestSelfScheduledThrow() {
Start(DebugConfig());
Transport().schedulesItself = true;
Transport().throwFromFetchAsync = true;
AsyncResult r = FetchAsync("http://h/a.js");
Check(r.completions == 1 && !r.result.ok,
"FetchAsync throwing still completes once");
}
// ── Fetch thread caps ───────────────────────────────────────────────────────
void TestLaneCap() {
HttpLoaderConfig config = DebugConfig();
config.fetchConcurrency[0] = 2;
Start(config);
Check(ModuleFetchConcurrency(ModuleFetchHostClass::kLoopback) == 2,
"configured loopback cap");
Check(ModuleFetchConcurrency(ModuleFetchHostClass::kRemote) == 32,
"default remote cap");
std::atomic<int> inFlight{0};
std::atomic<int> maxInFlight{0};
Transport().SetResponder([&](const AttemptRequest& request) {
const int now = ++inFlight;
int seen = maxInFlight.load();
while (now > seen && !maxInFlight.compare_exchange_weak(seen, now)) {
}
std::this_thread::sleep_for(milliseconds(20));
inFlight--;
return Ok(request.url, "export {}");
});
const int starts = Transport().threadStarts;
std::atomic<int> done{0};
for (int i = 0; i < 8; i++) {
FetchModuleBodyAsync("http://localhost/" + std::to_string(i) + ".js",
std::nullopt, [&](ModuleFetchResult) { done++; });
}
for (int i = 0; i < 400 && done < 8; i++) {
std::this_thread::sleep_for(milliseconds(5));
}
Check(done == 8, "every queued fetch completes");
Check(maxInFlight <= 2, "loopback lane honours its cap",
std::to_string(maxInFlight.load()));
Check(Transport().threadStarts - starts <= 2, "threads bounded by the cap");
for (int i = 0;
i < 200 && Transport().threadExits != Transport().threadStarts; i++) {
std::this_thread::sleep_for(milliseconds(5));
}
Check(Transport().threadExits == Transport().threadStarts,
"fetch threads run their exit hook");
}
// ── Cache ───────────────────────────────────────────────────────────────────
void TestCacheSwitch() {
HttpLoaderConfig config = DebugConfig();
config.moduleHttpCacheAtStartup = false;
Start(config);
Check(!ModuleHttpCacheEnabled(), "startup setting off");
SetModuleHttpCacheEnabled(true);
Check(ModuleHttpCacheEnabled(), "setter wins over startup");
SetModuleHttpCacheDisabledBy(1, true);
SetModuleHttpCacheDisabledBy(1, true);
SetModuleHttpCacheDisabledBy(2, true);
Check(!ModuleHttpCacheEnabled(), "holders disable");
SetModuleHttpCacheDisabledBy(1, false);
Check(!ModuleHttpCacheEnabled(), "another holder still disables");
SetModuleHttpCacheDisabledBy(2, false);
Check(ModuleHttpCacheEnabled(), "idempotent per holder");
// Sampled when the fetch is issued.
std::atomic<bool> release{false};
Transport().schedulesItself = false;
Transport().SetResponder([&](const AttemptRequest& request) {
while (!release) {
std::this_thread::sleep_for(milliseconds(1));
}
return Ok(request.url, "export {}");
});
std::atomic<int> done{0};
FetchModuleBodyAsync("http://h/a.js", std::nullopt,
[&](ModuleFetchResult) { done++; });
SetModuleHttpCacheEnabled(false);
release = true;
for (int i = 0; i < 400 && done == 0; i++) {
std::this_thread::sleep_for(milliseconds(5));
}
const auto requests = Transport().Requests();
Check(requests.size() == 1 && requests[0].useCache,
"in-flight fetch keeps the switch it was issued with");
Transport().clearResult = CacheOpResult{false, "permission denied"};
CacheOpResult cleared = ClearModuleHttpCache();
Check(!cleared.ok && cleared.error == "permission denied" &&
Transport().clearAllCalls == 1,
"clear failures are reported");
Transport().clearResult = CacheOpResult{false, "throw"};
cleared = ClearModuleHttpCache();
Check(!cleared.ok && cleared.error == "disk full",
"a throwing clear is reported");
}
void TestClearSiteData() {
Check(ClearSiteDataClearsCache({"\"cookies\", \"cache\""}), "listed cache");
Check(ClearSiteDataClearsCache({"\"storage\"", " \"*\" "}),
"wildcard on a second header line");
Check(!ClearSiteDataClearsCache({"cache", "\"cookies\",,"}),
"unquoted or other directives");
Start(DebugConfig());
Transport().SetResponder([](const AttemptRequest&) {
AttemptOutcome outcome = Ok("https://cdn.example.com/x.js", "export {}");
outcome.clearSiteData = {"\"cache\""};
return outcome;
});
ModuleFetchResult result;
HttpFetchModule("http://localhost:5173/a.js", result);
auto origins = Transport().ClearedOrigins();
Check(origins.size() == 2 && origins[0] == "https://cdn.example.com" &&
origins[1] == "http://localhost:5173",
"clears the response and the fetching origin");
Transport().Reset();
Transport().SetResponder([](const AttemptRequest& request) {
AttemptOutcome outcome = Ok(request.url, "export {}");
outcome.clearSiteData = {"\"*\""};
return outcome;
});
FetchAsync("http://localhost:5173/a.js");
origins = Transport().ClearedOrigins();
Check(origins.size() == 1 && origins[0] == "http://localhost:5173",
"each origin once");
Transport().Reset();
SetModuleHttpCacheEnabled(false);
Transport().SetResponder([](const AttemptRequest&) {
AttemptOutcome outcome = Ok("https://cdn.example.com/x.js", "export {}");
outcome.clearSiteData = {"\"cache\""};
return outcome;
});
HttpFetchModule("http://localhost:5173/a.js", result);
origins = Transport().ClearedOrigins();
Check(origins.size() == 1 && origins[0] == "https://cdn.example.com",
"uncached fetch stored nothing under its own origin");
}
} // namespace
int main() {
TestGateRelease();
TestRedirectGate();
TestRequestShape();
TestSyncRetry();
TestAsync(false);
TestAsync(true);
TestSelfScheduledThrow();
TestLaneCap();
TestCacheSwitch();
TestClearSiteData();
if (failures > 0) {
std::fprintf(stderr, "%d failure(s)\n", failures);
return 1;
}
std::printf("all HTTP fetch tests passed\n");
return 0;
}