[boring] Only follow https redirects when fetching prebuilt libraries (#2907) Enforce https for the initial URL and all redirects in fetchHttpWithRetry / downloadBytes (used by both the fetch build mode and tool/regenerate_hashes.dart). GitHub release asset URLs always return a 302 redirect to GitHub's asset storage, so the client must follow redirects. dart:io's HttpClient follows redirects to plain http URLs by default, which can downgrade the transfer out of TLS: - In tool/regenerate_hashes.dart, assets are downloaded before any SHA-256 pin exists, so keeping redirects on TLS prevents a downgrade/MITM from injecting a tampered library into hashes.dart. - In consumer fetch builds, integrity is already covered by the pinned SHA-256, so keeping redirects on TLS provides defense-in-depth (confidentiality and preventing trivial plaintext DoS). Handles redirects manually in _fetchWithSecureRedirects (max 5), refusing non-https initial URLs, non-https redirects, invalid or duplicate Location headers, and excessive redirects with a non-retryable HttpFetchException. Switches the fetch unit tests to local loopback HTTPS and adds redirect test coverage.
diff --git a/pkgs/boring/CHANGELOG.md b/pkgs/boring/CHANGELOG.md index 6aaf0d2..19aa9b0 100644 --- a/pkgs/boring/CHANGELOG.md +++ b/pkgs/boring/CHANGELOG.md
@@ -1,5 +1,7 @@ ## 0.5.1-wip +- The `fetch` build mode only follows redirects to `https` URLs when + downloading the prebuilt libraries. - BoringSSL is compiled with `OPENSSL_SMALL`, which for example makes the tree-shaken library of `package:webcrypto` about 19% smaller, and P-256 operations about 2x slower.
diff --git a/pkgs/boring/lib/src/hook_helpers/fetch.dart b/pkgs/boring/lib/src/hook_helpers/fetch.dart index 023a9bb..945fdd4 100644 --- a/pkgs/boring/lib/src/hook_helpers/fetch.dart +++ b/pkgs/boring/lib/src/hook_helpers/fetch.dart
@@ -116,10 +116,12 @@ /// `403`, `5xx`), network, or timeout errors, or throws a [BuildError] if the /// download fails. /// -/// Honors `HTTPS_PROXY` environment variables, `Retry-After` headers (capped at -/// 60s), and an overall [totalTimeout] across all attempts. +/// Requires [url] and any redirects to use the `https` scheme. Honors +/// `HTTPS_PROXY` environment variables, `Retry-After` headers (capped at 60s), +/// and an overall [totalTimeout] across all attempts. Future<List<int>> downloadBytes( Uri url, { + HttpClient? client, int maxAttempts = defaultMaxAttempts, Duration totalTimeout = defaultTotalTimeout, Future<void> Function(Duration) delay = Future<void>.delayed, @@ -129,6 +131,7 @@ try { response = await fetchHttpWithRetry( url, + client: client, maxAttempts: maxAttempts, totalTimeout: totalTimeout, delay: delay, @@ -155,7 +158,11 @@ /// before falling back to `1s`, `2s`, `4s`, and enforces an overall /// [totalTimeout] across all attempts. Returns the non-retryable HTTP status /// and body bytes (`200` or permanent status codes such as `404`), or throws an -/// [HttpFetchException] when retries or [totalTimeout] are exhausted. +/// [HttpFetchException] for non-`https` URLs, disallowed or excessive +/// redirects, or when retries or [totalTimeout] are exhausted. +/// +/// Requires [url] to use the `https` scheme and follows redirects (such as +/// GitHub's to its release asset storage) only to `https` URLs. Future<({int statusCode, List<int> bytes})> fetchHttpWithRetry( Uri url, { HttpClient? client, @@ -236,12 +243,7 @@ }) async { Duration capped(Duration limit) => _minDuration(limit, remaining()); try { - final request = await client - .getUrl(url) - .timeout(capped(defaultConnectionTimeout)); - final response = await request.close().timeout( - capped(defaultConnectionTimeout), - ); + final response = await _fetchWithSecureRedirects(client, url, capped); final statusCode = response.statusCode; if (_isRetryableStatus(statusCode, response.headers)) { final retryAfter = _parseRetryAfter(response.headers, now); @@ -272,6 +274,71 @@ } } +/// The most redirects [_fetchWithSecureRedirects] follows. +const _maxRedirects = 5; + +/// Sends a `GET` request for [url] with [client] and follows redirects only to +/// `https` URLs, so that the download never leaves TLS, unlike [HttpClient]'s +/// own redirect handling, which also follows redirects to `http` URLs. +/// +/// Caps each await with [capped]. Throws an [HttpFetchException], which isn't +/// retried, if [url] is not an `https` URL, or for a redirect to another +/// scheme, an invalid or duplicate `Location` header, or too many redirects. +Future<HttpClientResponse> _fetchWithSecureRedirects( + HttpClient client, + Uri url, + Duration Function(Duration limit) capped, +) async { + if (url.scheme != 'https') { + throw HttpFetchException( + 'Refusing to download from $url, which is not an https URL.', + ); + } + var currentUrl = url; + for (var redirects = 0; ; redirects++) { + final request = await client + .getUrl(currentUrl) + .timeout(capped(defaultConnectionTimeout)); + request.followRedirects = false; + final response = await request.close().timeout( + capped(defaultConnectionTimeout), + ); + // `headers[name]` instead of `headers.value(name)`, which throws an + // `HttpException` (an `IOException`) on duplicate header lines. + final locations = response.headers[HttpHeaders.locationHeader]; + if (!response.isRedirect || locations == null || locations.isEmpty) { + return response; + } + await response.drain<void>().timeout(capped(defaultConnectionTimeout)); + if (locations.length > 1) { + throw HttpFetchException( + 'Received multiple Location headers from $currentUrl while ' + 'downloading from $url.', + ); + } + final location = locations.single; + final Uri nextUrl; + try { + nextUrl = currentUrl.resolve(location); + } on FormatException catch (e) { + throw HttpFetchException( + 'Received invalid redirect location "$location" from $currentUrl ' + 'while downloading from $url: $e', + ); + } + if (nextUrl.scheme != 'https') { + throw HttpFetchException( + 'Refusing to follow the redirect from $currentUrl to $nextUrl, which ' + 'is not an https URL, while downloading from $url.', + ); + } + if (redirects == _maxRedirects) { + throw HttpFetchException('Too many redirects downloading from $url.'); + } + currentUrl = nextUrl; + } +} + bool _isRetryableStatus(int statusCode, HttpHeaders headers) { if (statusCode == HttpStatus.requestTimeout || statusCode == HttpStatus.tooManyRequests || @@ -311,7 +378,9 @@ Duration _minDuration(Duration a, Duration b) => a <= b ? a : b; -/// Exception thrown by [fetchHttpWithRetry] when all retry attempts or the +/// Exception thrown by [fetchHttpWithRetry] when a request fails permanently +/// (for example, a non-`https` URL or redirect, an invalid or duplicate +/// `Location` header, or too many redirects) or when all retry attempts or the /// overall deadline are exhausted. final class HttpFetchException implements Exception { final String message;
diff --git a/pkgs/boring/test/hook_helpers_test.dart b/pkgs/boring/test/hook_helpers_test.dart index acc10df..d209ff3 100644 --- a/pkgs/boring/test/hook_helpers_test.dart +++ b/pkgs/boring/test/hook_helpers_test.dart
@@ -5,6 +5,7 @@ @TestOn('vm') library; +import 'dart:convert'; import 'dart:io'; import 'package:boring/src/hook_helpers/build_options.dart'; @@ -177,8 +178,7 @@ 'retries transient 5xx and connection drops before succeeding', () async { var requests = 0; - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - addTearDown(() => server.close(force: true)); + final server = await _bindTestHttpsServer(); server.listen((request) async { requests++; switch (requests) { @@ -198,7 +198,8 @@ final delays = <Duration>[]; final bytes = await downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/asset.bin'), + Uri.parse('https://${server.address.host}:${server.port}/asset.bin'), + client: _testHttpsClient(), delay: (duration) async => delays.add(duration), ); @@ -211,12 +212,197 @@ }, ); - test('does not retry permanent 404 responses', () async { + test('refuses non-https URLs without making a request', () async { var requests = 0; final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); addTearDown(() => server.close(force: true)); server.listen((request) async { requests++; + await request.response.close(); + }); + + await expectLater( + () => downloadBytes( + Uri.parse('http://${server.address.host}:${server.port}/asset.bin'), + delay: (_) async {}, + ), + throwsA( + isA<BuildError>().having( + (e) => e.message, + 'message', + allOf( + contains('which is not an https URL'), + contains('buildMode: checkout'), + ), + ), + ), + ); + expect(requests, 0); + }); + + test('follows valid https redirects', () async { + final visited = <String>[]; + final server = await _bindTestHttpsServer(); + server.listen((request) async { + visited.add(request.uri.path); + switch (request.uri.path) { + case '/start': + await request.response.redirect( + Uri.parse('https://${server.address.host}:${server.port}/mid'), + ); + case '/mid': + request.response + ..statusCode = HttpStatus.found + ..headers.set(HttpHeaders.locationHeader, '/final.bin'); + await request.response.close(); + default: + request.response.add(const [7, 8, 9]); + await request.response.close(); + } + }); + + final bytes = await downloadBytes( + Uri.parse('https://${server.address.host}:${server.port}/start'), + client: _testHttpsClient(), + delay: (_) async {}, + ); + + expect(bytes, [7, 8, 9]); + expect(visited, ['/start', '/mid', '/final.bin']); + }); + + test('refuses redirects to http URLs without retrying', () async { + var requests = 0; + final server = await _bindTestHttpsServer(); + server.listen((request) async { + requests++; + await request.response.redirect( + Uri.parse('http://${server.address.host}:${server.port}/plain'), + ); + }); + + await expectLater( + () => downloadBytes( + Uri.parse('https://${server.address.host}:${server.port}/asset.bin'), + client: _testHttpsClient(), + delay: (_) async {}, + ), + throwsA( + isA<BuildError>().having( + (e) => e.message, + 'message', + contains('which is not an https URL'), + ), + ), + ); + expect(requests, 1); + }); + + test('refuses invalid redirect locations', () async { + final server = await _bindTestHttpsServer(); + server.listen((request) async { + request.response + ..statusCode = HttpStatus.found + ..headers.set(HttpHeaders.locationHeader, 'https://[::1'); + await request.response.close(); + }); + + await expectLater( + () => downloadBytes( + Uri.parse('https://${server.address.host}:${server.port}/asset.bin'), + client: _testHttpsClient(), + delay: (_) async {}, + ), + throwsA( + isA<BuildError>().having( + (e) => e.message, + 'message', + contains('invalid redirect location'), + ), + ), + ); + }); + + test('refuses duplicate Location headers without retrying', () async { + // HttpServer folds repeated headers into one line, so emit raw + // duplicate lines the way some proxies do. + var requests = 0; + final server = await SecureServerSocket.bind( + InternetAddress.loopbackIPv4, + 0, + _testSecurityContext(), + ); + addTearDown(server.close); + server.listen((socket) async { + requests++; + await socket.first; + socket.write( + 'HTTP/1.1 302 Found\r\n' + 'Location: https://${server.address.host}:${server.port}/a\r\n' + 'Location: https://${server.address.host}:${server.port}/b\r\n' + 'Content-Length: 0\r\n' + '\r\n', + ); + await socket.flush(); + await socket.close(); + }); + + final delays = <Duration>[]; + await expectLater( + () => downloadBytes( + Uri.parse('https://${server.address.host}:${server.port}/asset.bin'), + client: _testHttpsClient(), + delay: (duration) async => delays.add(duration), + ), + throwsA( + isA<BuildError>().having( + (e) => e.message, + 'message', + contains('multiple Location headers'), + ), + ), + ); + expect(requests, 1); + expect(delays, isEmpty); + }); + + test('refuses too many redirects without retrying', () async { + var requests = 0; + final server = await _bindTestHttpsServer(); + server.listen((request) async { + requests++; + await request.response.redirect( + Uri.parse( + 'https://${server.address.host}:${server.port}/hop/$requests', + ), + ); + }); + + final delays = <Duration>[]; + await expectLater( + () => downloadBytes( + Uri.parse('https://${server.address.host}:${server.port}/hop/0'), + client: _testHttpsClient(), + delay: (duration) async => delays.add(duration), + ), + throwsA( + isA<BuildError>().having( + (e) => e.message, + 'message', + contains('Too many redirects'), + ), + ), + ); + // Initial request plus 5 followed redirects; the 6th redirect fails. + expect(requests, 6); + expect(delays, isEmpty); + }); + + test('does not retry permanent 404 responses', () async { + var requests = 0; + final server = await _bindTestHttpsServer(); + server.listen((request) async { + requests++; request.response.statusCode = HttpStatus.notFound; await request.response.close(); }); @@ -224,7 +410,10 @@ final delays = <Duration>[]; await expectLater( () => downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/missing.bin'), + Uri.parse( + 'https://${server.address.host}:${server.port}/missing.bin', + ), + client: _testHttpsClient(), delay: (duration) async => delays.add(duration), ), throwsA( @@ -244,8 +433,7 @@ 'throws BuildError after exhausting retries on persistent 504', () async { var requests = 0; - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - addTearDown(() => server.close(force: true)); + final server = await _bindTestHttpsServer(); server.listen((request) async { requests++; request.response.statusCode = HttpStatus.gatewayTimeout; @@ -255,7 +443,10 @@ final delays = <Duration>[]; await expectLater( () => downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/flaky.bin'), + Uri.parse( + 'https://${server.address.host}:${server.port}/flaky.bin', + ), + client: _testHttpsClient(), maxAttempts: 3, delay: (duration) async => delays.add(duration), ), @@ -280,8 +471,7 @@ 'retries 403 rate-limit responses and honors Retry-After capped at 60s', () async { var requests = 0; - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - addTearDown(() => server.close(force: true)); + final server = await _bindTestHttpsServer(); server.listen((request) async { requests++; switch (requests) { @@ -302,7 +492,8 @@ final delays = <Duration>[]; final bytes = await downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/throttled'), + Uri.parse('https://${server.address.host}:${server.port}/throttled'), + client: _testHttpsClient(), delay: (duration) async => delays.add(duration), ); @@ -319,8 +510,7 @@ 'retries 403 with only x-ratelimit-remaining: 0 and 408 using backoff', () async { var requests = 0; - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - addTearDown(() => server.close(force: true)); + final server = await _bindTestHttpsServer(); server.listen((request) async { requests++; switch (requests) { @@ -339,7 +529,8 @@ final delays = <Duration>[]; final bytes = await downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/limited'), + Uri.parse('https://${server.address.host}:${server.port}/limited'), + client: _testHttpsClient(), delay: (duration) async => delays.add(duration), ); @@ -356,8 +547,7 @@ 'does not retry plain 403 responses without rate-limit headers', () async { var requests = 0; - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - addTearDown(() => server.close(force: true)); + final server = await _bindTestHttpsServer(); server.listen((request) async { requests++; request.response.statusCode = HttpStatus.forbidden; @@ -367,7 +557,8 @@ final delays = <Duration>[]; await expectLater( () => downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/denied'), + Uri.parse('https://${server.address.host}:${server.port}/denied'), + client: _testHttpsClient(), delay: (duration) async => delays.add(duration), ), throwsA( @@ -390,7 +581,11 @@ // HttpServer folds repeated headers into one line, so emit raw // duplicate lines the way some proxies do. var requests = 0; - final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final server = await SecureServerSocket.bind( + InternetAddress.loopbackIPv4, + 0, + _testSecurityContext(), + ); addTearDown(server.close); server.listen((socket) async { requests++; @@ -409,7 +604,8 @@ final delays = <Duration>[]; await expectLater( () => downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/denied'), + Uri.parse('https://${server.address.host}:${server.port}/denied'), + client: _testHttpsClient(), delay: (duration) async => delays.add(duration), ), throwsA( @@ -430,8 +626,7 @@ var requests = 0; final fixedNow = DateTime.utc(2026, 11, 18, 12, 0, 0); final retryAt = fixedNow.add(const Duration(seconds: 9)); - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - addTearDown(() => server.close(force: true)); + final server = await _bindTestHttpsServer(); server.listen((request) async { requests++; if (requests == 1) { @@ -449,7 +644,8 @@ final delays = <Duration>[]; final bytes = await downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/date-retry'), + Uri.parse('https://${server.address.host}:${server.port}/date-retry'), + client: _testHttpsClient(), now: () => fixedNow, delay: (duration) async => delays.add(duration), ); @@ -463,8 +659,7 @@ 'enforces overall totalTimeout deadline across stalled body reads', () async { var requests = 0; - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - addTearDown(() => server.close(force: true)); + final server = await _bindTestHttpsServer(); server.listen((request) async { requests++; request.response.bufferOutput = false; @@ -477,9 +672,10 @@ final delays = <Duration>[]; await expectLater( () => downloadBytes( - Uri.parse('http://${server.address.host}:${server.port}/stalled'), + Uri.parse('https://${server.address.host}:${server.port}/stalled'), + client: _testHttpsClient(), maxAttempts: 4, - totalTimeout: const Duration(milliseconds: 80), + totalTimeout: const Duration(milliseconds: 200), delay: (duration) async => delays.add(duration), ), throwsA( @@ -504,8 +700,7 @@ 'reuses a caller-supplied HttpClient across 404 and retried 504 requests', () async { var requests = 0; - final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); - addTearDown(() => server.close(force: true)); + final server = await _bindTestHttpsServer(); server.listen((request) async { requests++; if (request.uri.path == '/missing.so') { @@ -522,12 +717,13 @@ await request.response.close(); }); - final client = HttpClient(); - addTearDown(() => client.close(force: true)); + final client = _testHttpsClient(); final delays = <Duration>[]; final missing = await fetchHttpWithRetry( - Uri.parse('http://${server.address.host}:${server.port}/missing.so'), + Uri.parse( + 'https://${server.address.host}:${server.port}/missing.so', + ), client: client, delay: (duration) async => delays.add(duration), ); @@ -537,7 +733,9 @@ expect(delays, isEmpty); final found = await fetchHttpWithRetry( - Uri.parse('http://${server.address.host}:${server.port}/present.so'), + Uri.parse( + 'https://${server.address.host}:${server.port}/present.so', + ), client: client, delay: (duration) async => delays.add(duration), ); @@ -550,6 +748,66 @@ }); } +Future<HttpServer> _bindTestHttpsServer() async { + final server = await HttpServer.bindSecure( + InternetAddress.loopbackIPv4, + 0, + _testSecurityContext(), + ); + addTearDown(() => server.close(force: true)); + return server; +} + +HttpClient _testHttpsClient() { + final client = HttpClient(context: _testSecurityContext()) + // macOS's SecTrustEvaluate enforces Apple's TLS leaf policy (such as the + // 825-day validity cap), which rejects long-lived self-signed test certs + // even when added to SecurityContext. Accept only our exact test cert on + // loopback so the tests pass on macOS without expiring every two years. + ..badCertificateCallback = (cert, host, port) => + host == InternetAddress.loopbackIPv4.address && + cert.pem.trim() == _localhostCertPemString.trim(); + addTearDown(() => client.close(force: true)); + return client; +} + +SecurityContext _testSecurityContext() => SecurityContext() + ..setTrustedCertificatesBytes(_localhostCertPem) + ..useCertificateChainBytes(_localhostCertPem) + ..usePrivateKeyBytes(_localhostKeyPem, password: 'test'); + +// Self-signed ECDSA P-256 certificate for 127.0.0.1 / localhost, generated +// with: +// openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \ +// -keyout test_key.pem -out test_cert.pem -days 36500 -passout pass:test \ +// -subj '/CN=localhost' -addext 'subjectAltName=IP:127.0.0.1,DNS:localhost' +final _localhostKeyPem = utf8.encode(r''' +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIH0MF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBBWVf/06GV+jC7t0ha0 +UfP2AgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQcedLjKlZKOVVZp9p +Yd28xASBkIvXcWV/xRGm890Vc0fU/hopEoW3dOerAB1X8gqWn4IHYPALc2jq3fAr +4VZ/9ED7niTt3yN35CrF723e7D+LA0FYfk9vAipv3UlhE5yhQrvmWLmyWSTGR4I6 +G0ckOamoDfDcdRBjLm02FUa/zAZ4FrpCcKoPpXdWPEzwpyYW7u8lvleUjE/Z7NKS +nuLZInOzMg== +-----END ENCRYPTED PRIVATE KEY----- +'''); + +const _localhostCertPemString = r''' +-----BEGIN CERTIFICATE----- +MIIBmjCCAUGgAwIBAgIUY23lKqegWdyuWstvlIhKhgwLUCowCgYIKoZIzj0EAwIw +FDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MTIwMjA4NTAzOFoYDzIxMjYxMTA4 +MDg1MDM4WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjO +PQMBBwNCAARwgFXf8KVhQ625AordnE7Ouv+yCaAs86y76He7I7ciQ/tvlJQ9pij+ +a6tLeceGNNMI4G5Y4qmGJFH/MM823zoco28wbTAdBgNVHQ4EFgQUo1kDKPWoZrXt +12Vi/KToB2gWO7QwHwYDVR0jBBgwFoAUo1kDKPWoZrXt12Vi/KToB2gWO7QwDwYD +VR0TAQH/BAUwAwEB/zAaBgNVHREEEzARhwR/AAABgglsb2NhbGhvc3QwCgYIKoZI +zj0EAwIDRwAwRAIgNbuWPRYjbPG+6Vfpkr3S22+yi5ZQ6QpWHQ74nL6hVVYCICWm +Au4KHDyf/5CsNmKzVeBj39C7P0vsNiGE6X0NstJU +-----END CERTIFICATE----- +'''; + +final _localhostCertPem = utf8.encode(_localhostCertPemString); + final _basePath = Directory.current.uri; /// The user-defines of a root package whose pubspec.yaml has [defines] under