feat(crypto): harden Crypto primitives and add optional CryptoAsync adapter

This commit is contained in:
faumaray committed 2026-11-25 06:28:50 +03:00
1 parent 8a1c15f9c0
commit eb42228604
14 files changed
+2448 -90

No files matched your search

+368
View File
@@ -0,0 +1,368 @@
#include <Void/Crypto/Crypto.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <string>
#include <string_view>
#include <vector>
namespace
{
int hex_nibble(char c)
{
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
}
std::vector<std::byte> from_hex(std::string_view hex)
{
Void::Testing::require(hex.size() % 2 == 0);
std::vector<std::byte> out;
out.reserve(hex.size() / 2);
for (std::size_t i = 0; i < hex.size(); i += 2) {
const int hi = hex_nibble(hex[i]);
const int lo = hex_nibble(hex[i + 1]);
Void::Testing::require(hi >= 0 && lo >= 0);
out.push_back(static_cast<std::byte>((hi << 4) | lo));
}
return out;
}
std::string to_hex(std::span<const std::byte> data)
{
static constexpr char kHex[] = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (const std::byte b : data) {
const auto v = static_cast<unsigned char>(b);
out.push_back(kHex[v >> 4]);
out.push_back(kHex[v & 0x0F]);
}
return out;
}
std::span<const std::byte> as_bytes(std::string_view text)
{
return std::as_bytes(std::span{text.data(), text.size()});
}
} // namespace
Void::Testing::Test crypto_hasher_state_poisoning_and_provider_isolation()
{
using namespace Void::Crypto;
auto h = Hasher::create(HashAlgorithm::Sha256);
Void::Testing::require(h.has_value());
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Ready));
Void::Testing::require(h->update("ab").has_value());
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Updating));
// Inject mid-stream update failure -> hasher is permanently poisoned.
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::hash_update,
CryptoErrorCode::backend_error, 0}};
auto bad = h->update("c");
Void::Testing::require(!bad.has_value());
Void::Testing::expect_eq(bad.error().code().domain,
Void::Result::kCryptoErrorDomain);
Void::Testing::expect_eq(
bad.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::backend_error));
}
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::Failed));
auto retry_update = h->update("d");
Void::Testing::require(!retry_update.has_value());
Void::Testing::expect_eq(
retry_update.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_state));
auto retry_finalize = h->finalize();
Void::Testing::require(!retry_finalize.has_value());
Void::Testing::expect_eq(
retry_finalize.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_state));
// Moved-from state reports MovedFrom and fails cleanly.
Hasher moved = std::move(*h);
Void::Testing::expect_eq(static_cast<int>(h->state()),
static_cast<int>(HasherState::MovedFrom));
Void::Testing::expect(!h->update("x").has_value());
Void::Testing::expect(!moved.finalize().has_value());
// Per-context unavailable provider fails without breaking subsequent
// default-provider operations.
ProviderOptions bad_provider{.property_query = "provider=nonexistent_void"};
auto unavailable = Hasher::create(HashAlgorithm::Sha256, bad_provider);
Void::Testing::require(!unavailable.has_value());
Void::Testing::expect_eq(
unavailable.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::provider_error));
auto good = sha256("abc");
Void::Testing::require(good.has_value());
Void::Testing::expect_eq(
to_hex(*good),
std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f"
"20015ad"});
}
Void::Testing::Test crypto_ed25519_signing_vectors_and_boundaries()
{
using namespace Void::Crypto;
struct Rfc8032Vector {
std::string_view seed_hex;
std::string_view pub_hex;
std::string_view msg_hex;
std::string_view sig_hex;
};
const std::array<Rfc8032Vector, 3> vectors = {{
{"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
"",
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155"
"5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"},
{"4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
"3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
"72",
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da"
"085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"},
{"c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
"fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
"af82",
"6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac"
"18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"},
}};
for (const auto& vec : vectors) {
const auto seed = from_hex(vec.seed_hex);
const auto expected_pub = from_hex(vec.pub_hex);
const auto msg = from_hex(vec.msg_hex);
const auto expected_sig = from_hex(vec.sig_hex);
auto key = Ed25519PrivateKey::from_raw_seed(seed);
Void::Testing::require(key.has_value());
auto pub = key->public_key();
Void::Testing::require(pub.has_value());
Void::Testing::expect_eq(to_hex(pub->view()), std::string{vec.pub_hex});
auto exported = key->export_raw_seed();
Void::Testing::require(exported.has_value());
Void::Testing::expect(constant_time_equal(exported->view(), seed));
exported->clear();
Void::Testing::expect(!exported->valid());
Void::Testing::expect(exported->view().empty());
auto sig = sign_ed25519(msg, *key);
Void::Testing::require(sig.has_value());
Void::Testing::expect_eq(to_hex(sig->view()), std::string{vec.sig_hex});
auto verified = verify_ed25519(msg, *sig, *pub);
Void::Testing::require(verified.has_value());
Void::Testing::expect(*verified);
// Flipping a single signature bit yields false, NOT an error.
auto tampered_sig = *sig;
tampered_sig.bytes[0] ^= std::byte{0x01};
auto bad_verify = verify_ed25519(msg, tampered_sig, *pub);
Void::Testing::require(bad_verify.has_value());
Void::Testing::expect(!*bad_verify);
}
// Key generation round-trip.
auto generated = Ed25519PrivateKey::generate();
Void::Testing::require(generated.has_value());
auto gen_pub = generated->public_key();
Void::Testing::require(gen_pub.has_value());
auto gen_sig = sign_ed25519(as_bytes("hello ed25519"), *generated);
Void::Testing::require(gen_sig.has_value());
auto gen_ok =
verify_ed25519(as_bytes("hello ed25519"), *gen_sig, *gen_pub);
Void::Testing::require(gen_ok.has_value());
Void::Testing::expect(*gen_ok);
// Invalid sizes near boundaries must fail with typed invalid_argument.
for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) {
std::vector<std::byte> bad_key(bad_key_len, std::byte{0x11});
auto r = verifyEd25519({}, gen_sig->view(), bad_key);
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
auto import_r = Ed25519PrivateKey::from_raw_seed(bad_key);
Void::Testing::require(!import_r.has_value());
Void::Testing::expect_eq(
import_r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_key_size));
}
for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) {
std::vector<std::byte> bad_sig(bad_sig_len, std::byte{0x22});
auto r = verifyEd25519({}, bad_sig, gen_pub->view());
Void::Testing::require(!r.has_value());
Void::Testing::expect_eq(
r.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_signature_size));
}
// Oversized message (>16 MiB) rejected before OpenSSL call.
std::vector<std::byte> huge(CryptoLimits::kMaxOneShotMessageBytes + 1U,
std::byte{0});
auto huge_sign = sign_ed25519(huge, *generated);
Void::Testing::require(!huge_sign.has_value());
Void::Testing::expect_eq(
huge_sign.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::message_too_large));
auto huge_verify = verify_ed25519(huge, *gen_sig, *gen_pub);
Void::Testing::require(!huge_verify.has_value());
Void::Testing::expect_eq(
huge_verify.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::message_too_large));
// Provider fault returns error without leaking secret key material.
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::ed25519_sign,
CryptoErrorCode::provider_error, 0}};
auto failed = sign_ed25519(as_bytes("secret-free"), *generated);
Void::Testing::require(!failed.has_value());
Void::Testing::expect_eq(
failed.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::provider_error));
}
}
Void::Testing::Test crypto_hmac_sha256_and_hkdf_sha256_vectors_and_guards()
{
using namespace Void::Crypto;
// RFC 4231 Case 1
{
const std::vector<std::byte> key(20, std::byte{0x0b});
auto mac = hmac_sha256(key, as_bytes("Hi There"));
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e93"
"76c2e32cff7"});
}
// RFC 4231 Case 2
{
auto mac = hmac_sha256(as_bytes("Jefe"),
as_bytes("what do ya want for nothing?"));
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec5"
"8b964ec3843"});
}
// RFC 4231 Case 3
{
const std::vector<std::byte> key(20, std::byte{0xaa});
const std::vector<std::byte> msg(50, std::byte{0xdd});
auto mac = hmac_sha256(key, msg);
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(
to_hex(*mac),
std::string{"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635"
"514ced565fe"});
}
// Empty key and empty message work cleanly.
{
auto mac = hmac_sha256({}, {});
Void::Testing::require(mac.has_value());
Void::Testing::expect_eq(mac->size(), HmacSha256Size);
}
// RFC 5869 Appendix A Case 1
{
const std::vector<std::byte> ikm(22, std::byte{0x0b});
const auto salt = from_hex("000102030405060708090a0b0c");
const auto info = from_hex("f0f1f2f3f4f5f6f7f8f9");
std::array<std::byte, 42> okm{};
auto r = hkdf_sha256(ikm, salt, info, okm);
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(
to_hex(okm),
std::string{"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02"
"d56ecc4c5bf34007208d5b887185865"});
}
// RFC 5869 Appendix A Case 3 (empty salt & info)
{
const std::vector<std::byte> ikm(22, std::byte{0x0b});
std::array<std::byte, 42> okm{};
auto r = hkdf_sha256(ikm, {}, {}, okm);
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(
to_hex(okm),
std::string{"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454"
"e5f3c738d2d9d201395faa4b61a96c8"});
}
// HKDF guards: empty output, oversized (>4 KiB) without mutating buffer,
// overlapping spans rejected, fault wipes destination.
{
const std::vector<std::byte> ikm(16, std::byte{0x42});
std::vector<std::byte> empty_out;
auto r_empty = hkdf_sha256(ikm, {}, {}, empty_out);
Void::Testing::require(!r_empty.has_value());
Void::Testing::expect_eq(
r_empty.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::invalid_argument));
std::vector<std::byte> too_large(CryptoLimits::kMaxHkdfOutputBytes + 1U,
std::byte{0x7A});
auto r_large = hkdf_sha256(ikm, {}, {}, too_large);
Void::Testing::require(!r_large.has_value());
Void::Testing::expect_eq(
r_large.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::output_too_large));
Void::Testing::expect(
std::all_of(too_large.begin(), too_large.end(),
[](std::byte b) { return b == std::byte{0x7A}; }));
std::array<std::byte, 64> shared{};
shared.fill(std::byte{0x55});
auto r_overlap =
hkdf_sha256(std::span{shared}.subspan(0, 32), {}, {},
std::span{shared}.subspan(16, 32));
Void::Testing::require(!r_overlap.has_value());
Void::Testing::expect_eq(
r_overlap.error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::overlapping_buffers));
std::array<std::byte, 32> wiped{};
wiped.fill(std::byte{0xCC});
{
ScopedFaultGuard fault{
FaultConfig{FaultOperation::hkdf,
CryptoErrorCode::provider_error, 0}};
auto r_fault = hkdf_sha256(ikm, {}, {}, wiped);
Void::Testing::require(!r_fault.has_value());
}
Void::Testing::expect(
std::all_of(wiped.begin(), wiped.end(),
[](std::byte b) { return b == std::byte{0x00}; }));
}
// constant_time_equal checks
const auto a = from_hex("01020304");
const auto b = from_hex("01020304");
const auto c = from_hex("01020305");
const auto d = from_hex("010203");
Void::Testing::expect(constant_time_equal(a, b));
Void::Testing::expect(!constant_time_equal(a, c));
Void::Testing::expect(!constant_time_equal(a, d));
}
@@ -0,0 +1,333 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Crypto/AsyncHash.hpp>
#include <Void/IO/Driver.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <array>
#include <atomic>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <optional>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
namespace
{
std::span<const std::byte> as_bytes(std::string_view text)
{
return std::as_bytes(std::span{text.data(), text.size()});
}
struct ScopedTempDir {
std::filesystem::path path;
ScopedTempDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
const auto ts =
std::chrono::steady_clock::now().time_since_epoch().count();
path = std::filesystem::temp_directory_path() /
("void_crypto_async_" + std::to_string(ts) + "_" +
std::to_string(id));
std::filesystem::create_directories(path);
}
~ScopedTempDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
Void::Coro::Task<void> run_hash_stream(
Void::Crypto::HashAlgorithm alg, Void::IO::Driver& driver,
Void::IO::ByteStream& stream, Void::Async::OperationOptions op,
Void::CryptoAsync::StreamHashOptions hash_opts,
std::optional<Void::Result::Result<Void::Crypto::Digest>>& out)
{
out = co_await Void::CryptoAsync::hash_stream(
alg, driver, stream, std::move(op), std::move(hash_opts));
}
Void::Coro::Task<void> run_hash_file(
Void::CryptoAsync::AsyncFileHasher& hasher,
Void::Crypto::HashAlgorithm alg, std::filesystem::path path,
Void::Async::OperationOptions op,
std::optional<Void::Result::Result<Void::Crypto::Digest>>& out,
std::atomic<int>* done_counter = nullptr)
{
out = co_await hasher.hash_file(alg, std::move(path), std::move(op));
if (done_counter != nullptr) {
done_counter->fetch_add(1, std::memory_order_release);
}
}
} // namespace
Void::Testing::Test crypto_async_hash_stream_eof_errors_and_cancellation()
{
using namespace Void::Crypto;
using namespace Void::CryptoAsync;
Void::Async::ManualExecutor exec;
Void::Time::ManualClock clock;
Void::IO::BackendOptions opts{};
opts.preference = Void::IO::BackendPreference::mock;
opts.limits.max_owned_buffer_bytes = 128 * 1024;
auto drv = Void::IO::Driver::create(exec, opts, clock);
Void::Testing::require(drv.has_value());
auto* mock = (*drv)->mock_controller();
Void::Testing::require(mock != nullptr);
// 1. Multi-chunk stream matches sha256("hello async world").
{
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(
run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {},
StreamHashOptions{.chunk_bytes = 8}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
Void::Testing::require(
mock->complete_read(*stream, as_bytes("hello "), false));
(void)exec.drain();
Void::Testing::require(
mock->complete_read(*stream, as_bytes("async "), false));
(void)exec.drain();
Void::Testing::require(
mock->complete_read(*stream, as_bytes("world"), true));
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && outcome->has_value());
auto expected = sha256("hello async world");
Void::Testing::require(expected.has_value());
Void::Testing::expect_eq(**outcome, *expected);
}
// 2. Partial read then error must never produce a digest.
{
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(
run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {},
StreamHashOptions{.chunk_bytes = 16}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
Void::Testing::require(
mock->complete_read(*stream, as_bytes("partial"), false));
(void)exec.drain();
Void::Testing::require(mock->fail_read(
*stream, Void::IO::make_io_error(Void::IO::IoErrorCode::os_error,
"injected read failure")));
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && !outcome->has_value());
Void::Testing::expect_eq(
outcome->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::io_error));
}
// 3. Stop requested racing with EOF completion must not return a digest.
{
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
std::stop_source stop_src;
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(run_hash_stream(
HashAlgorithm::Sha256, **drv, *stream,
Void::Async::OperationOptions{.stop = stop_src.get_token()},
StreamHashOptions{.chunk_bytes = 16}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
auto tok = mock->try_acquire_read(*stream);
Void::Testing::require(tok.has_value());
stop_src.request_stop();
(void)mock->finish_read_data(*tok, as_bytes("done"), true);
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && !outcome->has_value());
Void::Testing::expect_eq(
outcome->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::cancelled));
}
// 4. Deadline expiry between chunks returns timeout.
{
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
const auto deadline = clock.now() + std::chrono::seconds{5};
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(run_hash_stream(
HashAlgorithm::Sha256, **drv, *stream,
Void::Async::OperationOptions{.deadline = deadline},
StreamHashOptions{.chunk_bytes = 16}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
Void::Testing::require(
clock.advance(std::chrono::seconds{10}).has_value());
Void::Testing::require(
mock->complete_read(*stream, as_bytes("chunk1"), false));
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && !outcome->has_value());
Void::Testing::expect_eq(
outcome->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::timeout));
}
// 5. Buffer budget exhaustion returns resource_exhausted before reading.
{
auto hold = (*drv)->allocate_buffer(128 * 1024);
Void::Testing::require(hold.has_value());
auto stream = (*drv)->create_mock_stream();
Void::Testing::require(stream.has_value());
std::optional<Void::Result::Result<Digest>> outcome;
Void::Async::TaskScope scope{exec};
auto handle = scope.spawn(
run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {},
StreamHashOptions{.chunk_bytes = 1024}, outcome));
Void::Testing::require(handle.has_value());
(void)exec.drain();
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outcome.has_value() && !outcome->has_value());
Void::Testing::expect_eq(
outcome->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::resource_exhausted));
}
Void::Testing::require((*drv)->shutdown_and_join().has_value());
}
Void::Testing::Test crypto_async_file_hasher_bounds_and_shutdown()
{
using namespace Void::Crypto;
using namespace Void::CryptoAsync;
ScopedTempDir tmp;
const auto file_path = tmp.path / "sample.bin";
{
std::ofstream out{file_path, std::ios::binary};
std::string payload(200 * 1024, 'V');
out.write(payload.data(), static_cast<std::streamsize>(payload.size()));
}
auto sync_digest = sha256File(file_path);
Void::Testing::require(sync_digest.has_value());
Void::Async::ManualExecutor exec;
AsyncFileHasher hasher{
exec,
FileHasherOptions{.max_concurrent = 2,
.max_waiting = 4,
.buffer_budget_bytes = 256 * 1024,
.chunk_bytes = 16 * 1024}};
std::array<std::optional<Void::Result::Result<Digest>>, 4> results{};
std::atomic<int> done_count{0};
{
Void::Async::TaskScope scope{exec};
for (std::size_t i = 0; i < results.size(); ++i) {
auto h = scope.spawn(run_hash_file(hasher, HashAlgorithm::Sha256,
file_path, {}, results[i],
&done_count));
Void::Testing::require(h.has_value());
}
const auto deadline =
std::chrono::steady_clock::now() + std::chrono::seconds{10};
while (done_count.load(std::memory_order_acquire) < 4 &&
std::chrono::steady_clock::now() < deadline) {
if (exec.drain() == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
Void::Testing::require(scope.join_pumping(exec).has_value());
}
for (const auto& r : results) {
Void::Testing::require(r.has_value() && r->has_value());
Void::Testing::expect_eq(**r, *sync_digest);
}
// Pre-cancelled admission returns cancelled without starting.
{
std::stop_source ss;
ss.request_stop();
std::optional<Void::Result::Result<Digest>> cancelled;
Void::Async::TaskScope scope{exec};
auto h = scope.spawn(run_hash_file(
hasher, HashAlgorithm::Sha256, file_path,
Void::Async::OperationOptions{.stop = ss.get_token()}, cancelled));
Void::Testing::require(h.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(cancelled.has_value() && !cancelled->has_value());
Void::Testing::expect_eq(
cancelled->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::cancelled));
}
// Shutdown stops admission cleanly and leaves zero active/reserved budget.
Void::Testing::require(hasher.close_and_join().has_value());
const auto st = hasher.stats();
Void::Testing::expect(st.closing);
Void::Testing::expect_eq(st.active, 0U);
Void::Testing::expect_eq(st.reserved_buffer_bytes, 0U);
{
std::optional<Void::Result::Result<Digest>> after_close;
Void::Async::TaskScope scope{exec};
auto h = scope.spawn(run_hash_file(hasher, HashAlgorithm::Sha256,
file_path, {}, after_close));
Void::Testing::require(h.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(after_close.has_value() &&
!after_close->has_value());
Void::Testing::expect_eq(
after_close->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::closed));
}
// Budget smaller than chunk_bytes fails with resource_exhausted.
AsyncFileHasher tiny{
exec,
FileHasherOptions{.max_concurrent = 1,
.max_waiting = 1,
.buffer_budget_bytes = 1024,
.chunk_bytes = 4096}};
{
std::optional<Void::Result::Result<Digest>> budget_err;
Void::Async::TaskScope scope{exec};
auto h = scope.spawn(run_hash_file(tiny, HashAlgorithm::Sha256,
file_path, {}, budget_err));
Void::Testing::require(h.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(budget_err.has_value() &&
!budget_err->has_value());
Void::Testing::expect_eq(
budget_err->error().code().value,
static_cast<std::int32_t>(CryptoErrorCode::resource_exhausted));
}
Void::Testing::require(tiny.close_and_join().has_value());
}