blob: abf9c6b9aa651d78a419ff15017f5e0949052464 [file] [edit]
// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@TestOn('vm')
library;
import 'dart:convert';
import 'dart:io';
import 'package:boring/src/hook_helpers/build_options.dart';
import 'package:boring/src/hook_helpers/fetch.dart';
import 'package:boring/src/hook_helpers/hashes.dart';
import 'package:boring/src/hook_helpers/libc.dart';
import 'package:boring/src/hook_helpers/targets.dart';
import 'package:code_assets/code_assets.dart';
import 'package:hooks/hooks.dart';
import 'package:test/test.dart';
void main() {
group('hashes.dart', () {
// If the asset naming and the hashes file drift apart, `fetch` finds no
// hash and fails for every user.
test('pins exactly the assets of the prebuilt targets', () {
final expected = {
for (final (os, arch, iosSdk) in prebuiltTargets)
for (final static in [false, true])
releaseAssetName(os, arch, iosSdk: iosSdk, static: static),
};
if (sourceCommit.isEmpty) {
// A release built elsewhere may predate some of the prebuilt targets.
expect(fileHashes, isNotEmpty);
expect(expected, containsAll(fileHashes.keys));
} else {
expect(fileHashes.keys, unorderedEquals(expected));
}
});
test('has SHA-256 hashes', () {
for (final MapEntry(key: asset, value: hash) in fileHashes.entries) {
expect(hash, matches(RegExp(r'^[0-9a-f]{64}$')), reason: asset);
}
});
test('pins a release', () {
expect(releaseRepository, matches(RegExp(r'^[\w.-]+/[\w.-]+$')));
expect(releaseTag, isNotEmpty);
expect(sourceCommit, anyOf(isEmpty, matches(RegExp(r'^[0-9a-f]{40}$'))));
expect(
releaseAssetUrl(
repository: releaseRepository,
tag: releaseTag,
assetName: 'boring-linux-x64-libbssl_dart.so',
).toString(),
'https://github.com/$releaseRepository/releases/download/$releaseTag/'
'boring-linux-x64-libbssl_dart.so',
);
});
});
group('releaseAssetName', () {
test('uses the platform library names', () {
expect(
releaseAssetName(OS.linux, Architecture.x64, static: false),
'boring-linux-x64-libbssl_dart.so',
);
expect(
releaseAssetName(OS.linux, Architecture.arm64, static: true),
'boring-linux-arm64-libbssl_dart_static.a',
);
expect(
releaseAssetName(OS.macOS, Architecture.arm64, static: false),
'boring-macos-arm64-libbssl_dart.dylib',
);
expect(
releaseAssetName(OS.windows, Architecture.x64, static: false),
'boring-windows-x64-bssl_dart.dll',
);
expect(
releaseAssetName(OS.windows, Architecture.x64, static: true),
'boring-windows-x64-bssl_dart_static.lib',
);
});
test('distinguishes the iOS SDKs', () {
expect(
releaseAssetName(
OS.iOS,
Architecture.arm64,
iosSdk: IOSSdk.iPhoneSimulator,
static: true,
),
'boring-ios-arm64-iphonesimulator-libbssl_dart_static.a',
);
});
});
group('BuildOptions.fromDefines', () {
test('defaults to fetch', () {
final options = BuildOptions.fromDefines(_userDefines({}));
expect(options.buildMode, BuildModeEnum.fetch);
expect(options.localPath, isNull);
});
test('parses every build mode', () {
for (final mode in BuildModeEnum.values) {
expect(
BuildOptions.fromDefines(_userDefines({'buildMode': mode.name}))
.buildMode,
mode,
);
}
});
test('resolves localPath against the pubspec', () {
final options = BuildOptions.fromDefines(
_userDefines({'buildMode': 'local', 'localPath': 'lib/libfoo.so'}),
);
expect(options.buildMode, BuildModeEnum.local);
expect(options.localPath, _basePath.resolve('lib/libfoo.so'));
});
test('rejects an unknown build mode instead of fetching', () {
expect(
() => BuildOptions.fromDefines(_userDefines({'buildMode': 'chekout'})),
throwsA(
isA<BuildError>().having(
(e) => e.message,
'message',
allOf(contains("'chekout'"), contains('`checkout`')),
),
),
);
});
test('rejects a build mode that is not a string', () {
expect(
() => BuildOptions.fromDefines(_userDefines({'buildMode': true})),
throwsA(isA<BuildError>()),
);
});
});
group('libc.dart', () {
test('parses glibc versions', () {
expect(parseGlibcVersion('2.35'), equals((2, 35)));
expect(parseGlibcVersion('2.39.9000'), equals((2, 39)));
expect(parseGlibcVersion('unknown'), isNull);
});
test('accepts glibc from prebuiltLinuxGlibc on', () {
final (major, minor) = prebuiltLinuxGlibc;
expect(unsupportedLinuxLibcReason((major, minor)), isNull);
expect(unsupportedLinuxLibcReason((major, minor + 7)), isNull);
expect(unsupportedLinuxLibcReason((major + 1, 0)), isNull);
});
test('rejects older glibc and other C libraries', () {
final (major, minor) = prebuiltLinuxGlibc;
expect(
unsupportedLinuxLibcReason((major, minor - 1)),
contains('require glibc $major.$minor or newer'),
);
expect(unsupportedLinuxLibcReason(null), contains('musl'));
});
test('finds the glibc of this process', () {
final version = currentGlibcVersion();
if (Platform.isLinux) {
// The CI runners use glibc.
expect(version, isNotNull);
expect(unsupportedLinuxLibcReason(version), isNull);
} else {
expect(version, isNull);
}
});
});
group('fetchPrebuiltLibrary', () {
test('throws a BuildError when no prebuilt binary exists for target', () {
final builder = BuildInputBuilder()
..setupShared(
packageRoot: _basePath,
packageName: 'boring',
outputDirectoryShared: _basePath.resolve('.dart_tool/shared/'),
outputFile: _basePath.resolve('.dart_tool/output.json'),
)
..config.setupBuild(linkingEnabled: false)
..addExtension(
CodeAssetExtension(
targetOS: OS.linux,
targetArchitecture: Architecture.riscv64,
linkModePreference: LinkModePreference.dynamic,
),
);
expect(
() => fetchPrebuiltLibrary(builder.build(), static: false),
throwsA(
isA<BuildError>().having(
(e) => e.message,
'message',
allOf(
contains('linux-riscv64'),
contains('buildMode: checkout'),
),
),
),
);
});
});
group('downloadBytes', () {
test(
'retries transient 5xx and connection drops before succeeding',
() async {
var requests = 0;
final server = await _bindTestHttpsServer();
server.listen((request) async {
requests++;
switch (requests) {
case 1:
request.response.statusCode = HttpStatus.gatewayTimeout;
await request.response.close();
case 2:
final socket = await request.response.detachSocket(
writeHeaders: false,
);
socket.destroy();
default:
request.response.add(const [1, 2, 3, 4]);
await request.response.close();
}
});
final delays = <Duration>[];
final bytes = await downloadBytes(
Uri.parse('https://${server.address.host}:${server.port}/asset.bin'),
client: _testHttpsClient(),
delay: (duration) async => delays.add(duration),
);
expect(bytes, [1, 2, 3, 4]);
expect(requests, 3);
expect(delays, [
const Duration(seconds: 1),
const Duration(seconds: 2),
]);
},
);
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();
});
final delays = <Duration>[];
await expectLater(
() => downloadBytes(
Uri.parse(
'https://${server.address.host}:${server.port}/missing.bin',
),
client: _testHttpsClient(),
delay: (duration) async => delays.add(duration),
),
throwsA(
isA<BuildError>().having(
(e) => e.message,
'message',
contains('HTTP 404'),
),
),
);
expect(requests, 1);
expect(delays, isEmpty);
});
test(
'throws BuildError after exhausting retries on persistent 504',
() async {
var requests = 0;
final server = await _bindTestHttpsServer();
server.listen((request) async {
requests++;
request.response.statusCode = HttpStatus.gatewayTimeout;
await request.response.close();
});
final delays = <Duration>[];
await expectLater(
() => downloadBytes(
Uri.parse(
'https://${server.address.host}:${server.port}/flaky.bin',
),
client: _testHttpsClient(),
maxAttempts: 3,
delay: (duration) async => delays.add(duration),
),
throwsA(
isA<BuildError>().having(
(e) => e.message,
'message',
allOf(contains('HTTP 504'), contains('buildMode: checkout')),
),
),
);
expect(requests, 3);
expect(delays, [
const Duration(seconds: 1),
const Duration(seconds: 2),
]);
},
);
test(
'retries 403 rate-limit responses and honors Retry-After capped at 60s',
() async {
var requests = 0;
final server = await _bindTestHttpsServer();
server.listen((request) async {
requests++;
switch (requests) {
case 1:
request.response.statusCode = HttpStatus.forbidden;
request.response.headers.set('x-ratelimit-remaining', '0');
request.response.headers.set(HttpHeaders.retryAfterHeader, '12');
await request.response.close();
case 2:
request.response.statusCode = HttpStatus.tooManyRequests;
request.response.headers.set(HttpHeaders.retryAfterHeader, '300');
await request.response.close();
default:
request.response.add(const [9, 8, 7]);
await request.response.close();
}
});
final delays = <Duration>[];
final bytes = await downloadBytes(
Uri.parse('https://${server.address.host}:${server.port}/throttled'),
client: _testHttpsClient(),
delay: (duration) async => delays.add(duration),
);
expect(bytes, [9, 8, 7]);
expect(requests, 3);
expect(delays, [
const Duration(seconds: 12),
const Duration(seconds: 60),
]);
},
);
test(
'retries 403 with only x-ratelimit-remaining: 0 and 408 using backoff',
() async {
var requests = 0;
final server = await _bindTestHttpsServer();
server.listen((request) async {
requests++;
switch (requests) {
case 1:
request.response.statusCode = HttpStatus.forbidden;
request.response.headers.set('x-ratelimit-remaining', '0');
await request.response.close();
case 2:
request.response.statusCode = HttpStatus.requestTimeout;
await request.response.close();
default:
request.response.add(const [3, 1, 4]);
await request.response.close();
}
});
final delays = <Duration>[];
final bytes = await downloadBytes(
Uri.parse('https://${server.address.host}:${server.port}/limited'),
client: _testHttpsClient(),
delay: (duration) async => delays.add(duration),
);
expect(bytes, [3, 1, 4]);
expect(requests, 3);
expect(delays, [
const Duration(seconds: 1),
const Duration(seconds: 2),
]);
},
);
test(
'does not retry plain 403 responses without rate-limit headers',
() async {
var requests = 0;
final server = await _bindTestHttpsServer();
server.listen((request) async {
requests++;
request.response.statusCode = HttpStatus.forbidden;
await request.response.close();
});
final delays = <Duration>[];
await expectLater(
() => downloadBytes(
Uri.parse('https://${server.address.host}:${server.port}/denied'),
client: _testHttpsClient(),
delay: (duration) async => delays.add(duration),
),
throwsA(
isA<BuildError>().having(
(e) => e.message,
'message',
contains('HTTP 403'),
),
),
);
expect(requests, 1);
expect(delays, isEmpty);
},
);
test(
'does not retry plain 403 responses with duplicate header lines',
() 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 403 Forbidden\r\n'
'x-ratelimit-remaining: 5\r\n'
'x-ratelimit-remaining: 5\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}/denied'),
client: _testHttpsClient(),
delay: (duration) async => delays.add(duration),
),
throwsA(
isA<BuildError>().having(
(e) => e.message,
'message',
contains('HTTP 403'),
),
),
);
expect(requests, 1);
expect(delays, isEmpty);
},
);
test('honors HTTP-date Retry-After headers', () async {
var requests = 0;
final fixedNow = DateTime.utc(2026, 11, 18, 12, 0, 0);
final retryAt = fixedNow.add(const Duration(seconds: 9));
final server = await _bindTestHttpsServer();
server.listen((request) async {
requests++;
if (requests == 1) {
request.response.statusCode = HttpStatus.serviceUnavailable;
request.response.headers.set(
HttpHeaders.retryAfterHeader,
HttpDate.format(retryAt),
);
await request.response.close();
return;
}
request.response.add(const [5, 6]);
await request.response.close();
});
final delays = <Duration>[];
final bytes = await downloadBytes(
Uri.parse('https://${server.address.host}:${server.port}/date-retry'),
client: _testHttpsClient(),
now: () => fixedNow,
delay: (duration) async => delays.add(duration),
);
expect(bytes, [5, 6]);
expect(requests, 2);
expect(delays, [const Duration(seconds: 9)]);
});
test(
'enforces overall totalTimeout deadline across stalled body reads',
() async {
var requests = 0;
final server = await _bindTestHttpsServer();
server.listen((request) async {
requests++;
request.response.bufferOutput = false;
request.response.add(const [1]);
await request.response.flush();
// Leave the response stream open past totalTimeout to simulate a
// stalled download.
});
final delays = <Duration>[];
await expectLater(
() => downloadBytes(
Uri.parse('https://${server.address.host}:${server.port}/stalled'),
client: _testHttpsClient(),
maxAttempts: 4,
totalTimeout: const Duration(milliseconds: 200),
delay: (duration) async => delays.add(duration),
),
throwsA(
isA<BuildError>().having(
(e) => e.message,
'message',
allOf(contains('Timed out'), contains('buildMode: checkout')),
),
),
);
// The client may time out before the handler runs on a loaded machine,
// so only assert that the request was never retried.
expect(requests, lessThanOrEqualTo(1));
expect(delays, isEmpty);
},
);
});
group('fetchHttpWithRetry', () {
test(
'reuses a caller-supplied HttpClient across 404 and retried 504 requests',
() async {
var requests = 0;
final server = await _bindTestHttpsServer();
server.listen((request) async {
requests++;
if (request.uri.path == '/missing.so') {
request.response.statusCode = HttpStatus.notFound;
await request.response.close();
return;
}
if (requests == 2) {
request.response.statusCode = HttpStatus.gatewayTimeout;
await request.response.close();
return;
}
request.response.add(const [42, 43]);
await request.response.close();
});
final client = _testHttpsClient();
final delays = <Duration>[];
final missing = await fetchHttpWithRetry(
Uri.parse(
'https://${server.address.host}:${server.port}/missing.so',
),
client: client,
delay: (duration) async => delays.add(duration),
);
expect(missing.statusCode, HttpStatus.notFound);
expect(missing.bytes, isEmpty);
expect(requests, 1);
expect(delays, isEmpty);
final found = await fetchHttpWithRetry(
Uri.parse(
'https://${server.address.host}:${server.port}/present.so',
),
client: client,
delay: (duration) async => delays.add(duration),
);
expect(found.statusCode, HttpStatus.ok);
expect(found.bytes, [42, 43]);
expect(requests, 3);
expect(delays, [const Duration(seconds: 1)]);
},
);
});
}
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
/// `hooks.user_defines.boring`.
HookInputUserDefines _userDefines(Map<String, Object?> defines) {
final builder = BuildInputBuilder()
..setupShared(
packageRoot: _basePath,
packageName: 'boring',
outputDirectoryShared: _basePath.resolve('.dart_tool/shared/'),
outputFile: _basePath.resolve('.dart_tool/output.json'),
userDefines: PackageUserDefines(
workspacePubspec: PackageUserDefinesSource(
defines: defines,
basePath: _basePath,
),
),
)
..config.setupBuild(linkingEnabled: false);
return builder.build().userDefines;
}