Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.aescbc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Stream<Uint8List> _aesCbcEncryptOrDecrypt(
Stream<List<int>> source,
List<int> iv,
) {
return BoringArena.stream((scope) async* {
return _arenaStream((scope) async* {
assert(key.length == 16 || key.length == 32);
final cipher = key.length == 16
? ssl.EVP_aes_128_cbc()
Expand Down
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.aesctr.dart
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Stream<Uint8List> _aesCtrEncryptOrDecrypt(
// Heavily inspired by Chromium Web Crypto implementation, see:
// https://chromium.googlesource.com/chromium/src/+/43d62c50b705f88c67b14539e91fd8fd017f70c4/components/webcrypto/algorithms/aes_ctr.cc#144

return BoringArena.stream((scope) async* {
return _arenaStream((scope) async* {
assert(counter.length == 16);
assert(key.length == 16 || key.length == 32);
final cipher = key.length == 16
Expand Down
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.aesgcm.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Future<Uint8List> _aesGcmEncryptDecrypt(
// what chrome does, how firefox passes tests. And check if other
// primitives that accept an iv/nonce has size limitations on it.

return BoringArena.using((scope) async {
return _arena((scope) async {
assert(key.length == 16 || key.length == 32);
final aead = key.length == 16
? ssl.EVP_aead_aes_128_gcm()
Expand Down
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.digest.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ abstract class _HashImpl implements HashImpl {

@override
Future<Uint8List> digestStream(Stream<List<int>> data) {
return BoringArena.using((scope) async {
return _arena((scope) async {
final ctx = scope.create(ssl.EVP_MD_CTX_new, ssl.EVP_MD_CTX_free);
// Initialize with hash function
_checkOp(ssl.EVP_DigestInit(ctx, _md) == 1);
Expand Down
16 changes: 8 additions & 8 deletions lib/src/impl_ffi/impl_ffi.ec_common.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ String _ecCurveToJwkCrv(EllipticCurve curve) {

/// Perform some post-import validation for EC keys.
void _validateEllipticCurveKey(_EvpPKey key, EllipticCurve curve) {
return BoringArena.using((scope) {
return _arena((scope) {
_checkData(
ssl.EVP_PKEY_id.invoke(key) == EVP_PKEY_EC,
message: 'key is not an EC key',
Expand Down Expand Up @@ -94,7 +94,7 @@ void _validateEllipticCurveKey(_EvpPKey key, EllipticCurve curve) {
}

_EvpPKey _importPkcs8EcPrivateKey(List<int> keyData, EllipticCurve curve) {
return BoringArena.using((scope) {
return _arena((scope) {
final cbs = scope.cbs(keyData);
final k = ssl.EVP_parse_private_key(cbs);

Expand All @@ -108,7 +108,7 @@ _EvpPKey _importPkcs8EcPrivateKey(List<int> keyData, EllipticCurve curve) {
}

_EvpPKey _importSpkiEcPublicKey(List<int> keyData, EllipticCurve curve) {
return BoringArena.using((scope) {
return _arena((scope) {
final cbs = scope.cbs(keyData);
final k = ssl.EVP_parse_public_key(cbs);

Expand Down Expand Up @@ -169,7 +169,7 @@ _EvpPKey _importJwkEcPrivateOrPublicKey(
// TODO: Reject keys with key_ops in inconsistent with isPrivateKey
// Also in the js implementation...

return BoringArena.using((scope) {
return _arena((scope) {
final ec = ssl.EC_KEY_new_by_curve_name(_ecCurveToNID(curve));
_checkOp(ec.address != 0, fallback: 'internal failure to use curve');
scope.register(ec, ssl.EC_KEY_free);
Expand Down Expand Up @@ -225,7 +225,7 @@ _EvpPKey _importJwkEcPrivateOrPublicKey(

_EvpPKey _importRawEcPublicKey(List<int> keyData, EllipticCurve curve) {
// See: https://chromium.googlesource.com/chromium/src/+/43d62c50b705f88c67b14539e91fd8fd017f70c4/components/webcrypto/algorithms/ec.cc#332
return BoringArena.using((scope) {
return _arena((scope) {
// Create EC_KEY for the curve
final ec = ssl.EC_KEY_new_by_curve_name(_ecCurveToNID(curve));
_checkOp(ec.address != 0, fallback: 'internal failure to use curve');
Expand Down Expand Up @@ -262,7 +262,7 @@ _EvpPKey _importRawEcPublicKey(List<int> keyData, EllipticCurve curve) {
}

Uint8List _exportRawEcPublicKey(_EvpPKey key) {
return BoringArena.using((scope) {
return _arena((scope) {
final ec = ssl.EVP_PKEY_get1_EC_KEY.invoke(key);
_checkOp(ec.address != 0, fallback: 'internal key type invariant error');
scope.register(ec, ssl.EC_KEY_free);
Expand All @@ -287,7 +287,7 @@ Map<String, dynamic> _exportJwkEcPrivateOrPublicKey(
required bool isPrivateKey,
String? jwkUse,
}) {
return BoringArena.using((scope) {
return _arena((scope) {
final ec = ssl.EVP_PKEY_get1_EC_KEY.invoke(key);
_checkOp(ec.address != 0, fallback: 'internal key type invariant error');
scope.register(ec, ssl.EC_KEY_free);
Expand Down Expand Up @@ -338,7 +338,7 @@ Map<String, dynamic> _exportJwkEcPrivateOrPublicKey(
}

KeyPair<_EvpPKey, _EvpPKey> _generateEcKeyPair(EllipticCurve curve) {
return BoringArena.using((scope) {
return _arena((scope) {
final ecPriv = ssl.EC_KEY_new_by_curve_name(_ecCurveToNID(curve));
_checkOp(ecPriv.address != 0, fallback: 'internal failure to use curve');
scope.register(ecPriv, ssl.EC_KEY_free);
Expand Down
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.ecdh.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ final class _EcdhPrivateKeyImpl implements EcdhPrivateKeyImpl {
throw ArgumentError.value(length, 'length', 'must be non-negative');
}

return BoringArena.using((scope) async {
return _arena((scope) async {
final pubEcKey = ssl.EVP_PKEY_get1_EC_KEY.invoke(publicKey._key);
_checkOp(pubEcKey.address != 0, fallback: 'not an ec key');
scope.register(pubEcKey, ssl.EC_KEY_free);
Expand Down
4 changes: 2 additions & 2 deletions lib/src/impl_ffi/impl_ffi.ecdsa.dart
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ Uint8List _convertEcdsaDerSignatureToWebCryptoSignature(
_EvpPKey key,
Uint8List signature,
) {
return BoringArena.using((scope) {
return _arena((scope) {
// TODO: Check if cbs is empty after parsing, consider using ECDSA_SIG_from_bytes instead (like chrome does)
final ecdsa = ssl.ECDSA_SIG_parse(scope.cbs(signature));
_checkOp(
Expand Down Expand Up @@ -139,7 +139,7 @@ Uint8List? _convertEcdsaWebCryptoSignatureToDerSignature(
_EvpPKey key,
List<int> signature,
) {
return BoringArena.using((scope) {
return _arena((scope) {
// Read EC key and get the number of bytes required to encode R and S.
final ec = ssl.EVP_PKEY_get1_EC_KEY.invoke(key);
_checkOp(ec.address != 0, message: 'internal key type invariant violation');
Expand Down
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.hkdf.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ final class _HkdfSecretKeyImpl implements HkdfSecretKeyImpl {
throw operationError(lengthTooLong);
}

return BoringArena.using((scope) async {
return _arena((scope) async {
final out = scope<ffi.Uint8>(lengthInBytes);
final r = ssl.HKDF(
out,
Expand Down
4 changes: 2 additions & 2 deletions lib/src/impl_ffi/impl_ffi.hmac.dart
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ final class _HmacSecretKeyImpl implements HmacSecretKeyImpl {

@override
Future<Uint8List> signStream(Stream<List<int>> data) {
return BoringArena.using((scope) async {
return _arena((scope) async {
final ctx = scope.create(ssl.HMAC_CTX_new, ssl.HMAC_CTX_free);
_checkOpIsOne(
ssl.HMAC_Init_ex(
Expand Down Expand Up @@ -180,7 +180,7 @@ final class _HmacSecretKeyImpl implements HmacSecretKeyImpl {
if (signature.length != other.length) {
return false;
}
return BoringArena.using((scope) {
return _arena((scope) {
final cmp = ssl.CRYPTO_memcmp(
scope.copyBytes(signature),
scope.copyBytes(other),
Expand Down
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.pbkdf2.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ final class _Pbkdf2SecretKeyImpl implements Pbkdf2SecretKeyImpl {

final lengthInBytes = length ~/ 8;

return BoringArena.using((scope) async {
return _arena((scope) async {
final out = scope<ffi.Uint8>(lengthInBytes);
_checkOpIsOne(
await _PKCS5_PBKDF2_HMAC(
Expand Down
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.random.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ final class _RandomImpl implements RandomImpl {

@override
void fillRandomBytes(TypedData destination) {
return BoringArena.using((scope) {
return _arena((scope) {
final dest = destination.buffer.asUint8List(
destination.offsetInBytes,
destination.lengthInBytes,
Expand Down
10 changes: 5 additions & 5 deletions lib/src/impl_ffi/impl_ffi.rsa_common.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
part of 'impl_ffi.dart';

_EvpPKey _importPkcs8RsaPrivateKey(List<int> keyData) {
return BoringArena.using((scope) {
return _arena((scope) {
final cbs = scope.cbs(keyData);
final k = ssl.EVP_parse_private_key(cbs);

Expand All @@ -39,7 +39,7 @@ _EvpPKey _importPkcs8RsaPrivateKey(List<int> keyData) {
}

_EvpPKey _importSpkiRsaPublicKey(List<int> keyData) {
return BoringArena.using((scope) {
return _arena((scope) {
final cbs = scope.cbs(keyData);
final k = ssl.EVP_parse_public_key(cbs);

Expand Down Expand Up @@ -68,7 +68,7 @@ _EvpPKey _importJwkRsaPrivateOrPublicKey(
required String expectedAlg,
required String expectedUse,
}) {
return BoringArena.using((scope) {
return _arena((scope) {
void checkJwk(
bool condition,
String prop, [
Expand Down Expand Up @@ -175,7 +175,7 @@ Map<String, dynamic> _exportJwkRsaPrivateOrPublicKey(
required String jwkAlg,
required String jwkUse,
}) {
return BoringArena.using((scope) {
return _arena((scope) {
final rsa = ssl.EVP_PKEY_get1_RSA.invoke(key);
_checkOp(rsa.address != 0, fallback: 'internal key type error');
scope.register(rsa, ssl.RSA_free);
Expand Down Expand Up @@ -258,7 +258,7 @@ Future<KeyPair<_EvpPKey, _EvpPKey>> _generateRsaKeyPair(
throw UnsupportedError('publicExponent is not supported, try 3 or 65537');
}

return BoringArena.using((scope) async {
return _arena((scope) async {
// Generate private RSA key
final privRSA = scope.createRSA();

Expand Down
2 changes: 1 addition & 1 deletion lib/src/impl_ffi/impl_ffi.rsaoaep.dart
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ Future<Uint8List> _rsaOaepeEncryptOrDecryptBytes(
List<int> data, {
List<int>? label,
}) async {
return BoringArena.using((scope) {
return _arena((scope) {
final ctx = scope.create(
() => ssl.EVP_PKEY_CTX_new.invoke(key, ffi.nullptr),
ssl.EVP_PKEY_CTX_free,
Expand Down
29 changes: 25 additions & 4 deletions lib/src/impl_ffi/impl_ffi.utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,27 @@ extension type _EvpPKey._(NativeHandle<EVP_PKEY> _handle)
// failing call, using _checkOp / _checkData or ERR_clear_error, rather than
// deferring it to a `finally` or BoringArena release that may run after an
// `await`. In tests, checkErrorStack fails if errors are left behind.
//
// Every package using package:boring on a thread shares its queue, so other
// code may leave errors behind, which _checkOp / _checkData would report for
// webcrypto's next failure. So run all BoringSSL calls in _arena or
// _arenaStream, which clear the queue first.

/// Runs [computation] with a new [BoringArena], like [BoringArena.using],
/// after clearing errors that other code left on BoringSSL's error queue.
R _arena<R>(R Function(BoringArena scope) computation) {
ssl.ERR_clear_error();
return BoringArena.using(computation);
}

/// Returns the stream of [computation] with a new [BoringArena], like
/// [BoringArena.stream], after clearing errors that other code left on
/// BoringSSL's error queue when the stream is listened to.
Stream<T> _arenaStream<T>(Stream<T> Function(BoringArena scope) computation) =>
BoringArena.stream((scope) {
ssl.ERR_clear_error();
return computation(scope);
});

/// Throw [OperationError] if [condition] is `false`.
///
Expand Down Expand Up @@ -151,7 +172,7 @@ Future<Uint8List> _signStream(
Stream<List<int>> data, {
void Function(ffi.Pointer<EVP_PKEY_CTX> ctx)? config,
}) {
return BoringArena.using((scope) async {
return _arena((scope) async {
final ctx = scope.create(ssl.EVP_MD_CTX_new, ssl.EVP_MD_CTX_free);
final pctx = config != null
? scope<ffi.Pointer<EVP_PKEY_CTX>>()
Expand Down Expand Up @@ -186,7 +207,7 @@ Future<bool> _verifyStream(
Stream<List<int>> data, {
void Function(ffi.Pointer<EVP_PKEY_CTX> ctx)? config,
}) {
return BoringArena.using((scope) async {
return _arena((scope) async {
// Create and initialize verification context
final ctx = scope.create(ssl.EVP_MD_CTX_new, ssl.EVP_MD_CTX_free);
final pctx = config != null
Expand Down Expand Up @@ -221,7 +242,7 @@ Future<bool> _verifyStream(

/// Export private [key] as PKCS8.
Uint8List _exportPkcs8Key(_EvpPKey key) {
return BoringArena.using((scope) {
return _arena((scope) {
final cbb = scope.cbb();
_checkOpIsOne(ssl.EVP_marshal_private_key.invoke(cbb, key));
return cbb.toBytes();
Expand All @@ -230,7 +251,7 @@ Uint8List _exportPkcs8Key(_EvpPKey key) {

/// Export public [key] as SPKI.
Uint8List _exportSpkiKey(_EvpPKey key) {
return BoringArena.using((scope) {
return _arena((scope) {
final cbb = scope.cbb();
_checkOpIsOne(ssl.EVP_marshal_public_key.invoke(cbb, key));
return cbb.toBytes();
Expand Down
64 changes: 64 additions & 0 deletions test/ffi/stale_boringssl_errors_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

@TestOn('vm')
library;

import 'dart:ffi' as ffi;

import 'package:boring/bindings.dart' as ssl;
import 'package:test/test.dart';
import 'package:webcrypto/webcrypto.dart';

/// Leaves an `EC_R_UNKNOWN_GROUP` error on BoringSSL's error queue, like
/// another package using package:boring on this thread might.
void _leaveStaleError() {
ssl.ERR_clear_error();
expect(ssl.EC_KEY_new_by_curve_name(-1), equals(ffi.nullptr));
expect(ssl.ERR_peek_error(), isNot(0));
}

void main() {
tearDown(ssl.ERR_clear_error);

test('errors left by other code are not reported for RSA imports', () async {
_leaveStaleError();
await expectLater(
RsaOaepPrivateKey.importPkcs8Key([1, 2, 3], Hash.sha256),
throwsA(
isA<FormatException>().having(
(e) => e.message,
'message',
allOf(contains('DECODE_ERROR'), isNot(contains('UNKNOWN_GROUP'))),
),
),
);
expect(ssl.ERR_peek_error(), equals(0));
});

test('errors left by other code are not reported for EC imports', () async {
_leaveStaleError();
await expectLater(
EcdhPublicKey.importSpkiKey([1, 2, 3], EllipticCurve.p256),
throwsA(
isA<FormatException>().having(
(e) => e.message,
'message',
isNot(contains('UNKNOWN_GROUP')),
),
),
);
expect(ssl.ERR_peek_error(), equals(0));
});
}
Loading