Skip to content

Commit 3ca7e71

Browse files
authored
test(redteam): verify Chrome Debugger.scriptParsed source maps for Wasm and JS (#9)
- Enable the CDP `Debugger` domain in `ChromeSession` and capture `Debugger.scriptParsed` events (`ParsedScriptRecord`) including `sourceMapURL` and `scriptLanguage`. - Update `S12` (`PrecacheManifestScenario`) to verify that: - `main.dart.wasm.map` resolves (`200 OK`) with valid Source Map v3 JSON (`version: 3`, non-empty `sources` and `mappings`). - Live headless Chrome emits `Debugger.scriptParsed` with `sourceMapURL: "main.dart.wasm.map"` for `main.dart.<hash>.wasm` and a content-hashed `main.dart.<mapHash>.js.map` for `main.dart.<hash>.js`, and can fetch and parse both `.map` files as valid Source Map v3 JSON. Refs: flutter/flutter#193601 Refs: flutter/flutter#193614
1 parent 70a79ef commit 3ca7e71

2 files changed

Lines changed: 179 additions & 1 deletion

File tree

‎tool/redteam_harness/lib/src/chrome.dart‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,31 @@ class ServiceWorkerVersion {
6969
};
7070
}
7171

72+
/// A script or WebAssembly module parsed by V8 (`Debugger.scriptParsed`).
73+
class ParsedScriptRecord {
74+
ParsedScriptRecord({
75+
required this.scriptId,
76+
required this.url,
77+
this.sourceMapUrl,
78+
this.scriptLanguage,
79+
});
80+
81+
final String scriptId;
82+
final String url;
83+
final String? sourceMapUrl;
84+
final String? scriptLanguage;
85+
86+
String get path => Uri.tryParse(url)?.path ?? url;
87+
88+
Map<String, Object?> toJson() => {
89+
'scriptId': scriptId,
90+
'url': url,
91+
if (sourceMapUrl != null && sourceMapUrl!.isNotEmpty)
92+
'sourceMapUrl': sourceMapUrl,
93+
if (scriptLanguage != null) 'scriptLanguage': scriptLanguage,
94+
};
95+
}
96+
7297
/// Resolves a Chromium binary: `$REDTEAM_CHROME`, then Playwright's download,
7398
/// then a system Chrome.
7499
String resolveChromeBinary() {
@@ -129,6 +154,7 @@ class ChromeSession {
129154
final Map<String, ServiceWorkerVersion> serviceWorkers =
130155
<String, ServiceWorkerVersion>{};
131156
final List<String> serviceWorkerEvents = <String>[];
157+
final List<ParsedScriptRecord> parsedScripts = <ParsedScriptRecord>[];
132158

133159
/// Top-level navigations since the last [resetObservations] (1 = the load
134160
/// itself; more = the page reloaded itself, e.g. a service worker
@@ -229,6 +255,7 @@ class ChromeSession {
229255
await _page.sendCommand('Runtime.enable');
230256
await _page.sendCommand('Log.enable');
231257
await _page.sendCommand('ServiceWorker.enable');
258+
await _page.sendCommand('Debugger.enable');
232259
}
233260

234261
void _onNotification(WipEvent event) {
@@ -250,6 +277,8 @@ class ChromeSession {
250277
_onLogEntryAdded(params);
251278
case 'ServiceWorker.workerVersionUpdated':
252279
_onWorkerVersionUpdated(params);
280+
case 'Debugger.scriptParsed':
281+
_onScriptParsed(params);
253282
case 'Page.frameNavigated':
254283
final frame = params['frame'] as Map<String, Object?>;
255284
if (frame['parentId'] == null) navigations++;
@@ -259,6 +288,22 @@ class ChromeSession {
259288
}
260289
}
261290

291+
void _onScriptParsed(Map<String, Object?> params) {
292+
final url = (params['url'] as String?) ?? '';
293+
if (!url.startsWith('http')) return;
294+
final sourceMapUrl = params['sourceMapURL'] as String?;
295+
parsedScripts.add(
296+
ParsedScriptRecord(
297+
scriptId: params['scriptId'] as String,
298+
url: url,
299+
sourceMapUrl: (sourceMapUrl != null && sourceMapUrl.isNotEmpty)
300+
? sourceMapUrl
301+
: null,
302+
scriptLanguage: params['scriptLanguage'] as String?,
303+
),
304+
);
305+
}
306+
262307
void _onRequestWillBeSent(Map<String, Object?> params) {
263308
final id = params['requestId'] as String;
264309
final request = params['request'] as Map<String, Object?>;
@@ -349,6 +394,7 @@ class ChromeSession {
349394
consoleMessages.clear();
350395
logEntries.clear();
351396
serviceWorkerEvents.clear();
397+
parsedScripts.clear();
352398
navigations = 0;
353399
}
354400

@@ -499,6 +545,7 @@ class ChromeSession {
499545
'logEntries': logEntries,
500546
'serviceWorkers': serviceWorkers.values.map((v) => v.toJson()).toList(),
501547
'serviceWorkerEvents': serviceWorkerEvents,
548+
'parsedScripts': parsedScripts.map((s) => s.toJson()).toList(),
502549
'navigations': navigations,
503550
};
504551
}

‎tool/redteam_harness/lib/src/scenarios_variants.dart‎

Lines changed: 132 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import 'package:http/http.dart' as http;
77
import 'package:path/path.dart' as p;
88

99
import 'builder.dart';
10+
import 'chrome.dart';
1011
import 'hosting.dart';
1112
import 'scenario.dart';
1213

@@ -402,6 +403,7 @@ class PrecacheManifestScenario extends Scenario {
402403
badSourceMaps.isEmpty,
403404
badSourceMaps.take(6).join(' | '),
404405
);
406+
await _verifyWasmSourceMap(host.baseUri, step);
405407

406408
final live = host
407409
.liveFiles()
@@ -417,11 +419,140 @@ class PrecacheManifestScenario extends Scenario {
417419
step.notes.add(
418420
'${entries.length} entries; hashed: ${entries.where((e) => e['urlHashed'] == true).length}',
419421
);
422+
423+
await _verifyChromeSourceMaps(ctx, result, host, urls);
420424
} finally {
421425
await host.stop();
422426
}
423427
}
424428

429+
static Future<void> _verifyWasmSourceMap(Uri baseUri, Step step) async {
430+
final wasmMapResp = await http.get(baseUri.resolve('main.dart.wasm.map'));
431+
final validWasmMap =
432+
wasmMapResp.statusCode == 200 &&
433+
_isValidSourceMapV3Json(wasmMapResp.body);
434+
step.check(
435+
'main.dart.wasm.map resolves (200 OK) with valid Source Map v3 JSON',
436+
validWasmMap,
437+
'status=${wasmMapResp.statusCode}',
438+
);
439+
}
440+
441+
static Future<void> _verifyChromeSourceMaps(
442+
ScenarioContext ctx,
443+
ScenarioResult result,
444+
HostingServer host,
445+
List<String> urls,
446+
) async {
447+
final chromeStep = result.step(
448+
'chrome Debugger.scriptParsed source maps (Wasm + JS)',
449+
);
450+
final chrome = await ctx.chrome(ctx.freshProfile('S12'));
451+
try {
452+
final report = await loadAndCapture(
453+
chromeStep,
454+
chrome,
455+
host,
456+
host.baseUri,
457+
);
458+
checkHealthyLoad(chromeStep, chrome, report, expectedVersion: 'v1');
459+
460+
final mainJsUrl = urls.firstWhere(
461+
(u) => u.startsWith('main.dart.') && u.endsWith('.js'),
462+
orElse: () => '',
463+
);
464+
if (mainJsUrl.isNotEmpty) {
465+
await chrome.evaluate('''
466+
new Promise((resolve) => {
467+
const s = document.createElement('script');
468+
s.src = ${json.encode(mainJsUrl)};
469+
s.onload = () => resolve(true);
470+
s.onerror = () => resolve(false);
471+
document.head.appendChild(s);
472+
})
473+
''');
474+
}
475+
476+
final wasmScript = chrome.parsedScripts
477+
.where(
478+
(s) => s.path.endsWith('.wasm') && s.path.contains('main.dart.'),
479+
)
480+
.firstOrNull;
481+
chromeStep.check(
482+
'Chrome Debugger.scriptParsed reports sourceMapURL for main.dart.<hash>.wasm',
483+
wasmScript?.sourceMapUrl == 'main.dart.wasm.map',
484+
'wasmScript=${wasmScript?.toJson()}',
485+
);
486+
if (wasmScript?.sourceMapUrl != null) {
487+
final resolvedWasmMap = Uri.parse(wasmScript!.url)
488+
.resolve(wasmScript.sourceMapUrl!)
489+
.toString();
490+
final wasmMapOk = await _chromeFetchSourceMapV3(
491+
chrome,
492+
resolvedWasmMap,
493+
);
494+
chromeStep.check(
495+
'Chrome fetches and parses main.dart.wasm.map (200 OK, Source Map v3)',
496+
wasmMapOk,
497+
resolvedWasmMap,
498+
);
499+
}
500+
501+
final jsScript = chrome.parsedScripts
502+
.where((s) => s.path.endsWith('.js') && s.path.contains('main.dart.'))
503+
.firstOrNull;
504+
final jsMapUrl = jsScript?.sourceMapUrl ?? '';
505+
chromeStep.check(
506+
'Chrome Debugger.scriptParsed reports hashed sourceMapURL for main.dart.<hash>.js',
507+
jsMapUrl.isNotEmpty && _hashedFilenameRegex.hasMatch(jsMapUrl),
508+
'jsScript=${jsScript?.toJson()}',
509+
);
510+
if (jsScript != null && jsMapUrl.isNotEmpty) {
511+
final resolvedJsMap = Uri.parse(jsScript.url)
512+
.resolve(jsMapUrl)
513+
.toString();
514+
final jsMapOk = await _chromeFetchSourceMapV3(chrome, resolvedJsMap);
515+
chromeStep.check(
516+
'Chrome fetches and parses main.dart.<hash>.js.map (200 OK, Source Map v3)',
517+
jsMapOk,
518+
resolvedJsMap,
519+
);
520+
}
521+
} finally {
522+
await chrome.close();
523+
}
524+
}
525+
526+
static Future<bool> _chromeFetchSourceMapV3(
527+
ChromeSession chrome,
528+
String mapUrl,
529+
) async {
530+
final res = await chrome.evaluate('''
531+
fetch(${json.encode(mapUrl)}).then(async (r) => {
532+
if (r.status !== 200) return false;
533+
const data = await r.json();
534+
return data && data.version === 3 && Array.isArray(data.sources) && data.sources.length > 0 && typeof data.mappings === 'string' && data.mappings.length > 0;
535+
}).catch(() => false)
536+
''');
537+
return res == true;
538+
}
539+
540+
static bool _isValidSourceMapV3Json(String body) {
541+
try {
542+
final decoded = json.decode(body);
543+
if (decoded case {
544+
'version': 3,
545+
'sources': final List<Object?> sources,
546+
'mappings': final String mappings,
547+
}) {
548+
return sources.isNotEmpty && mappings.isNotEmpty;
549+
}
550+
return false;
551+
} on FormatException {
552+
return false;
553+
}
554+
}
555+
425556
static bool _isIncludedRuntimeFile(String f) =>
426557
!f.startsWith('canvaskit/') &&
427558
!f.startsWith('.') &&
@@ -506,7 +637,7 @@ class PrecacheManifestScenario extends Scenario {
506637
final mapResp = await http.get(
507638
baseUri.resolve(Uri.encodeFull(url)).resolve(mapUrl),
508639
);
509-
if (mapResp.statusCode != 200) {
640+
if (mapResp.statusCode != 200 || !_isValidSourceMapV3Json(mapResp.body)) {
510641
badSourceMaps.add('$url -> $mapUrl (${mapResp.statusCode})');
511642
}
512643
}

0 commit comments

Comments
 (0)