feat(security): add SecureBuffer, VSEC envelopes, authorization, and SecurityAsync Authenticator

This commit is contained in:
faumaray committed 2026-11-25 20:44:31 +03:00
1 parent eb42228604
commit 713d2dc656
20 files changed
+4070 -43

No files matched your search

@@ -0,0 +1,322 @@
#include <Void/Security/Authorization.hpp>
#include <Void/Security/Envelope.hpp>
#include <Void/Security/SecureBuffer.hpp>
#include <Void/Security/Security.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <array>
#include <cstddef>
#include <string>
#include <vector>
Void::Testing::Test security_secure_buffer_wipe_and_lock_policies()
{
using namespace Void::Security;
const auto wiped_before = SecureBuffer::total_wiped_bytes();
{
auto buf = SecureBuffer::from_string("top-secret-key-material");
Void::Testing::require(buf.has_value());
Void::Testing::expect_eq(buf->string_view(),
std::string_view{"top-secret-key-material"});
Void::Testing::expect(!buf->is_locked());
auto moved = std::move(*buf);
Void::Testing::expect(buf->empty());
Void::Testing::expect_eq(moved.size(), 23U);
}
Void::Testing::expect(SecureBuffer::total_wiped_bytes() >=
wiped_before + 23U);
// LockedRequired fails closed on locked allocation failure (no downgrade).
{
ScopedFaultGuard fault{
FaultConfig{FaultOperation::locked_alloc,
SecurityErrorCode::locked_memory_unavailable, 0}};
auto required = SecureBuffer::allocate(64, LockPolicy::LockedRequired);
Void::Testing::require(!required.has_value());
Void::Testing::expect_eq(
required.error().code().value,
static_cast<std::int32_t>(
SecurityErrorCode::locked_memory_unavailable));
auto optional = SecureBuffer::allocate(64, LockPolicy::LockedOptional);
Void::Testing::require(optional.has_value());
Void::Testing::expect(!optional->is_locked());
}
// Oversized allocation rejected before touching backend.
auto huge =
SecureBuffer::allocate(SecurityLimits::kMaxSecretPlaintextBytes + 1U);
Void::Testing::require(!huge.has_value());
Void::Testing::expect_eq(
huge.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::input_too_large));
}
Void::Testing::Test security_input_caps_cost_budget_and_fault_seams()
{
using namespace Void::Security;
// Excessive Argon2id memory/iteration cost rejected BEFORE allocation.
const std::string malicious_mem =
"$argon2id$v=19$m=4194304,t=3,p=1$AAAAAAAAAAAAAAAAAAAAAA$"
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
auto parsed = parse_argon2id_cost(malicious_mem);
Void::Testing::require(parsed.has_value());
Void::Testing::expect_eq(parsed->memory_kib, 4194304ULL);
PasswordVerifyBudget tight_budget{
.max_memory_bytes = 64ULL * 1024ULL * 1024ULL,
.max_iterations = 4,
.max_parallelism = 2,
};
auto rejected = verify_password_budgeted("pw", malicious_mem, tight_budget);
Void::Testing::require(!rejected.has_value());
Void::Testing::expect_eq(
rejected.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::cost_budget_exceeded));
// Malformed hash corpus rejected cleanly.
for (const std::string_view bad : {
"",
"$argon2i$v=19$m=65536,t=2,p=1$aaaa$bbbb",
"$argon2id$v=18$m=65536,t=2,p=1$aaaa$bbbb",
"$argon2id$v=19$m=0,t=2,p=1$aaaa$bbbb",
"$argon2id$v=19$m=99999999999999999999,t=2,p=1$aaaa$bbbb",
"$argon2id$v=19$m=65536,t=2$aaaa$bbbb",
"$argon2id$v=19$m=65536,t=2,p=1$aaaa$",
}) {
Void::Testing::expect(!parse_argon2id_cost(bad).has_value());
}
// Input length caps: >1 KiB password, >512 B token.
const std::string long_pw(SecurityLimits::kMaxPasswordBytes + 1U, 'p');
auto pw_err = hash_password(long_pw, PasswordHashStrength::Interactive);
Void::Testing::require(!pw_err.has_value());
Void::Testing::expect_eq(
pw_err.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::input_too_large));
const std::string long_tok(SecurityLimits::kMaxTokenBytes + 1U, 't');
auto tok_err = hash_token(long_tok);
Void::Testing::require(!tok_err.has_value());
Void::Testing::expect_eq(
tok_err.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::input_too_large));
// Sodium init / randomness failure publishes no token or key.
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::sodium_init,
SecurityErrorCode::backend_error, 0}};
Void::Testing::expect(!random_token().has_value());
Void::Testing::expect(!random_secret_key().has_value());
}
{
ScopedFaultGuard fault{FaultConfig{FaultOperation::random_bytes,
SecurityErrorCode::backend_error, 0}};
Void::Testing::expect(!random_token().has_value());
Void::Testing::expect(!random_secret_key().has_value());
}
// Legacy envelope exact byte layout preserved: 24B nonce + 16B MAC + pt.
auto key = random_secret_key();
Void::Testing::require(key.has_value());
const std::vector<unsigned char> pt{'v', 'o', 'i', 'd'};
auto legacy = seal_secret(pt, *key);
Void::Testing::require(legacy.has_value());
Void::Testing::expect_eq(legacy->size(),
secret_nonce_bytes + secret_authentication_bytes +
pt.size());
auto opened = open_secret(*legacy, *key);
Void::Testing::require(opened.has_value());
Void::Testing::expect_eq(*opened, pt);
}
Void::Testing::Test security_versioned_envelope_rotation_and_no_legacy_fallback()
{
using namespace Void::Security;
SecretKeyRing ring;
Void::Testing::require(ring.generate_and_add_key("k1", true).has_value());
Void::Testing::expect_eq(ring.active_key_id().value_or(""),
std::string{"k1"});
const std::vector<unsigned char> pt{'a', 'p', 'i', '-', 'k', 'e', 'y'};
const std::vector<unsigned char> aad{'t', 'e', 'n', 'a', 'n', 't', ':', '1'};
const std::vector<unsigned char> wrong_aad{'t', 'e', 'n', 'a',
'n', 't', ':', '2'};
auto env_k1 = ring.seal(pt, aad);
Void::Testing::require(env_k1.has_value());
auto hdr = inspect_envelope(*env_k1);
Void::Testing::require(hdr.has_value());
Void::Testing::expect_eq(hdr->version, kEnvelopeVersionV1);
Void::Testing::expect_eq(hdr->algorithm, kEnvelopeAlgXChaCha20Poly1305Ietf);
Void::Testing::expect_eq(hdr->key_id, std::string{"k1"});
Void::Testing::expect_eq(hdr->plaintext_size,
static_cast<std::uint32_t>(pt.size()));
// Rotate to k2: new writes use k2, old k1 envelopes still decrypt.
Void::Testing::require(ring.generate_and_add_key("k2", true).has_value());
Void::Testing::expect_eq(ring.active_key_id().value_or(""),
std::string{"k2"});
auto env_k2 = ring.seal(pt, aad);
Void::Testing::require(env_k2.has_value());
auto hdr2 = inspect_envelope(*env_k2);
Void::Testing::require(hdr2.has_value());
Void::Testing::expect_eq(hdr2->key_id, std::string{"k2"});
auto dec1 = ring.open(*env_k1, aad);
auto dec2 = ring.open(*env_k2, aad);
Void::Testing::require(dec1.has_value() && dec2.has_value());
Void::Testing::expect(constant_time_equal(dec1->view(), pt));
Void::Testing::expect(constant_time_equal(dec2->view(), pt));
// Wrong AAD fails authentication.
auto bad_aad = ring.open(*env_k1, wrong_aad);
Void::Testing::require(!bad_aad.has_value());
Void::Testing::expect_eq(
bad_aad.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::authentication_failed));
// Tampering any header/key_id/ciphertext byte fails authentication.
auto tampered = *env_k1;
tampered.back() ^= 0x80U;
Void::Testing::expect(!ring.open(tampered, aad).has_value());
auto bad_ver = *env_k1;
bad_ver[4] = 99U;
auto ver_res = ring.open(bad_ver, aad);
Void::Testing::require(!ver_res.has_value());
Void::Testing::expect_eq(
ver_res.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::unsupported_version));
// Legacy secretbox envelope MUST NOT silently fall back in SecretKeyRing.
auto legacy_key = random_secret_key();
Void::Testing::require(legacy_key.has_value());
auto legacy_env = seal_secret(pt, *legacy_key);
Void::Testing::require(legacy_env.has_value());
auto no_fallback = ring.open(*legacy_env, {});
Void::Testing::require(!no_fallback.has_value());
Void::Testing::expect_eq(
no_fallback.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::unsupported_version));
// Key retirement guards: cannot retire active key or key still in inventory.
const std::vector<std::string> empty_inv{};
auto retire_active = ring.retire_key("k2", empty_inv);
Void::Testing::require(!retire_active.has_value());
Void::Testing::expect_eq(
retire_active.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::key_in_use));
const std::vector<std::string> still_used{"k1", "k2"};
auto retire_in_use = ring.retire_key("k1", still_used);
Void::Testing::require(!retire_in_use.has_value());
Void::Testing::expect_eq(
retire_in_use.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::key_in_use));
const std::vector<std::string> migrated_inv{"k2"};
Void::Testing::require(ring.retire_key("k1", migrated_inv).has_value());
Void::Testing::expect(!ring.has_key("k1"));
auto retired_open = ring.open(*env_k1, aad);
Void::Testing::require(!retired_open.has_value());
Void::Testing::expect_eq(
retired_open.error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::key_not_found));
}
Void::Testing::Test security_authorization_default_deny_and_limits()
{
using namespace Void::Security;
auto policy = PolicySnapshot::create(
7,
{
PolicyRule{
.id = "allow-owner-read",
.effect = Effect::Allow,
.action = "doc:read",
.condition = Predicate::all_of(
{Predicate::resource_type("document"),
Predicate::owner_is_subject()}),
},
PolicyRule{
.id = "allow-admin-all",
.effect = Effect::Allow,
.action = "*",
.condition = Predicate::has_role("admin"),
},
PolicyRule{
.id = "deny-classified",
.effect = Effect::Deny,
.action = "*",
.condition = Predicate::resource_attr("tier", "classified"),
},
});
Void::Testing::require(policy.has_value());
Principal alice{
.subject = "alice", .roles = {"editor"}, .policy_generation = 7};
Principal admin{
.subject = "root", .roles = {"admin"}, .policy_generation = 7};
ResourceAttributes doc{
.resource_type = "document",
.resource_id = "d1",
.attributes = {{"owner", "alice"}, {"tier", "standard"}},
};
ResourceAttributes secret_doc{
.resource_type = "document",
.resource_id = "d2",
.attributes = {{"owner", "alice"}, {"tier", "classified"}},
};
// Explicit allow for owner.
auto d1 = policy->authorize(alice, "doc:read", doc);
Void::Testing::expect(d1.allowed);
Void::Testing::expect_eq(d1.matched_rule_id,
std::string{"allow-owner-read"});
// Default deny for unmatched action.
auto d2 = policy->authorize(alice, "doc:delete", doc);
Void::Testing::expect(!d2.allowed);
// Deny overrides allow even for admin.
auto d3 = policy->authorize(admin, "doc:read", secret_doc);
Void::Testing::expect(!d3.allowed);
Void::Testing::expect_eq(d3.matched_rule_id,
std::string{"deny-classified"});
// Principal exceeding 64 roles fails closed.
Principal bloated{.subject = "bob"};
bloated.roles.assign(SecurityLimits::kMaxRolesPerPrincipal + 1U, "admin");
Void::Testing::expect(!policy->authorize(bloated, "doc:read", doc).allowed);
// Rule count > 4096 rejected.
std::vector<PolicyRule> too_many(
SecurityLimits::kMaxPolicyRules + 1U,
PolicyRule{.id = "r",
.effect = Effect::Allow,
.action = "x",
.condition = Predicate::always_true()});
Void::Testing::expect(!PolicySnapshot::create(1, std::move(too_many)).has_value());
// Predicate depth > 16 rejected.
Predicate deep = Predicate::always_true();
for (std::size_t i = 0; i < SecurityLimits::kMaxPredicateDepth + 1U; ++i) {
deep = Predicate::negate(std::move(deep));
}
Void::Testing::expect(
!PolicySnapshot::create(
1, {PolicyRule{.id = "deep",
.effect = Effect::Allow,
.action = "x",
.condition = std::move(deep)}})
.has_value());
}
@@ -0,0 +1,439 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Security/Authenticator.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <future>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <thread>
namespace
{
using namespace Void::Security;
using namespace Void::SecurityAsync;
Void::Coro::Task<void> run_login(
Authenticator& auth, LoginInput input,
Void::Async::OperationOptions opts,
std::optional<Void::Result::Result<SessionGrant>>& out,
std::atomic<int>* done = nullptr)
{
out = co_await auth.login(std::move(input), std::move(opts));
if (done != nullptr) {
done->fetch_add(1, std::memory_order_release);
}
}
Void::Coro::Task<void> run_authenticate(
Authenticator& auth, const BearerToken& token,
Void::Async::OperationOptions opts,
std::optional<Void::Result::Result<Principal>>& out)
{
out = co_await auth.authenticate(token, std::move(opts));
}
Void::Coro::Task<void> run_revoke(
Authenticator& auth, std::string session_id,
Void::Async::OperationOptions opts,
std::optional<Void::Result::Result<void>>& out)
{
out = co_await auth.revoke(std::move(session_id), std::move(opts));
}
void pump_until(Void::Async::ManualExecutor& exec,
const std::atomic<int>& counter, int target)
{
const auto deadline =
std::chrono::steady_clock::now() + std::chrono::seconds{15};
while (counter.load(std::memory_order_acquire) < target &&
std::chrono::steady_clock::now() < deadline) {
if (exec.drain() == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
}
} // namespace
Void::Testing::Test security_async_login_auth_revoke_expiry_and_clock_rollback()
{
auto store = std::make_shared<InMemoryAccountSessionStore>();
auto audit = std::make_shared<InMemoryAuditSink>(64);
Void::Async::ManualExecutor exec;
Void::Time::ManualClock mono_clock;
Void::Time::ManualCivilClock civil_clock{
std::chrono::system_clock::time_point{std::chrono::seconds{1000000}}};
auto alice_hash =
hash_password("correct-pw", PasswordHashStrength::Interactive);
Void::Testing::require(alice_hash.has_value());
Void::Testing::require(
store
->upsert_account(AccountRecord{
.subject = "sub-alice",
.normalized_username = "alice",
.password_hash = *alice_hash,
.roles = {"user"},
.credential_version = 1,
.revocation_generation = 1,
.policy_generation = 3,
.enabled = true,
})
.has_value());
AuthenticatorOptions opts{};
opts.dummy_hash_strength = PasswordHashStrength::Interactive;
opts.precomputed_dummy_hash = *alice_hash;
opts.session.ttl = std::chrono::seconds{3600};
opts.session.max_total_sessions = 4;
opts.session.max_per_subject = 2;
opts.session.clock_rollback_tolerance = std::chrono::seconds{60};
auto auth = Authenticator::create(store, exec, opts, audit, mono_clock,
civil_clock);
Void::Testing::require(auth.has_value());
// 1. Unknown account and wrong password produce identical public denial but
// distinct internal audit reasons.
{
std::optional<Void::Result::Result<SessionGrant>> unknown_res;
std::optional<Void::Result::Result<SessionGrant>> wrong_pw_res;
std::atomic<int> done{0};
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {"ghost", "any"}, {}, unknown_res,
&done))
.has_value());
Void::Testing::require(
scope
.spawn(run_login(**auth, {"ALICE", "wrong-pw"}, {},
wrong_pw_res, &done))
.has_value());
pump_until(exec, done, 2);
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(unknown_res.has_value() &&
!unknown_res->has_value());
Void::Testing::require(wrong_pw_res.has_value() &&
!wrong_pw_res->has_value());
Void::Testing::expect_eq(unknown_res->error().code().value,
wrong_pw_res->error().code().value);
Void::Testing::expect_eq(unknown_res->error().message(),
wrong_pw_res->error().message());
const auto events = audit->snapshot();
bool saw_not_found = false;
bool saw_invalid_pw = false;
for (const auto& ev : events) {
if (ev.internal_reason == "account_not_found") {
saw_not_found = true;
}
if (ev.internal_reason == "invalid_password") {
saw_invalid_pw = true;
}
}
Void::Testing::expect(saw_not_found);
Void::Testing::expect(saw_invalid_pw);
}
// 2. Successful login (case-insensitive username) + authoritative
// authenticate + immediate revocation (zero positive cache).
std::optional<SessionGrant> grant1;
{
std::optional<Void::Result::Result<SessionGrant>> res;
std::atomic<int> done{0};
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {" Alice ", "correct-pw"}, {}, res,
&done))
.has_value());
pump_until(exec, done, 1);
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(res.has_value() && res->has_value());
grant1.emplace(std::move(**res));
}
{
std::optional<Void::Result::Result<Principal>> principal;
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_authenticate(**auth, grant1->bearer_token, {},
principal))
.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(principal.has_value() && principal->has_value());
Void::Testing::expect_eq((*principal)->subject,
std::string{"sub-alice"});
Void::Testing::expect_eq((*principal)->policy_generation, 3ULL);
}
// Revoke takes effect immediately on next authenticate call.
{
std::optional<Void::Result::Result<void>> rev_res;
std::optional<Void::Result::Result<Principal>> after_rev;
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_revoke(**auth, grant1->session_id, {}, rev_res))
.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(rev_res.has_value() && rev_res->has_value());
Void::Async::TaskScope scope2{exec};
Void::Testing::require(
scope2
.spawn(run_authenticate(**auth, grant1->bearer_token, {},
after_rev))
.has_value());
Void::Testing::require(scope2.join_pumping(exec).has_value());
Void::Testing::require(after_rev.has_value() && !after_rev->has_value());
Void::Testing::expect_eq(
after_rev->error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::session_revoked));
}
// 3. Per-subject session capacity (max_per_subject = 2) enforced, and
// expiry + bounded cleanup reclaims slots.
std::optional<SessionGrant> g2;
std::optional<SessionGrant> g3;
for (auto* target : {&g2, &g3}) {
std::optional<Void::Result::Result<SessionGrant>> res;
std::atomic<int> done{0};
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {"alice", "correct-pw"}, {}, res, &done))
.has_value());
pump_until(exec, done, 1);
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(res.has_value() && res->has_value());
target->emplace(std::move(**res));
}
{
std::optional<Void::Result::Result<SessionGrant>> over_cap;
std::atomic<int> done{0};
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {"alice", "correct-pw"}, {}, over_cap,
&done))
.has_value());
pump_until(exec, done, 1);
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(over_cap.has_value() && !over_cap->has_value());
Void::Testing::expect_eq(
over_cap->error().code().value,
static_cast<std::int32_t>(
SecurityErrorCode::session_capacity_exceeded));
}
// Advance civil clock past TTL -> authenticate denies expired, cleanup
// removes sessions.
Void::Testing::require(
civil_clock.advance(std::chrono::seconds{3601}).has_value());
{
std::optional<Void::Result::Result<Principal>> expired;
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_authenticate(**auth, g2->bearer_token, {}, expired))
.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(expired.has_value() && !expired->has_value());
Void::Testing::expect_eq(
expired->error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::session_expired));
}
auto cleaned = (*auth)->cleanup_expired_step();
Void::Testing::require(cleaned.has_value());
Void::Testing::expect_eq(*cleaned, 3U);
// 4. Civil-clock rollback beyond 60s tolerance halts admission until
// explicitly reconciled.
civil_clock.set(civil_clock.now() - std::chrono::seconds{120});
{
std::optional<Void::Result::Result<SessionGrant>> halted;
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {"alice", "correct-pw"}, {}, halted))
.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(halted.has_value() && !halted->has_value());
Void::Testing::expect_eq(
halted->error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::clock_rollback));
}
(*auth)->reconcile_clock(civil_clock.now());
// 5. Store outage fails closed.
store->set_available(false);
{
std::optional<Void::Result::Result<SessionGrant>> outage;
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {"alice", "correct-pw"}, {}, outage))
.has_value());
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(outage.has_value() && !outage->has_value());
Void::Testing::expect_eq(
outage->error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::store_unavailable));
}
store->set_available(true);
Void::Testing::require((*auth)->close_and_join().has_value());
}
Void::Testing::Test security_async_version_race_hash_stop_and_mandatory_audit()
{
auto store = std::make_shared<InMemoryAccountSessionStore>();
auto audit = std::make_shared<InMemoryAuditSink>(1); // capacity 1!
Void::Async::ManualExecutor exec;
Void::Time::ManualClock mono_clock;
Void::Time::ManualCivilClock civil_clock{
std::chrono::system_clock::time_point{std::chrono::seconds{2000000}}};
auto pw_hash =
hash_password("hunter2", PasswordHashStrength::Interactive);
Void::Testing::require(pw_hash.has_value());
Void::Testing::require(
store
->upsert_account(AccountRecord{
.subject = "sub-bob",
.normalized_username = "bob",
.password_hash = *pw_hash,
.roles = {"member"},
.credential_version = 1,
.revocation_generation = 1,
.policy_generation = 1,
.enabled = true,
})
.has_value());
// 1. Stop during in-flight password hash: worker drains to completion,
// releases memory budget, discards outcome, and creates zero sessions.
{
std::promise<void> entered_hash;
std::promise<void> release_hash;
auto entered_fut = entered_hash.get_future();
auto release_fut = release_hash.get_future().share();
AuthenticatorOptions opts{};
opts.dummy_hash_strength = PasswordHashStrength::Interactive;
opts.precomputed_dummy_hash = *pw_hash;
opts.before_password_verify_hook = [&]() {
entered_hash.set_value();
release_fut.wait();
};
auto auth = Authenticator::create(store, exec, opts, nullptr,
mono_clock, civil_clock);
Void::Testing::require(auth.has_value());
std::stop_source ss;
std::optional<Void::Result::Result<SessionGrant>> res;
std::atomic<int> done{0};
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {"bob", "hunter2"},
Void::Async::OperationOptions{
.stop = ss.get_token()},
res, &done))
.has_value());
(void)exec.drain();
// Wait until worker actually holds password job budget.
entered_fut.wait();
Void::Testing::expect_eq((*auth)->stats().active_password_jobs, 1U);
Void::Testing::expect((*auth)->stats().reserved_password_memory_bytes >
0U);
ss.request_stop();
release_hash.set_value();
pump_until(exec, done, 1);
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(res.has_value() && !res->has_value());
Void::Testing::expect_eq(
res->error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::cancelled));
Void::Testing::expect_eq(store->session_count(), 0U);
Void::Testing::expect_eq((*auth)->stats().active_password_jobs, 0U);
Void::Testing::expect_eq(
(*auth)->stats().reserved_password_memory_bytes, 0U);
Void::Testing::require((*auth)->close_and_join().has_value());
}
// 2. Credential version change racing with login invalidates session write.
{
AuthenticatorOptions opts{};
opts.dummy_hash_strength = PasswordHashStrength::Interactive;
opts.precomputed_dummy_hash = *pw_hash;
opts.before_password_verify_hook = [&]() {
(void)store->bump_credential_version("sub-bob");
};
auto auth = Authenticator::create(store, exec, opts, nullptr,
mono_clock, civil_clock);
Void::Testing::require(auth.has_value());
std::optional<Void::Result::Result<SessionGrant>> res;
std::atomic<int> done{0};
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {"bob", "hunter2"}, {}, res, &done))
.has_value());
pump_until(exec, done, 1);
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(res.has_value() && !res->has_value());
Void::Testing::expect_eq(
res->error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::conflict));
Void::Testing::expect_eq(store->session_count(), 0U);
Void::Testing::require((*auth)->close_and_join().has_value());
}
// 3. Mandatory fail-closed audit queue full revokes session and fails login.
{
// Pre-fill the 1-slot audit sink.
Void::Testing::require(
audit->record(AuditEvent{.event_type = "fill"}).has_value());
AuthenticatorOptions opts{};
opts.dummy_hash_strength = PasswordHashStrength::Interactive;
opts.precomputed_dummy_hash = *pw_hash;
opts.audit_policy = AuditFailurePolicy::FailClosed;
auto auth = Authenticator::create(store, exec, opts, audit, mono_clock,
civil_clock);
Void::Testing::require(auth.has_value());
std::optional<Void::Result::Result<SessionGrant>> res;
std::atomic<int> done{0};
Void::Async::TaskScope scope{exec};
Void::Testing::require(
scope
.spawn(run_login(**auth, {"bob", "hunter2"}, {}, res, &done))
.has_value());
pump_until(exec, done, 1);
Void::Testing::require(scope.join_pumping(exec).has_value());
Void::Testing::require(res.has_value() && !res->has_value());
Void::Testing::expect_eq(
res->error().code().value,
static_cast<std::int32_t>(SecurityErrorCode::audit_failed));
Void::Testing::require((*auth)->close_and_join().has_value());
}
}