From 6413326abf333957bd74a32b766df70a207ef80b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Paw=C5=82ow?= Date: Tue, 20 Oct 2026 07:14:20 +0200 Subject: [PATCH 1/8] Fix the queue's completion race; add allocation-free byte overloads BcryptQueue's requests completed through ManualResetValueTaskSourceCore, which marks a result ready before it claims the continuation slot. A caller that read the result in that window released the request, and the completion then landed in its next call. CompletionCore claims the slot first and touches nothing after; a late continuation runs inline. New: Bcrypt.Verify/Hash over bytes, BcryptQueue.VerifyAsync/HashAsync over bytes, TryVerifyAsync/TryHashAsync with a BcryptStatus instead of exceptions, and BcryptHash, which holds a hash's 60 bytes inline. Version 1.1.0. --- README.md | 43 ++- .../VerifyBenchmarks.cs | 39 ++- src/CodeFusion.Security.Bcrypt/Bcrypt.Core.cs | 73 +++- src/CodeFusion.Security.Bcrypt/Bcrypt.cs | 43 +++ src/CodeFusion.Security.Bcrypt/BcryptHash.cs | 62 ++++ .../BcryptHashResult.cs | 18 + src/CodeFusion.Security.Bcrypt/BcryptQueue.cs | 196 ++++++++--- .../BcryptStatus.cs | 21 ++ .../CodeFusion.Security.Bcrypt.csproj | 2 +- .../CompletionCore.cs | 154 +++++++++ .../AllocationTests.cs | 93 +++++ .../BcryptQueueTests.cs | 2 +- .../BcryptQueueUtf8Tests.cs | 319 ++++++++++++++++++ .../CompletionTests.cs | 176 ++++++++++ .../Utf8Tests.cs | 181 ++++++++++ 15 files changed, 1366 insertions(+), 56 deletions(-) create mode 100644 src/CodeFusion.Security.Bcrypt/BcryptHash.cs create mode 100644 src/CodeFusion.Security.Bcrypt/BcryptHashResult.cs create mode 100644 src/CodeFusion.Security.Bcrypt/BcryptStatus.cs create mode 100644 src/CodeFusion.Security.Bcrypt/CompletionCore.cs create mode 100644 tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs create mode 100644 tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs create mode 100644 tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs diff --git a/README.md b/README.md index cddadc9..dd13bea 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # CodeFusion.Security.Bcrypt bcrypt for .NET 8, 9 and 10, tested on .NET 11 too. A check allocates no memory at all, and a new hash only its -string. Up to five hashes run interleaved on one thread, each for a quarter to two fifths of the CPU time of a hash +string, or nothing when it's written as bytes. Up to five hashes run interleaved on one thread, each for a quarter to two fifths of the CPU time of a hash alone, and `BcryptQueue` gives a server that batching without blocking its thread pool. Hashes are interchangeable with OpenBSD, Go, PHP, Python's bcrypt and BCrypt.Net-Next, including BCrypt.Net-Next's @@ -72,7 +72,7 @@ makes one: ```csharp builder.Services.AddSingleton(new BcryptQueue(new BcryptQueueOptions { - MaxQueued = 1024, // past that, calls fail at once with BcryptQueueFullException: answer 503 + MaxQueued = 1024, // past that, calls fail at once with BcryptQueueFullException (TryVerifyAsync says Busy): answer 503 })); string dummyHash = Bcrypt.Hash(Guid.NewGuid().ToString(), 12); @@ -122,6 +122,43 @@ up to 200 ms of latency. | A check now and then, or not a server | `Bcrypt.Verify(password, hash)` | | A batch you already hold | `Bcrypt.Verify(passwords, hashes, results)` | | A web server's sign-in and sign-up | `BcryptQueue.VerifyAsync` and `HashAsync` | +| A server that reads passwords and keeps hashes as bytes | the byte overloads below | + +## Bytes instead of strings + +A server reads the password off the wire as bytes and may keep the hash as bytes too. The overloads that take spans +skip both strings, and none of them allocates: + +```csharp +bool ok = Bcrypt.Verify(passwordUtf8, storedHash); // two ReadOnlySpan +int written = Bcrypt.Hash(passwordUtf8, 12, destination); // 60 ASCII bytes into a Span + +bool ok = await bcrypt.VerifyAsync(passwordUtf8, storedHash, aborted); +BcryptHash hash = await bcrypt.HashAsync(passwordUtf8, 12); // the 60 bytes, held inline +hash.CopyTo(row.PasswordHash); +``` + +- The queue copies both spans before the call returns, so their buffers can be reused at once. +- The password's bytes are the key as they are. UTF-8 gives the same hashes as the string overloads, and other bytes + are taken too, as OpenBSD and Go take them. Over 72 bytes is refused, as with strings. The enhanced hashes take + strings only. +- `BcryptHash` reads out with `CopyTo`, `TryFormat` (to bytes or chars) or `AsSpan`; `ToString` makes the string. + +`TryVerifyAsync` and `TryHashAsync` report a full queue or a fired token as a status instead of an exception, so +overload costs no exception either: + +```csharp +switch (await bcrypt.TryVerifyAsync(passwordUtf8, storedHash, aborted)) +{ + case BcryptStatus.Match: return Results.Ok(Token(user)); + case BcryptStatus.Busy: return Results.StatusCode(503); + case BcryptStatus.Cancelled: return Results.Empty; // the client went away + default: return Results.Unauthorized(); // NoMatch, or a malformed hash +} + +BcryptHashResult made = await bcrypt.TryHashAsync(passwordUtf8, 12); +if (made.Status == BcryptStatus.Hashed) made.Hash.CopyTo(row.PasswordHash); +``` ## Passwords over 72 bytes @@ -165,6 +202,8 @@ there are. Bytes allocated per call, measured over 2,000 calls (the cost doesn't | `EnhancedVerify` | **0 B** | 5,856 B | | `BcryptQueue.VerifyAsync` | **0 B** | | | `Hash` | 144 B: the returned string | 5,416 B | +| `Verify` and `Hash` from bytes | **0 B** | | +| `BcryptQueue.VerifyAsync`, `HashAsync`, `TryVerifyAsync` and `TryHashAsync` from bytes | **0 B** | | At 1,000 sign-ins a second, BCrypt.Net-Next makes 5 MB of garbage a second; this package makes none. BCrypt.Net-Next allocates a new 4 KB copy of the Blowfish tables for every hash. This package does the following: diff --git a/benchmarks/CodeFusion.Security.Bcrypt.Benchmarks/VerifyBenchmarks.cs b/benchmarks/CodeFusion.Security.Bcrypt.Benchmarks/VerifyBenchmarks.cs index f5b2b4d..fef3103 100644 --- a/benchmarks/CodeFusion.Security.Bcrypt.Benchmarks/VerifyBenchmarks.cs +++ b/benchmarks/CodeFusion.Security.Bcrypt.Benchmarks/VerifyBenchmarks.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.CompilerServices; +using System.Text; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; @@ -19,6 +20,7 @@ public class VerifyBenchmarks // From Go's golang.org/x/crypto/bcrypt. const string Hash = "$2a$10$ZSfEoPvlcsj2XfvsSeK25em4NZ9Jm7ntGqXuLgQfHEeZPYB8899wq"; + static readonly byte[] PasswordUtf8 = Encoding.UTF8.GetBytes(Password), HashAscii = Encoding.ASCII.GetBytes(Hash); static readonly string[] Passwords = [Password, Password, Password, Password, Password]; static readonly string[] Hashes = [Hash, Hash, Hash, Hash, Hash]; readonly bool[] _results = new bool[Bcrypt.MaxLanes]; @@ -36,6 +38,10 @@ public class VerifyBenchmarks [Benchmark, BenchmarkCategory("verify")] public bool Verify() => Bcrypt.Verify(Password, Hash); + /// The same check from bytes, as a server reads them off the wire. + [Benchmark, BenchmarkCategory("verify")] + public bool VerifyUtf8() => Bcrypt.Verify(PasswordUtf8, HashAscii); + [Benchmark(OperationsPerInvoke = 2), BenchmarkCategory("verify")] public bool Lanes2() => Lanes(2); @@ -62,6 +68,18 @@ async ValueTask FiveThroughTheQueue() return await a & await b & await c & await d & await e; } + /// through the byte overload. + [Benchmark(OperationsPerInvoke = 5), BenchmarkCategory("verify")] + public ValueTask Queue5Utf8() => FiveUtf8ThroughTheQueue(); + + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] + async ValueTask FiveUtf8ThroughTheQueue() + { + ValueTask a = _queue.VerifyAsync(PasswordUtf8, HashAscii), b = _queue.VerifyAsync(PasswordUtf8, HashAscii), + c = _queue.VerifyAsync(PasswordUtf8, HashAscii), d = _queue.VerifyAsync(PasswordUtf8, HashAscii), e = _queue.VerifyAsync(PasswordUtf8, HashAscii); + return await a & await b & await c & await d & await e; + } + bool Lanes(int n) { Bcrypt.Verify(Passwords.AsSpan(0, n), Hashes.AsSpan(0, n), _results.AsSpan(0, n)); @@ -69,16 +87,35 @@ bool Lanes(int n) } } -/// A new hash at cost 10: the string it returns is all it allocates. +/// A new hash at cost 10: the string overloads allocate only the string they return, the byte ones nothing. [MemoryDiagnoser] public class HashBenchmarks { + static readonly byte[] PasswordUtf8 = "password123"u8.ToArray(); + readonly byte[] _destination = new byte[Bcrypt.HashLength]; + BcryptQueue _queue = null!; + + [GlobalSetup] + public void Setup() => _queue = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); + + [GlobalCleanup] + public void Cleanup() => _queue.Dispose(); + [Benchmark(Baseline = true)] public string BCryptNetNext() => BCrypt.Net.BCrypt.HashPassword("password123", 10); [Benchmark] public string Hash() => Bcrypt.Hash("password123", 10); + [Benchmark] + public int HashUtf8() => Bcrypt.Hash(PasswordUtf8, 10, _destination); + [Benchmark] public string EnhancedHash() => Bcrypt.EnhancedHash("password123", 10); + + [Benchmark] + public ValueTask QueueHash() => _queue.HashAsync("password123", 10); + + [Benchmark] + public ValueTask QueueHashUtf8() => _queue.HashAsync(PasswordUtf8, 10); } diff --git a/src/CodeFusion.Security.Bcrypt/Bcrypt.Core.cs b/src/CodeFusion.Security.Bcrypt/Bcrypt.Core.cs index 541cdcc..344a975 100644 --- a/src/CodeFusion.Security.Bcrypt/Bcrypt.Core.cs +++ b/src/CodeFusion.Security.Bcrypt/Bcrypt.Core.cs @@ -216,11 +216,24 @@ static bool IsWholeHash(ReadOnlySpan hash, int end) internal static bool PrepareVerify(ReadOnlySpan password, ReadOnlySpan hash, BcryptPrehash prehash, Input* input) { Span salt = stackalloc byte[SaltBytes]; - int end = ParseSettings(hash, out char revision, out int cost, salt); - if (!IsWholeHash(hash, end)) return false; - return Prepare(password, salt, cost, revision, prehash, input); + return ParseHash(hash, out char revision, out int cost, salt) && Prepare(password, salt, cost, revision, prehash, input); } + /// of a password + /// and a hash as bytes; false when the hash is malformed or the password is over 72 bytes. + internal static bool PrepareVerify(ReadOnlySpan password, ReadOnlySpan hash, Input* input) + { + if (hash.Length > HashLength) return false; + Span text = stackalloc char[HashLength]; + for (int i = 0; i < hash.Length; i++) text[i] = (char)hash[i]; // a byte past ASCII widens to a char the parser refuses + Span salt = stackalloc byte[SaltBytes]; + return ParseHash(text[..hash.Length], out char revision, out int cost, salt) && Prepare(password, salt, cost, revision, input); + } + + /// The settings of a whole hash; false when it's malformed. + static bool ParseHash(ReadOnlySpan hash, out char revision, out int cost, Span salt) => + IsWholeHash(hash, ParseSettings(hash, out revision, out cost, salt)); + internal static bool Prepare(ReadOnlySpan password, ReadOnlySpan salt, int cost, char revision, BcryptPrehash prehash, Input* input) { if (!PrepareKey(password, revision, prehash, input->Key)) return false; @@ -231,6 +244,24 @@ internal static bool Prepare(ReadOnlySpan password, ReadOnlySpan sal return true; } + /// of a + /// password as bytes, taken as they are: false when they are over 72. + internal static bool Prepare(ReadOnlySpan password, ReadOnlySpan salt, int cost, char revision, Input* input) + { + if (password.Length > MaxPasswordBytes) return false; + Span key = stackalloc byte[MaxPasswordBytes + 1]; + password.CopyTo(key); + int n = password.Length; + if (revision != '\0') key[n++] = 0; + StreamWords(key[..n], input->Key); + CryptographicOperations.ZeroMemory(key); + StreamWords(salt, input->Salt); + salt.CopyTo(new Span(input->SaltBytes, SaltBytes)); + input->Cost = cost; + input->Revision = revision; + return true; + } + /// /// The key's words: the password's UTF-8 and, except for "$2$", a terminating NUL. False when the UTF-8 is over /// 72 bytes (bcrypt would ignore the rest) or the text isn't valid UTF-16. With a prehash the key is instead the @@ -332,11 +363,13 @@ static int DigestInChunks(ReadOnlySpan password, BcryptPrehash prehash, Sp } } - /// Why refused , for the exception. + /// Why refused , for the exception. internal static string RefusalOf(ReadOnlySpan password) => IsValidUtf16(password) - ? "bcrypt reads at most 72 UTF-8 bytes of a password; use an enhanced hash for longer ones" + ? TooLong : "the password isn't valid UTF-16: it has a lone surrogate"; + internal const string TooLong = "bcrypt reads at most 72 UTF-8 bytes of a password; use an enhanced hash for longer ones"; + static bool IsValidUtf16(ReadOnlySpan text) { for (int i = 0; i < text.Length; i++) @@ -421,15 +454,41 @@ internal static bool Matches(uint* c, ReadOnlySpan stored) return CryptographicOperations.FixedTimeEquals(MemoryMarshal.AsBytes(encoded), MemoryMarshal.AsBytes(stored)); } + /// of a stored hash as ASCII bytes. + internal static bool Matches(uint* c, ReadOnlySpan stored) + { + Span hash = stackalloc byte[HashBytes]; + HashBytesOf(c, hash); + Span encoded = stackalloc char[HashChars]; + Encode(hash, encoded); + Span ascii = stackalloc byte[HashChars]; + for (int i = 0; i < HashChars; i++) ascii[i] = (byte)encoded[i]; + return CryptographicOperations.FixedTimeEquals(ascii, stored); + } + /// The finished hash: "$2b$10$" + salt + hash, or "$2$10$" + ... for the original revision. internal static string Format(Input* input, uint* c) { - Span s = stackalloc char[60]; + Span s = stackalloc char[HashLength]; + return new string(s[..Format(input, c, s)]); + } + + /// The finished hash as ASCII bytes; returns the length written. + internal static int Format(Input* input, uint* c, Span destination) + { + Span s = stackalloc char[HashLength]; + int n = Format(input, c, s); + for (int i = 0; i < n; i++) destination[i] = (byte)s[i]; + return n; + } + + static int Format(Input* input, uint* c, Span s) + { int at = WriteSettings(s, input->Revision, input->Cost, new ReadOnlySpan(input->SaltBytes, SaltBytes)); Span hash = stackalloc byte[HashBytes]; HashBytesOf(c, hash); Encode(hash, s.Slice(at, HashChars)); - return new string(s[..(at + HashChars)]); + return at + HashChars; } /// Writes "$2b$10$" + 22 salt characters; returns the length written. diff --git a/src/CodeFusion.Security.Bcrypt/Bcrypt.cs b/src/CodeFusion.Security.Bcrypt/Bcrypt.cs index f3891d4..dd44806 100644 --- a/src/CodeFusion.Security.Bcrypt/Bcrypt.cs +++ b/src/CodeFusion.Security.Bcrypt/Bcrypt.cs @@ -32,11 +32,39 @@ public static unsafe partial class Bcrypt /// The longest password, in UTF-8 bytes, that bcrypt reads in full. public const int MaxPasswordBytes = 72; + /// The length of a hash this library makes, in characters or ASCII bytes: "$2b$", the cost, "$", 22 salt + /// characters and 31 hash characters. + public const int HashLength = 60; + /// A new "$2b$" hash of with a random salt. /// The password is over 72 UTF-8 bytes or isn't valid UTF-16. /// is outside 4 to 31. public static string Hash(string password, int cost = DefaultCost) => Hash(password, cost, BcryptPrehash.None); + /// + /// A new "$2b$" hash of the password in , written to + /// as ASCII. Allocates nothing. The bytes are the key as they are: UTF-8 gives the hash + /// gives the same text, and other bytes are taken too, as OpenBSD and Go take them. + /// + /// The bytes written: . + /// The password is over 72 bytes, or is shorter + /// than . + /// is outside 4 to 31. + public static int Hash(ReadOnlySpan passwordUtf8, int cost, Span destination) + { + CheckCost(cost); + if (destination.Length < HashLength) throw new ArgumentException($"the destination must hold {HashLength} bytes", nameof(destination)); + Input input; + Span salt = stackalloc byte[SaltBytes]; + RandomNumberGenerator.Fill(salt); + if (!Prepare(passwordUtf8, salt, cost, 'b', &input)) throw new ArgumentException(TooLong, nameof(passwordUtf8)); + uint* ct = stackalloc uint[6]; + Run(&input, 1, ct); + int written = Format(&input, ct, destination); + Wipe(&input, 1); + return written; + } + /// /// The hash of with the revision, cost and salt of : a value /// from , or a whole hash. @@ -48,6 +76,21 @@ public static unsafe partial class Bcrypt /// over 72 UTF-8 bytes or not valid UTF-16, never matches. Never throws for any non-null input. public static bool Verify(string password, string hash) => Verify(password, hash, BcryptPrehash.None); + /// + /// Whether the password in matches , its ASCII bytes. As + /// for the UTF-8 of the same text; other bytes are taken as they are. A + /// malformed hash, or a password over 72 bytes, never matches. Allocates nothing and never throws. + /// + public static bool Verify(ReadOnlySpan passwordUtf8, ReadOnlySpan hash) + { + Input input; + if (!PrepareVerify(passwordUtf8, hash, &input)) return false; + uint* ct = stackalloc uint[6]; + Run(&input, 1, ct); + Wipe(&input, 1); + return Matches(ct, hash[^HashChars..]); + } + /// /// Checks passwords[i] against hashes[i] into results[i], up to five at a time interleaved on /// this thread: five checks take 1.3 to 2 times as long as one, depending on the CPU. diff --git a/src/CodeFusion.Security.Bcrypt/BcryptHash.cs b/src/CodeFusion.Security.Bcrypt/BcryptHash.cs new file mode 100644 index 0000000..36da540 --- /dev/null +++ b/src/CodeFusion.Security.Bcrypt/BcryptHash.cs @@ -0,0 +1,62 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Text; + +namespace CodeFusion.Security; + +/// +/// A new bcrypt hash as its 60 ASCII bytes, held inline instead of in a string: what +/// returns. Copy it +/// where it is stored with or ; +/// makes the string. +/// +public readonly struct BcryptHash : ISpanFormattable, IUtf8SpanFormattable +{ + readonly Buffer _bytes; + + internal BcryptHash(in Buffer bytes) => _bytes = bytes; + + /// ; 0 for default, which holds no hash. + public int Length => _bytes[0] == (byte)'$' ? Bcrypt.HashLength : 0; + + /// The hash's ASCII bytes, read in place. + [UnscopedRef] + public ReadOnlySpan AsSpan() => ((ReadOnlySpan)_bytes)[..Length]; + + /// Copies the hash's ASCII bytes to the start of . + /// is shorter than . + public void CopyTo(Span destination) + { + if (!AsSpan().TryCopyTo(destination)) throw new ArgumentException($"the destination must hold {Length} bytes", nameof(destination)); + } + + /// Writes the hash's ASCII bytes; false, writing nothing, when is too short. + public bool TryFormat(Span utf8Destination, out int bytesWritten, ReadOnlySpan format = default, IFormatProvider? provider = null) + { + bytesWritten = AsSpan().TryCopyTo(utf8Destination) ? Length : 0; + return bytesWritten == Length; + } + + /// Writes the hash's characters; false, writing nothing, when is too short. + public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default, IFormatProvider? provider = null) + { + charsWritten = 0; + if (destination.Length < Length) return false; + charsWritten = Encoding.ASCII.GetChars(AsSpan(), destination); + return true; + } + + /// The hash as a string, "$2b$..."; empty for default. + public override string ToString() => Encoding.ASCII.GetString(AsSpan()); + + /// + public string ToString(string? format, IFormatProvider? formatProvider) => ToString(); + + /// A hash's bytes, inline. + [InlineArray(Bcrypt.HashLength)] + internal struct Buffer + { + byte _first; + } +} diff --git a/src/CodeFusion.Security.Bcrypt/BcryptHashResult.cs b/src/CodeFusion.Security.Bcrypt/BcryptHashResult.cs new file mode 100644 index 0000000..98588ce --- /dev/null +++ b/src/CodeFusion.Security.Bcrypt/BcryptHashResult.cs @@ -0,0 +1,18 @@ +namespace CodeFusion.Security; + +/// What reports: holds the new hash when +/// is . +public readonly struct BcryptHashResult +{ + internal BcryptHashResult(BcryptStatus status, BcryptHash hash) + { + Status = status; + Hash = hash; + } + + /// , or . + public BcryptStatus Status { get; } + + /// The new hash; default unless is . + public BcryptHash Hash { get; } +} diff --git a/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs b/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs index ebca98e..4cc8662 100644 --- a/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs +++ b/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; +using System.Text; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; @@ -32,11 +33,16 @@ public sealed unsafe class BcryptQueue : IDisposable const int Linking = 0, Queued = 1, Out = 2; /// One hash or check. Two references keep it from reuse: the queue's entry and the caller's await. - sealed class Request(BcryptQueue owner) : IValueTaskSource, IValueTaskSource, IThreadPoolWorkItem + sealed class Request(BcryptQueue owner) : IValueTaskSource, IValueTaskSource, IValueTaskSource, + IValueTaskSource, IValueTaskSource, IThreadPoolWorkItem { - ManualResetValueTaskSourceCore _core; // continuations run inline: Execute already runs on the pool + CompletionCore _core; // continuations run inline: Execute already runs on the pool public Bcrypt.Input Input; // prepared on the caller's thread; cleared once a worker has copied it - public string? Stored; // a check: the stored hash; null for a new hash + /// A check: the stored hash's last 31 characters, copied on the caller's thread. A new hash: the hash, + /// once made. + public BcryptHash.Buffer Bytes; + public bool Verifying; + public bool Quiet; // a Try call: a cancellation completes it with a status, not an exception public long Enqueued; public CancellationToken Token; public CancellationTokenRegistration Registration; @@ -45,24 +51,30 @@ sealed class Request(BcryptQueue owner) : IValueTaskSource, IValueTaskSour public bool CancelledWhileLinking; public int Refs; int _consumed; - bool _match; - string? _hash; + BcryptStatus _status; Exception? _error; public short Version => _core.Version; /// Completes on a pool thread, so the caller's continuation never runs on a bcrypt worker. - public void Complete(bool match, string? hash, Exception? error) + public void Complete(BcryptStatus status, Exception? error) { - _match = match; - _hash = hash; + _status = status; _error = error; ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: false); } + /// Completes a request whose token fired before a worker took it. + public void CompleteCancelled() + { + fixed (Bcrypt.Input* input = &Input) Bcrypt.Wipe(input, 1); + if (Quiet) Complete(BcryptStatus.Cancelled, null); + else Complete(BcryptStatus.NoMatch, new OperationCanceledException(Token)); + } + void IThreadPoolWorkItem.Execute() { - if (_error is null) _core.SetResult(_match); + if (_error is null) _core.SetResult(); else _core.SetException(_error); } @@ -81,8 +93,7 @@ public void Cancel() owner._ready.Wait(0); // drop its wake-up; if a worker already has that one, it wakes to fewer requests Interlocked.Decrement(ref owner._queued); Interlocked.Increment(ref owner._cancelled); - fixed (Bcrypt.Input* input = &Input) Bcrypt.Wipe(input, 1); - Complete(false, null, new OperationCanceledException(Token)); + CompleteCancelled(); Release(); // last: once the caller has read the result too, the request is reused } @@ -94,19 +105,21 @@ public void Release() public void Reset() { fixed (Bcrypt.Input* input = &Input) Bcrypt.Wipe(input, 1); - Stored = null; + ((Span)Bytes).Clear(); + Verifying = Quiet = false; Token = default; Registration = default; Prev = Next = null; Stage = Linking; CancelledWhileLinking = false; _consumed = 0; - _hash = null; + _status = BcryptStatus.NoMatch; _error = null; _core.Reset(); } - void Consume(short token) + /// Checks the caller's token, throws a failure, and releases the request once its result is copied. + T Read(short token, Func result) { // Reading a result before it's ready (.Result or .GetAwaiter().GetResult() on a pending ValueTask) must not // release the request: a worker still holds it, and it would be reused for another caller meanwhile. @@ -115,26 +128,25 @@ void Consume(short token) // A second await of the same ValueTask would release the request twice and hand it to two callers. if (token != _core.Version || Interlocked.Exchange(ref _consumed, 1) != 0) throw new InvalidOperationException("a BcryptQueue result was awaited twice or after it was reused; await each ValueTask once"); - } - - bool IValueTaskSource.GetResult(short token) - { - Consume(token); - try { return _core.GetResult(token); } - finally { Release(); } - } - - string IValueTaskSource.GetResult(short token) - { - Consume(token); try { _core.GetResult(token); - return _hash!; + return result(this); } finally { Release(); } } + bool IValueTaskSource.GetResult(short token) => Read(token, static r => r._status == BcryptStatus.Match); + + string IValueTaskSource.GetResult(short token) => Read(token, static r => new BcryptHash(r.Bytes).ToString()); + + BcryptHash IValueTaskSource.GetResult(short token) => Read(token, static r => new BcryptHash(r.Bytes)); + + BcryptStatus IValueTaskSource.GetResult(short token) => Read(token, static r => r._status); + + BcryptHashResult IValueTaskSource.GetResult(short token) => + Read(token, static r => new BcryptHashResult(r._status, r._status == BcryptStatus.Hashed ? new BcryptHash(r.Bytes) : default)); + public ValueTaskSourceStatus GetStatus(short token) => _core.GetStatus(token); public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => @@ -233,8 +245,39 @@ public ValueTask VerifyAsync(string password, string hash, BcryptPrehash p Recycle(r); return new ValueTask(false); } - r.Stored = hash; - return Enqueue(r, cancellationToken, out var error) is { } version ? new ValueTask(r, version) : ValueTask.FromException(error!); + r.Verifying = true; + Encoding.ASCII.GetBytes(hash.AsSpan(hash.Length - Bcrypt.HashChars), r.Bytes); // checked: all ASCII + return Enqueue(r, cancellationToken, out short version) ? new ValueTask(r, version) : ValueTask.FromException(new BcryptQueueFullException()); + } + + /// + /// of a password and a stored hash as bytes, which it + /// copies before it returns: the buffers can be reused at once. Allocates nothing. The password's bytes are the key + /// as they are (UTF-8 matches the string overload); a malformed hash or a password over 72 bytes is false at once, + /// without queueing. + /// + /// The queue is full (in the returned task); see + /// for a status instead. + public ValueTask VerifyAsync(ReadOnlySpan passwordUtf8, ReadOnlySpan hash, CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + if (cancellationToken.IsCancellationRequested) return ValueTask.FromCanceled(cancellationToken); + if (RentCheck(passwordUtf8, hash, quiet: false) is not { } r) return new ValueTask(false); + return Enqueue(r, cancellationToken, out short version) ? new ValueTask(r, version) : ValueTask.FromException(new BcryptQueueFullException()); + } + + /// + /// that reports a full queue + /// as and a fired token as instead of + /// throwing, so overload costs no exception: or + /// otherwise. + /// + public ValueTask TryVerifyAsync(ReadOnlySpan passwordUtf8, ReadOnlySpan hash, CancellationToken cancellationToken = default) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + if (cancellationToken.IsCancellationRequested) return new ValueTask(BcryptStatus.Cancelled); + if (RentCheck(passwordUtf8, hash, quiet: true) is not { } r) return new ValueTask(BcryptStatus.NoMatch); + return Enqueue(r, cancellationToken, out short version) ? new ValueTask(r, version) : new ValueTask(BcryptStatus.Busy); } /// A new "$2b$" hash of ; see . @@ -262,8 +305,70 @@ public ValueTask HashAsync(string password, int cost, BcryptPrehash preh Recycle(r); throw new ArgumentException(Bcrypt.RefusalOf(password), nameof(password)); } - r.Stored = null; - return Enqueue(r, cancellationToken, out var error) is { } version ? new ValueTask(r, version) : ValueTask.FromException(error!); + return Enqueue(r, cancellationToken, out short version) ? new ValueTask(r, version) : ValueTask.FromException(new BcryptQueueFullException()); + } + + /// + /// A new "$2b$" hash of the password in , held inline instead of in a string: see + /// . Copies the password before it returns and + /// allocates nothing. + /// + /// The password is over 72 bytes. + /// The queue is full (in the returned task); see + /// for a status instead. + public ValueTask HashAsync(ReadOnlySpan passwordUtf8, int cost = Bcrypt.DefaultCost, CancellationToken cancellationToken = default) + { + Bcrypt.CheckCost(cost); + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + if (cancellationToken.IsCancellationRequested) return ValueTask.FromCanceled(cancellationToken); + var r = RentHash(passwordUtf8, cost, quiet: false); + return Enqueue(r, cancellationToken, out short version) ? new ValueTask(r, version) : ValueTask.FromException(new BcryptQueueFullException()); + } + + /// + /// that reports a full queue as + /// and a fired token as instead of throwing; + /// , with the hash, otherwise. + /// + /// The password is over 72 bytes. + public ValueTask TryHashAsync(ReadOnlySpan passwordUtf8, int cost = Bcrypt.DefaultCost, CancellationToken cancellationToken = default) + { + Bcrypt.CheckCost(cost); + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + if (cancellationToken.IsCancellationRequested) return new ValueTask(new BcryptHashResult(BcryptStatus.Cancelled, default)); + var r = RentHash(passwordUtf8, cost, quiet: true); + return Enqueue(r, cancellationToken, out short version) + ? new ValueTask(r, version) + : new ValueTask(new BcryptHashResult(BcryptStatus.Busy, default)); + } + + /// A request checking against ; null when the hash is + /// malformed or the password is over 72 bytes. + Request? RentCheck(ReadOnlySpan password, ReadOnlySpan hash, bool quiet) + { + var r = Rent(); + bool ok; + fixed (Bcrypt.Input* input = &r.Input) ok = Bcrypt.PrepareVerify(password, hash, input); + if (!ok) + { + Recycle(r); + return null; + } + r.Verifying = true; + r.Quiet = quiet; + hash[^Bcrypt.HashChars..].CopyTo(r.Bytes); + return r; + } + + Request RentHash(ReadOnlySpan passwordUtf8, int cost, bool quiet) + { + if (passwordUtf8.Length > Bcrypt.MaxPasswordBytes) throw new ArgumentException(Bcrypt.TooLong, nameof(passwordUtf8)); + var r = Rent(); + Span salt = stackalloc byte[Bcrypt.SaltBytes]; + RandomNumberGenerator.Fill(salt); + fixed (Bcrypt.Input* input = &r.Input) Bcrypt.Prepare(passwordUtf8, salt, cost, 'b', input); + r.Quiet = quiet; + return r; } /// @@ -278,18 +383,18 @@ public void Dispose() Drain(); } - short? Enqueue(Request r, CancellationToken cancellationToken, out Exception? error) + /// Queues and gives the version its ValueTask needs; false when the queue is full, + /// and is recycled. + bool Enqueue(Request r, CancellationToken cancellationToken, out short version) { - error = null; + version = r.Version; // read before a worker can complete and recycle r if (Interlocked.Increment(ref _queued) > _maxQueued) { Interlocked.Decrement(ref _queued); Interlocked.Increment(ref _refused); Recycle(r); - error = new BcryptQueueFullException(); - return null; + return false; } - short version = r.Version; // read before a worker can complete and recycle r r.Refs = 2; r.Enqueued = Stopwatch.GetTimestamp(); r.Token = cancellationToken; @@ -305,14 +410,13 @@ public void Dispose() r.Registration = default; Interlocked.Decrement(ref _queued); Interlocked.Increment(ref _cancelled); - fixed (Bcrypt.Input* input = &r.Input) Bcrypt.Wipe(input, 1); - r.Complete(false, null, new OperationCanceledException(cancellationToken)); + r.CompleteCancelled(); r.Release(); // the queue's reference - return version; + return true; } _ready.Release(); if (Volatile.Read(ref _disposed) != 0) Drain(); // raced Dispose: nothing would take it - return version; + return true; } /// Fails every request still queued; after Dispose. @@ -321,7 +425,7 @@ void Drain() while (TakeFirst() is { } r) { Interlocked.Decrement(ref _queued); - r.Complete(false, null, new ObjectDisposedException(nameof(BcryptQueue))); + r.Complete(BcryptStatus.NoMatch, new ObjectDisposedException(nameof(BcryptQueue))); r.Taken(); } } @@ -435,7 +539,7 @@ void Work() { for (int i = 0; i < n; i++) { - batch[i]?.Complete(false, null, e); + batch[i]?.Complete(BcryptStatus.NoMatch, e); batch[i] = null; } } @@ -455,8 +559,12 @@ public readonly void Finished(int i) { var r = Batch[i]!; Batch[i] = null; - if (r.Stored is { } stored) r.Complete(Bcrypt.Matches(Ct + 6 * i, stored.AsSpan(stored.Length - Bcrypt.HashChars)), null, null); - else r.Complete(false, Bcrypt.Format(Inputs + i, Ct + 6 * i), null); + if (r.Verifying) r.Complete(Bcrypt.Matches(Ct + 6 * i, ((ReadOnlySpan)r.Bytes)[..Bcrypt.HashChars]) ? BcryptStatus.Match : BcryptStatus.NoMatch, null); + else + { + Bcrypt.Format(Inputs + i, Ct + 6 * i, r.Bytes); + r.Complete(BcryptStatus.Hashed, null); + } } } diff --git a/src/CodeFusion.Security.Bcrypt/BcryptStatus.cs b/src/CodeFusion.Security.Bcrypt/BcryptStatus.cs new file mode 100644 index 0000000..594e981 --- /dev/null +++ b/src/CodeFusion.Security.Bcrypt/BcryptStatus.cs @@ -0,0 +1,21 @@ +namespace CodeFusion.Security; + +/// What and report. +public enum BcryptStatus +{ + /// The password doesn't match, the hash is malformed, or the password is over 72 bytes. Also the + /// default, so an unset status never reads as a match. + NoMatch, + + /// The password matches the hash. + Match, + + /// The new hash is made: it is in . + Hashed, + + /// The queue was full, so nothing was queued: answer 503, say. + Busy, + + /// The token fired before a worker took the call, so it never ran. + Cancelled, +} diff --git a/src/CodeFusion.Security.Bcrypt/CodeFusion.Security.Bcrypt.csproj b/src/CodeFusion.Security.Bcrypt/CodeFusion.Security.Bcrypt.csproj index 1f020ee..95f677d 100644 --- a/src/CodeFusion.Security.Bcrypt/CodeFusion.Security.Bcrypt.csproj +++ b/src/CodeFusion.Security.Bcrypt/CodeFusion.Security.Bcrypt.csproj @@ -12,7 +12,7 @@ true CodeFusion.Security.Bcrypt - 1.0.1 + 1.1.0 Krystian Pawłow CodeFusion Copyright (c) 2026 Krystian Pawłow diff --git a/src/CodeFusion.Security.Bcrypt/CompletionCore.cs b/src/CodeFusion.Security.Bcrypt/CompletionCore.cs new file mode 100644 index 0000000..6c59d83 --- /dev/null +++ b/src/CodeFusion.Security.Bcrypt/CompletionCore.cs @@ -0,0 +1,154 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Threading; +using System.Threading.Tasks; +using System.Threading.Tasks.Sources; + +namespace CodeFusion.Security; + +/// +/// The completion half of the runtime's ManualResetValueTaskSourceCore, without its race. That core marks a result +/// ready before it claims the continuation slot (.NET 8 to 11). A caller that sees the result in that window reads it +/// and releases the request, which is reset for its next call at once; the completing thread's claim then lands in +/// that next call, whose continuation runs before its result exists. This core claims the slot first and touches +/// nothing after marking the result ready. The result itself lives in the request; this keeps only whether it failed. +/// +/// A continuation registered after completion (the result arrived between the awaiter's look and its registration) +/// runs at once on the registering thread, as a Task's does, instead of being queued to the pool, which allocates. The +/// flags are honoured as the runtime's core honours them: the ExecutionContext flows, and a synchronization context or +/// task scheduler gets the continuation. +/// +/// +internal struct CompletionCore +{ + static readonly Action Sentinel = static _ => throw new InvalidOperationException("the completion sentinel ran"); + + /// For the tests: runs on the completing thread after the result is marked ready, before the waiting + /// continuation (if any) is invoked. Whatever the caller does meanwhile, this completion must not reach it. + internal static Action? AfterReadyForTests; + + Action? _continuation; + object? _state; + ExecutionContext? _context; + object? _scheduler; // a SynchronizationContext or TaskScheduler that gets the continuation + Exception? _error; + bool _completed; + short _version; + + public readonly short Version => _version; + + /// Ready for the next operation: a new version, nothing completed or waiting. + public void Reset() + { + _version++; + _completed = false; + _error = null; + _state = null; + _context = null; + _scheduler = null; + _continuation = null; + } + + /// Completes successfully; the result must already be written where the reader will look. + public void SetResult() => Signal(); + + public void SetException(Exception error) + { + _error = error; + Signal(); + } + + public readonly ValueTaskSourceStatus GetStatus(short token) + { + Validate(token); + return !Volatile.Read(ref Unsafe.AsRef(in _completed)) ? ValueTaskSourceStatus.Pending + : _error is null ? ValueTaskSourceStatus.Succeeded + : _error is OperationCanceledException ? ValueTaskSourceStatus.Canceled + : ValueTaskSourceStatus.Faulted; + } + + /// Throws the operation's exception, if it failed; after it is ready. + public readonly void GetResult(short token) + { + Validate(token); + if (!Volatile.Read(ref Unsafe.AsRef(in _completed))) throw new InvalidOperationException("the operation hasn't completed"); + if (_error is not null) ExceptionDispatchInfo.Throw(_error); + } + + public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) + { + ArgumentNullException.ThrowIfNull(continuation); + Validate(token); + // Everything goes in before the continuation: once it's published, Signal may run it at once. + if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) _context = ExecutionContext.Capture(); + if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) _scheduler = CurrentScheduler(); + _state = state; + Action? previous = Interlocked.CompareExchange(ref _continuation, continuation, null); + if (previous is null) return; + if (!ReferenceEquals(previous, Sentinel)) throw new InvalidOperationException("a pooled ValueTask was awaited twice"); + // Completed between the awaiter's look and now. Signal may be a few instructions short of marking the result + // ready; then run the continuation here, unless the stack is deep. + SpinWait spin = default; + while (!Volatile.Read(ref _completed)) spin.SpinOnce(); + if (RuntimeHelpers.TryEnsureSufficientExecutionStack()) Invoke(continuation, state, _context, _scheduler); + else ThreadPool.UnsafeQueueUserWorkItem(static p => p.Invoke(), new Late(continuation, state, _context, _scheduler), preferLocal: true); + } + + /// + /// Takes the waiting continuation (or leaves the sentinel for one that comes later) and its context before marking + /// the result ready, and touches nothing after: whoever sees the result ready may read it and reset the core for + /// its next operation at once. + /// + void Signal() + { + Action? waiting = Interlocked.Exchange(ref _continuation, Sentinel); + if (ReferenceEquals(waiting, Sentinel)) throw new InvalidOperationException("the operation completed twice"); + object? state = _state, scheduler = _scheduler; + ExecutionContext? context = _context; + Volatile.Write(ref _completed, true); // after the result, and the last write here + AfterReadyForTests?.Invoke(); + if (waiting is not null) Invoke(waiting, state, context, scheduler); + } + + static object? CurrentScheduler() + { + if (SynchronizationContext.Current is { } sc && sc.GetType() != typeof(SynchronizationContext)) return sc; + return TaskScheduler.Current is { } ts && ts != TaskScheduler.Default ? ts : null; + } + + static void Invoke(Action continuation, object? state, ExecutionContext? context, object? scheduler) + { + if (context is null && scheduler is null) continuation(state); // every await: the state machine flows its own context + else if (context is null) Dispatch(continuation, state, scheduler); + else ExecutionContext.Run(context, static p => ((Late)p!).Dispatch(), new Late(continuation, state, null, scheduler)); + } + + static void Dispatch(Action continuation, object? state, object? scheduler) + { + switch (scheduler) + { + case SynchronizationContext sc: + sc.Post(static p => ((Late)p!).Dispatch(), new Late(continuation, state, null, null)); + break; + case TaskScheduler ts: + _ = Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); + break; + default: + continuation(state); + break; + } + } + + /// A continuation carried to a context, a scheduler or the pool: only off the allocation-free path. + sealed class Late(Action continuation, object? state, ExecutionContext? context, object? scheduler) + { + public void Invoke() => CompletionCore.Invoke(continuation, state, context, scheduler); + public void Dispatch() => CompletionCore.Dispatch(continuation, state, scheduler); + } + + readonly void Validate(short token) + { + if (token != _version) throw new InvalidOperationException("a BcryptQueue result was awaited twice or after it was reused; await each ValueTask once"); + } +} diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs index 97cc888..4bd3e24 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -117,4 +118,96 @@ public async Task QueuedHashAllocatesOnlyItsString() } Assert.Equal(oneString * Calls, least); } + + static readonly byte[] Hash4Ascii = Encoding.ASCII.GetBytes(Hash4); + + [Fact] + public void Utf8VerifyAllocatesNothing() + { + Assert.Equal(0, OnThisThread(() => Assert.True(Bcrypt.Verify("password123"u8, Hash4Ascii)))); + Assert.Equal(0, OnThisThread(() => Assert.False(Bcrypt.Verify("wrong"u8, Hash4Ascii)))); + Assert.Equal(0, OnThisThread(() => Assert.False(Bcrypt.Verify("password123"u8, "malformed"u8)))); + byte[] tooLong = new byte[100]; + Assert.Equal(0, OnThisThread(() => Assert.False(Bcrypt.Verify(tooLong, Hash4Ascii)))); + } + + [Fact] + public void Utf8HashAllocatesNothing() + { + byte[] destination = new byte[Bcrypt.HashLength]; + Assert.Equal(0, OnThisThread(() => Assert.True(Bcrypt.Hash("password123"u8, 4, destination) == 60))); + } + + [Fact] + public async Task QueuedUtf8VerifyAllocatesNothing() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); + long least = long.MaxValue; + for (int t = 0; t < Tries; t++) + { + long before = GC.GetTotalAllocatedBytes(precise: true); + for (int i = 0; i < Calls; i++) + { + ValueTask a = q.VerifyAsync("password123"u8, Hash4Ascii), b = q.VerifyAsync("wrong"u8, Hash4Ascii); + ValueTask c = q.TryVerifyAsync("password123"u8, Hash4Ascii), d = q.TryVerifyAsync("wrong"u8, Hash4Ascii); + Assert.True(await a & !await b); + Assert.True(await c == BcryptStatus.Match & await d == BcryptStatus.NoMatch); // Assert.Equal allocates + } + if (t > 0) least = Math.Min(least, GC.GetTotalAllocatedBytes(precise: true) - before); + } + Assert.Equal(0, least); + } + + [Fact] + public async Task QueuedUtf8HashAllocatesNothing() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); + byte[] destination = new byte[Bcrypt.HashLength]; + long least = long.MaxValue; + for (int t = 0; t < Tries; t++) + { + long before = GC.GetTotalAllocatedBytes(precise: true); + for (int i = 0; i < Calls; i++) + { + ValueTask a = q.HashAsync("password123"u8, 4); + ValueTask b = q.TryHashAsync("password123"u8, 4); + (await a).CopyTo(destination); + var tried = await b; + Assert.True(tried.Status == BcryptStatus.Hashed && tried.Hash.Length == 60); + } + if (t > 0) least = Math.Min(least, GC.GetTotalAllocatedBytes(precise: true) - before); + } + Assert.Equal(0, least); + Assert.True(Bcrypt.Verify("password123"u8, destination)); + } + + /// A full queue and a cancelled token are statuses: no exception, no task, nothing allocated. + [Fact] + public async Task BusyAndCancelledAllocateNothing() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1, Lanes = 1, MaxQueued = 1 }); + var slow = q.VerifyAsync("slow", Bcrypt.Hash("slow", 13)); + while (q.QueueLength != 0) await Task.Delay(1); + var queued = q.TryVerifyAsync("password123"u8, Hash4Ascii); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + CancellationToken cancelled = cts.Token; + long least = long.MaxValue; + for (int t = 0; t < Tries; t++) + { + long before = GC.GetTotalAllocatedBytes(precise: true); + for (int i = 0; i < Calls; i++) + { + Assert.True(await q.TryVerifyAsync("password123"u8, Hash4Ascii) == BcryptStatus.Busy); + Assert.True((await q.TryHashAsync("password123"u8, 4)).Status == BcryptStatus.Busy); + Assert.True(await q.TryVerifyAsync("password123"u8, Hash4Ascii, cancelled) == BcryptStatus.Cancelled); + Assert.True((await q.TryHashAsync("password123"u8, 4, cancelled)).Status == BcryptStatus.Cancelled); + } + if (t > 0) least = Math.Min(least, GC.GetTotalAllocatedBytes(precise: true) - before); + } + Assert.False(slow.IsCompleted); // the queue stayed full throughout + Assert.Equal(0, least); + Assert.True(await slow); + Assert.Equal(BcryptStatus.Match, await queued); + } } diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs index db63849..8a53433 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs @@ -211,7 +211,7 @@ public async Task HashAsyncRefusesBadArgumentsAtOnce() using var q = Queue(); Assert.Throws(() => q.HashAsync(new string('a', 73), 4, Ct)); Assert.Throws(() => q.HashAsync("x", 3, Ct)); - Assert.Throws(() => q.HashAsync(null!, 4, Ct)); + Assert.Throws(() => q.HashAsync((string)null!, 4, Ct)); Assert.Throws(() => q.VerifyAsync(null!, Hash4, Ct)); Assert.Throws(() => q.VerifyAsync("x", null!, Ct)); Assert.True(await q.VerifyAsync("password123", Hash4, Ct)); // the refusals left nothing behind diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs new file mode 100644 index 0000000..b2122ac --- /dev/null +++ b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs @@ -0,0 +1,319 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +namespace CodeFusion.Security.Tests; + +/// The byte overloads of : copied before they return, and the Try forms' statuses. +public class BcryptQueueUtf8Tests +{ + static readonly string Hash4 = Bcrypt.Hash("password123", 4); + static readonly byte[] Hash4Ascii = Encoding.ASCII.GetBytes(Hash4); + static readonly string SlowHash = Bcrypt.Hash("slow", 13); + + static CancellationToken Ct => TestContext.Current.CancellationToken; + + static BcryptQueue Queue(int threads = 1, int lanes = 5, int? maxQueued = null) => + new(new BcryptQueueOptions { Threads = threads, Lanes = lanes, MaxQueued = maxQueued }); + + static async Task> Occupy(BcryptQueue q) + { + var slow = q.VerifyAsync("slow", SlowHash, Ct); + var sw = Stopwatch.StartNew(); + while (q.QueueLength != 0) + { + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(10), "timed out"); + await Task.Delay(1, Ct); + } + return slow; + } + + [Fact] + public async Task VerifyAsyncAgreesWithTheStringOverload() + { + using var q = Queue(threads: 2); + var random = new Random(7); + string[] passwords = ["", "\0", "password123", new string('a', 72), new string('a', 73), new string('é', 36), new string('a', 69) + "😀", "pässwörd"]; + foreach (string password in passwords.Concat(Enumerable.Range(0, 20).Select(_ => RandomText(random)))) + { + byte[] utf8 = Encoding.UTF8.GetBytes(password); + foreach (char revision in "aby") + { + var salt = new byte[16]; + random.NextBytes(salt); + string hash = BCrypt.Net.BCrypt.HashPassword(password, Support.Settings(4, salt, revision)); + byte[] ascii = Encoding.ASCII.GetBytes(hash); + bool expected = Bcrypt.Verify(password, hash); + Assert.Equal(utf8.Length <= 72, expected); + Assert.Equal(expected, await q.VerifyAsync(password, hash, Ct)); + Assert.Equal(expected, await q.VerifyAsync(utf8, ascii, Ct)); + Assert.Equal(expected ? BcryptStatus.Match : BcryptStatus.NoMatch, await q.TryVerifyAsync(utf8, ascii, Ct)); + Assert.False(await q.VerifyAsync([.. utf8, (byte)'x'], ascii, Ct)); + } + } + } + + /// Up to 24 characters from ASCII, Latin-1, CJK and astral planes: 1 to 4 bytes each, some past 72. + static string RandomText(Random random) + { + var text = new StringBuilder(); + for (int i = random.Next(25); i > 0; i--) + text.Append(random.Next(4) switch + { + 0 => ((char)random.Next(0, 128)).ToString(), + 1 => ((char)random.Next(0xa0, 0x800)).ToString(), + 2 => ((char)random.Next(0x4e00, 0x9fff)).ToString(), + _ => char.ConvertFromUtf32(random.Next(0x1f300, 0x1f64f)), + }); + return text.ToString(); + } + + [Fact] + public async Task HashAsyncMakesAHashEveryoneChecks() + { + using var q = Queue(); + BcryptHash hash = await q.HashAsync("pässwörd\0"u8, 5, Ct); + Assert.Equal(60, hash.Length); + string text = hash.ToString(); + Assert.StartsWith("$2b$05$", text, StringComparison.Ordinal); + Assert.True(Bcrypt.Verify("pässwörd\0", text)); + Assert.True(BCrypt.Net.BCrypt.Verify("pässwörd\0", text)); + Assert.True(await q.VerifyAsync("pässwörd\0"u8, hash.AsSpan(), Ct)); + + var tried = await q.TryHashAsync(""u8, 4, Ct); + Assert.Equal(BcryptStatus.Hashed, tried.Status); + Assert.True(Bcrypt.Verify("", tried.Hash.ToString())); + } + + [Fact] + public async Task AHashCopiesAndFormatsExactly() + { + using var q = Queue(); + BcryptHash hash = await q.HashAsync("x"u8, 4, Ct); + string text = hash.ToString(); + + var bytes = Enumerable.Repeat((byte)0xEE, 61).ToArray(); + hash.CopyTo(bytes); + Assert.Equal(text, Encoding.ASCII.GetString(bytes, 0, 60)); + Assert.Equal(0xEE, bytes[60]); + Assert.Throws(() => hash.CopyTo(new byte[59])); + + Assert.False(hash.TryFormat(new byte[59], out int written)); + Assert.Equal(0, written); + Assert.True(hash.TryFormat(new byte[60], out written)); + Assert.Equal(60, written); + + var chars = new char[70]; + Assert.False(hash.TryFormat(chars.AsSpan(0, 59), out written)); + Assert.Equal(0, written); + Assert.True(hash.TryFormat(chars, out written)); + Assert.Equal(text, new string(chars, 0, written)); + Assert.Equal(text, $"{hash}"); + + Assert.Equal(0, default(BcryptHash).Length); + Assert.Equal("", default(BcryptHash).ToString()); + Assert.True(default(BcryptHash).TryFormat(Span.Empty, out written)); + Assert.Equal(0, written); + } + + /// The caller's buffers belong to it again as soon as the call returns, while the hash still waits. + [Fact] + public async Task BuffersCanBeReusedAsSoonAsTheCallReturns() + { + using var q = Queue(); + var slow = await Occupy(q); + byte[] password = "password123"u8.ToArray(), hash = (byte[])Hash4Ascii.Clone(), newPassword = "new one"u8.ToArray(); + var check = q.VerifyAsync(password, hash, Ct); + var tried = q.TryVerifyAsync(password, hash, Ct); + var made = q.HashAsync(newPassword, 4, Ct); + password.AsSpan().Fill((byte)'z'); + hash.AsSpan(29).Fill((byte)'.'); + newPassword.AsSpan().Clear(); + Assert.Equal(3, q.QueueLength); + + Assert.True(await slow); + Assert.True(await check); + Assert.Equal(BcryptStatus.Match, await tried); + Assert.True(Bcrypt.Verify("new one", (await made).ToString())); + } + + [Fact] + public async Task MalformedHashesAndLongPasswordsAreAnsweredWithoutQueueing() + { + using var q = Queue(); + var malformed = q.VerifyAsync("password123"u8, "$2b$04$nope"u8, Ct); + var tooLong = q.VerifyAsync(new byte[73], Hash4Ascii, Ct); + var triedMalformed = q.TryVerifyAsync("password123"u8, Hash4Ascii.AsSpan(0, 59), Ct); + Assert.True(malformed.IsCompletedSuccessfully && tooLong.IsCompletedSuccessfully && triedMalformed.IsCompletedSuccessfully); + Assert.False(await malformed); + Assert.False(await tooLong); + Assert.Equal(BcryptStatus.NoMatch, await triedMalformed); + Assert.Equal(0, q.HashesRun); + + Assert.Equal("passwordUtf8", Assert.Throws(() => q.HashAsync(new byte[73], 4, Ct)).ParamName); + Assert.Throws(() => q.TryHashAsync(new byte[73], 4, Ct)); + Assert.Throws(() => q.HashAsync("x"u8, 3, Ct)); + Assert.Throws(() => q.TryHashAsync("x"u8, 32, Ct)); + Assert.True(await q.VerifyAsync("password123"u8, Hash4Ascii, Ct)); // the refusals left nothing behind + Assert.Equal(1, q.HashesRun); + } + + [Fact] + public async Task AFullQueueIsBusyWithoutAnException() + { + using var q = Queue(maxQueued: 1); + var slow = await Occupy(q); + var queued = q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct); + // Refused on this thread, so only this thread's exceptions count: other tests run meanwhile. + int exceptions = 0, thread = Environment.CurrentManagedThreadId; + EventHandler count = (_, _) => + { + if (Environment.CurrentManagedThreadId == thread) Interlocked.Increment(ref exceptions); + }; + AppDomain.CurrentDomain.FirstChanceException += count; + ValueTask busy; + ValueTask busyHash; + try + { + busy = q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct); + busyHash = q.TryHashAsync("x"u8, 4, Ct); + } + finally { AppDomain.CurrentDomain.FirstChanceException -= count; } + Assert.Equal(0, exceptions); + Assert.True(busy.IsCompletedSuccessfully && busyHash.IsCompletedSuccessfully); + Assert.Equal(BcryptStatus.Busy, await busy); + Assert.Equal(BcryptStatus.Busy, (await busyHash).Status); + Assert.Equal(0, (await busyHash).Hash.Length); + + // The throwing forms still throw. + await Assert.ThrowsAsync(async () => await q.VerifyAsync("password123"u8, Hash4Ascii, Ct)); + await Assert.ThrowsAsync(async () => await q.HashAsync("x"u8, 4, Ct)); + Assert.Equal(4, q.Refused); + + Assert.True(await slow); + Assert.Equal(BcryptStatus.Match, await queued); + Assert.Equal(BcryptStatus.Match, await q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct)); // room again + Assert.Equal(3, q.HashesRun); + } + + [Fact] + public async Task CancellingBeforeAWorkerTakesItIsCancelledWithoutAnException() + { + using var q = Queue(); + var slow = await Occupy(q); + using var cts = new CancellationTokenSource(); + var check = q.TryVerifyAsync("password123"u8, Hash4Ascii, cts.Token); + var hash = q.TryHashAsync("x"u8, 4, cts.Token); + var throwing = q.VerifyAsync("password123"u8, Hash4Ascii, cts.Token); + var throwingHash = q.HashAsync("x"u8, 4, cts.Token); + Assert.Equal(4, q.QueueLength); + + await cts.CancelAsync(); + var sw = Stopwatch.StartNew(); + while (!(check.IsCompleted && hash.IsCompleted && throwing.IsCompleted && throwingHash.IsCompleted)) + { + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(10), "timed out"); + await Task.Delay(1, Ct); + } + // Succeeded, not cancelled: the Try forms carry no exception. + Assert.True(check.IsCompletedSuccessfully && hash.IsCompletedSuccessfully); + Assert.True(throwing.IsCanceled && throwingHash.IsCanceled); + Assert.Equal(BcryptStatus.Cancelled, await check); + var result = await hash; + Assert.Equal(BcryptStatus.Cancelled, result.Status); + Assert.Equal(0, result.Hash.Length); + + var ex = await Assert.ThrowsAnyAsync(async () => await throwing); + Assert.Equal(cts.Token, ex.CancellationToken); + await Assert.ThrowsAnyAsync(async () => await throwingHash); + Assert.False(slow.IsCompleted); // ended while the worker was still busy + Assert.Equal(4, q.Cancelled); + Assert.Equal(0, q.QueueLength); + + Assert.True(await slow); + Assert.Equal(BcryptStatus.Match, await q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct)); + Assert.Equal(2, q.HashesRun); // the cancelled ones never ran + } + + [Fact] + public async Task AnAlreadyCancelledTokenIsAnsweredAtOnce() + { + using var q = Queue(); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + var check = q.TryVerifyAsync("password123"u8, Hash4Ascii, cts.Token); + var hash = q.TryHashAsync("x"u8, 4, cts.Token); + Assert.True(check.IsCompletedSuccessfully && hash.IsCompletedSuccessfully); + Assert.Equal(BcryptStatus.Cancelled, await check); + Assert.Equal(BcryptStatus.Cancelled, (await hash).Status); + Assert.True(q.VerifyAsync("password123"u8, Hash4Ascii, cts.Token).IsCanceled); + Assert.True(q.HashAsync("x"u8, 4, cts.Token).IsCanceled); + Assert.Equal(0, q.HashesRun); + Assert.Equal(0, q.QueueLength); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ATokenFiringWhileTheCallIsQueuedIsCancelled(bool hash) + { + using var q = Queue(); + using var cts = new CancellationTokenSource(); + q.BeforeLinkForTests = cts.Cancel; + BcryptStatus status = hash ? (await q.TryHashAsync("x"u8, 4, cts.Token)).Status : await q.TryVerifyAsync("password123"u8, Hash4Ascii, cts.Token); + q.BeforeLinkForTests = null; + Assert.Equal(BcryptStatus.Cancelled, status); + Assert.Equal(1, q.Cancelled); + Assert.Equal(0, q.Entries); + Assert.Equal(BcryptStatus.Match, await q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct)); + Assert.Equal(1, q.HashesRun); + } + + [Fact] + public async Task DisposeStillThrowsForTheTryForms() + { + var q = Queue(); + var slow = await Occupy(q); + var waiting = q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct); + q.Dispose(); + Assert.True(await slow); + await Assert.ThrowsAsync(async () => await waiting); + Assert.Throws(() => q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct)); + Assert.Throws(() => q.TryHashAsync("x"u8, 4, Ct)); + Assert.Throws(() => q.VerifyAsync("password123"u8, Hash4Ascii, Ct)); + Assert.Throws(() => q.HashAsync("x"u8, 4, Ct)); + } + + /// Requests go back to one pool whichever overload used them: no state leaks from one kind to the next. + [Fact] + public async Task EveryKindOfCallSharesThePoolSoundly() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 2, Lanes = 3 }); + var tasks = Enumerable.Range(0, 160).Select(i => Task.Run(async () => + { + byte[] mine = Encoding.UTF8.GetBytes($"pw{i}"); + switch (i % 8) + { + case 0: Assert.True(await q.VerifyAsync("password123", Hash4, Ct)); break; + case 1: Assert.False(await q.VerifyAsync("password124"u8.ToArray(), Hash4Ascii, Ct)); break; + case 2: Assert.Equal(BcryptStatus.Match, await q.TryVerifyAsync("password123"u8.ToArray(), Hash4Ascii, Ct)); break; + case 3: Assert.Equal(BcryptStatus.NoMatch, await q.TryVerifyAsync("password12"u8.ToArray(), Hash4Ascii, Ct)); break; + case 4: Assert.True(Bcrypt.Verify($"pw{i}", await q.HashAsync($"pw{i}", 4, Ct))); break; + case 5: Assert.True(Bcrypt.Verify($"pw{i}", (await q.HashAsync(mine, 4, Ct)).ToString())); break; + case 6: + var r = await q.TryHashAsync(mine, 4, Ct); + Assert.Equal(BcryptStatus.Hashed, r.Status); + Assert.True(Bcrypt.Verify($"pw{i}", r.Hash.ToString())); + break; + default: Assert.False(await q.VerifyAsync("password123", Bcrypt.Hash("other", 4), Ct)); break; + } + }, Ct)).ToArray(); + await Task.WhenAll(tasks); + Assert.Equal(160, q.HashesRun); + Assert.Equal(0, q.QueueLength); + } +} diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs new file mode 100644 index 0000000..007affb --- /dev/null +++ b/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs @@ -0,0 +1,176 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +// The tests read results the moment they are ready, synchronously, as the callers that hit the race did. +#pragma warning disable xUnit1031 + +namespace CodeFusion.Security.Tests; + +/// +/// How a queued call completes. The runtime's ManualResetValueTaskSourceCore marks a result ready before it claims +/// the continuation slot; a caller that read the result in between and released the request had the completion land +/// in its next call, whose continuation then ran before its result existed. These tests pause the completing thread +/// right after the result is ready (a static hook, so they run alone) or oversubscribe the cores to widen that window. +/// +[Collection(nameof(Measuring))] +public class CompletionTests +{ + static readonly string Hash4 = Bcrypt.Hash("password123", 4); + static readonly string SlowHash = Bcrypt.Hash("slow", 13); + + static CancellationToken Ct => TestContext.Current.CancellationToken; + + static readonly AsyncLocal Local = new(); + + static async Task AwaitIt(ValueTask check) => await check; + + /// Pauses the first completion after its result is ready, until resume is set. + sealed class Pause : IDisposable + { + int _once; + public readonly ManualResetEventSlim Paused = new(), Resume = new(); + + public Pause() => CompletionCore.AfterReadyForTests = () => + { + if (Interlocked.Exchange(ref _once, 1) != 0) return; + Paused.Set(); + Resume.Wait(TimeSpan.FromSeconds(30)); + }; + + public void Dispose() + { + CompletionCore.AfterReadyForTests = null; + Resume.Set(); + Paused.Dispose(); + Resume.Dispose(); + } + } + + [Fact] + public async Task ACallerThatReadsAtOnceDoesNotGetTheCompletionInItsNextCall() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); + using var pause = new Pause(); + var first = q.VerifyAsync("password123", Hash4, Ct); + Assert.True(pause.Paused.Wait(TimeSpan.FromSeconds(10), Ct)); + + // The completing thread has marked the result ready and stopped there. Read it, which frees the request. + Assert.True(first.IsCompleted); + Assert.True(first.GetAwaiter().GetResult()); + // The next call gets that request back and waits on it with a continuation. + var next = q.VerifyAsync("slow", SlowHash, Ct); + Assert.Same(Source(first), Source(next)); + var awaiting = AwaitIt(next); + pause.Resume.Set(); + + // Had the completion claimed the slot only now, it would have run that continuation before next's result. + Assert.True(await awaiting); + } + + [Fact] + public async Task AContinuationRegisteredAfterCompletionRunsAtOnceOnItsOwnThread() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); + using var pause = new Pause(); + var check = q.VerifyAsync("password123", Hash4, Ct); + Assert.True(pause.Paused.Wait(TimeSpan.FromSeconds(10), Ct)); + + // As an awaiter that looked just before the result came: it registers after completion. + Thread? ranOn = null; + check.GetAwaiter().UnsafeOnCompleted(() => ranOn = Thread.CurrentThread); + Assert.Same(Thread.CurrentThread, ranOn); // inline, not queued to the pool + pause.Resume.Set(); + Assert.True(check.GetAwaiter().GetResult()); + } + + /// + /// Many callers each read their result the moment it is ready and queue their next call at once, which the pool + /// most often hands the request just freed. With twice as many callers as cores, all spinning, and as many workers, + /// the threads that complete calls are preempted often. The runtime's window is a few instructions, so this can't + /// force it the way the paused test above does; it guards the whole path under load. + /// + [Fact] + public void CallersReadingAtOnceGetTheirOwnResultsWithTheCoresOversubscribed() + { + int cores = Environment.ProcessorCount; + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = cores, Lanes = 2 }); + long rounds = 0, failures = 0; + string? firstFailure = null; + var stop = Stopwatch.StartNew(); + var callers = new Thread[cores * 2]; + for (int c = 0; c < callers.Length; c++) + { + int caller = c; + callers[c] = new Thread(() => + { + for (int i = 0; stop.Elapsed < TimeSpan.FromSeconds(2); i++) + { + try + { + bool expected = (i + caller) % 2 == 0; + var spun = q.VerifyAsync(expected ? "password123" : "password124", Hash4); + while (!spun.IsCompleted) Thread.SpinWait(20); // read the moment it is ready + bool spunResult = spun.GetAwaiter().GetResult(); + // At once, the next call: a continuation registered on what is likely the same request. + bool awaited = q.VerifyAsync(expected ? "password124" : "password123", Hash4).AsTask().GetAwaiter().GetResult(); + if (spunResult != expected || awaited == expected) throw new InvalidOperationException("a caller got another call's result"); + Interlocked.Increment(ref rounds); + } + catch (Exception e) + { + if (Interlocked.Increment(ref failures) == 1) firstFailure = e.ToString(); + } + } + }) { IsBackground = true }; + callers[c].Start(); + } + foreach (var t in callers) Assert.True(t.Join(TimeSpan.FromSeconds(60))); + Assert.True(failures == 0, $"{failures} of {rounds + failures} rounds failed; the first: {firstFailure}"); + Assert.True(rounds > 100, $"only {rounds} rounds ran"); + } + + sealed class CountingContext : SynchronizationContext + { + public int Posts; + + public override void Post(SendOrPostCallback d, object? state) + { + Interlocked.Increment(ref Posts); + ThreadPool.QueueUserWorkItem(_ => d(state)); + } + } + + [Fact] + public async Task AnAwaitUnderASynchronizationContextResumesThere() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); + var context = new CountingContext(); + var previous = SynchronizationContext.Current; + Task awaiting; + SynchronizationContext.SetSynchronizationContext(context); + try { awaiting = AwaitIt(q.VerifyAsync("slow", SlowHash, Ct)); } + finally { SynchronizationContext.SetSynchronizationContext(previous); } + Assert.True(await awaiting); + Assert.Equal(1, context.Posts); + } + + [Fact] + public async Task OnCompletedFlowsTheExecutionContext() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); + var check = q.VerifyAsync("slow", SlowHash, Ct); + var seen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Local.Value = "caller"; + check.GetAwaiter().OnCompleted(() => seen.SetResult(Local.Value)); + Local.Value = "changed"; + Assert.Equal("caller", await seen.Task); + Assert.True(check.GetAwaiter().GetResult()); + } + + static object Source(ValueTask task) => + typeof(ValueTask).GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(task)!; +} diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs new file mode 100644 index 0000000..2171224 --- /dev/null +++ b/tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs @@ -0,0 +1,181 @@ +using System; +using System.Linq; +using System.Text; +using FsCheck; +using FsCheck.Fluent; +using FsCheck.Xunit; +using Xunit; +using static CodeFusion.Security.Tests.Support; + +namespace CodeFusion.Security.Tests; + +/// The byte overloads of , checked against the string ones and BCrypt.Net-Next. +public class Utf8Tests +{ + static readonly string Hash4 = Bcrypt.Hash("password123", 4); + + static byte[] Ascii(string hash) => Encoding.ASCII.GetBytes(hash); + + static string HashOf(ReadOnlySpan password, int cost) + { + Span destination = stackalloc byte[Bcrypt.HashLength]; + int written = Bcrypt.Hash(password, cost, destination); + Assert.Equal(Bcrypt.HashLength, written); + return Encoding.ASCII.GetString(destination); + } + + /// Text at the edges: empty, exactly 72 bytes, 73, a four-byte character ending at byte 72 or 73, NULs. + public static TheoryData Edges => new() + { + "", + "\0", + "a\0b", + new string('a', 72), + new string('a', 73), + new string('a', 68) + "😀", // 72 bytes + new string('a', 69) + "😀", // 73 bytes + new string('é', 36), // 72 bytes in 36 characters + new string('é', 36) + "x", + "pässwörd €", + }; + + [Theory] + [MemberData(nameof(Edges))] + public void VerifyAgreesWithTheStringOverload(string password) + { + byte[] utf8 = Encoding.UTF8.GetBytes(password); + bool fits = utf8.Length <= Bcrypt.MaxPasswordBytes; + Assert.Equal(fits, Bcrypt.PasswordFits(password)); + foreach (char revision in "aby") + { + // A hash of the text cut to 72 bytes, as other libraries would make it: a longer password must still fail. + string hash = BCrypt.Net.BCrypt.HashPassword(password, Settings(4, new byte[16], revision)); + Assert.Equal(Bcrypt.Verify(password, hash), Bcrypt.Verify(utf8, Ascii(hash))); + Assert.Equal(fits, Bcrypt.Verify(utf8, Ascii(hash))); + Assert.False(Bcrypt.Verify([.. utf8, (byte)'!'], Ascii(hash))); + } + } + + [Theory] + [MemberData(nameof(Edges))] + public void HashMakesWhatTheStringOverloadsAndBCryptNetNextCheck(string password) + { + byte[] utf8 = Encoding.UTF8.GetBytes(password); + if (utf8.Length > Bcrypt.MaxPasswordBytes) + { + Assert.Throws(() => Bcrypt.Hash(password, 4)); + var ex = Assert.Throws(() => Bcrypt.Hash(utf8, 4, new byte[60])); + Assert.Equal("passwordUtf8", ex.ParamName); + return; + } + string hash = HashOf(utf8, 5); + Assert.StartsWith("$2b$05$", hash, StringComparison.Ordinal); + Assert.True(Bcrypt.Verify(password, hash)); + Assert.True(BCrypt.Net.BCrypt.Verify(password, hash)); + Assert.False(Bcrypt.Verify(password + "!", hash)); + } + + [Property(MaxTest = 40)] + public Property AnyPasswordGivesTheStringOverloadsAnswers() => Prop.ForAll( + Passwords(), + Gen.Zip(Salts(), Gen.Elements('a', 'b', 'y')).ToArbitrary(), + (password, t) => + { + var (salt, revision) = t; + byte[] utf8 = Encoding.UTF8.GetBytes(password); + string hash = Bcrypt.HashWith(password, salt, 4, revision, BcryptPrehash.None); + byte[] ascii = Ascii(hash); + bool other = Bcrypt.Verify(password + "x", hash); + return Bcrypt.Verify(utf8, ascii) + && Bcrypt.Verify(password, hash) + && Bcrypt.Verify([.. utf8, (byte)'x'], ascii) == other + && Bcrypt.Verify(password, HashOf(utf8, 4)); + }); + + [Theory] + [MemberData(nameof(TestVectorTests.Utf8), MemberType = typeof(TestVectorTests))] + public void VerifiesUtf8Vectors(string password, string hash) + { + Assert.True(Bcrypt.Verify(Encoding.UTF8.GetBytes(password), Ascii(hash))); + Assert.False(Bcrypt.Verify(Encoding.UTF8.GetBytes(password + "x"), Ascii(hash))); + } + + /// Bytes that aren't UTF-8 are the key as they are, as in OpenBSD and Openwall: no string can carry them. + [Theory] + [MemberData(nameof(TestVectorTests.NotUtf8), MemberType = typeof(TestVectorTests))] + [MemberData(nameof(TestVectorTests.Openwall), MemberType = typeof(TestVectorTests))] + public void VerifiesVectorsWhosePasswordsAreBytes(byte[] password, string hash) => + Assert.Equal(password.Length <= Bcrypt.MaxPasswordBytes, Bcrypt.Verify(password, Ascii(hash))); + + public static TheoryData Malformed => new() + { + "", + "malformed", + "$2b$04$nope", + Hash4[..^1], // one character short + Hash4 + ".", // one too many + Hash4[..29], // settings only + Hash4.Replace("$2b$", "$2x$", StringComparison.Ordinal), + Hash4.Replace("$04$", "$03$", StringComparison.Ordinal), + Hash4.Replace("$04$", "$32$", StringComparison.Ordinal), + BcryptQueueTests.StrayChecksumBits(Hash4), + Hash4[..40] + "!" + Hash4[41..], // a character outside the alphabet + }; + + [Theory] + [MemberData(nameof(Malformed))] + public void AMalformedHashIsFalse(string hash) + { + Assert.False(Bcrypt.Verify("password123", hash)); + Assert.False(Bcrypt.Verify("password123"u8, Ascii(hash))); + } + + /// A byte past ASCII is no hash character, though widened to a char it is one of Latin-1's. + [Fact] + public void ABytePastAsciiIsNotAHashCharacter() + { + byte[] hash = Ascii(Hash4); + Assert.True(Bcrypt.Verify("password123"u8, hash)); + foreach (int at in new[] { 0, 3, 5, 10, 40, 59 }) + { + byte[] bad = (byte[])hash.Clone(); + bad[at] = 0xC3; + Assert.False(Bcrypt.Verify("password123"u8, bad)); + } + Assert.False(Bcrypt.Verify("password123"u8, [.. hash, 0])); + Assert.False(Bcrypt.Verify("password123"u8, new byte[1000])); + } + + /// The original "$2$" revision, 59 characters and no terminating NUL in the key. + [Fact] + public void ChecksTheOriginalRevision() + { + const string hash = "$2$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK"; + Assert.Equal(Bcrypt.Verify("U*U*", hash), Bcrypt.Verify("U*U*"u8, Ascii(hash))); + string ours = Bcrypt.Hash("U*U*", hash[..28]); + Assert.True(Bcrypt.Verify("U*U*"u8, Ascii(ours))); + Assert.False(Bcrypt.Verify("U*U*\0"u8, Ascii(ours))); + } + + [Fact] + public void HashRefusesBadArguments() + { + Assert.Throws(() => Bcrypt.Hash("x"u8, 4, new byte[59])); + Assert.Throws(() => Bcrypt.Hash("x"u8, 3, new byte[60])); + Assert.Throws(() => Bcrypt.Hash("x"u8, 32, new byte[60])); + Assert.Throws(() => Bcrypt.Hash(new byte[73], 4, new byte[60])); + } + + /// A destination longer than the hash keeps its bytes past it. + [Fact] + public void HashWritesOnlyItsSixtyBytes() + { + var destination = Enumerable.Repeat((byte)0xEE, 64).ToArray(); + Assert.Equal(60, Bcrypt.Hash("x"u8, 4, destination)); + Assert.All(destination[60..], b => Assert.Equal(0xEE, b)); + Assert.True(Bcrypt.Verify("x", Encoding.ASCII.GetString(destination, 0, 60))); + } + + [Fact] + public void TwoHashesOfOnePasswordDiffer() => Assert.NotEqual(HashOf("x"u8, 4), HashOf("x"u8, 4)); +} From 7ed1b962b79f790203e59a0fa147ab7842586208 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Paw=C5=82ow?= Date: Tue, 20 Oct 2026 07:15:43 +0200 Subject: [PATCH 2/8] Tests: wait for the paused thread before disposing, check the original revision for real, bound the Busy test's wait --- tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs | 6 +++++- tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs | 5 ++++- tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs | 6 +++--- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs index 4bd3e24..f5251ed 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs @@ -187,7 +187,11 @@ public async Task BusyAndCancelledAllocateNothing() { using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1, Lanes = 1, MaxQueued = 1 }); var slow = q.VerifyAsync("slow", Bcrypt.Hash("slow", 13)); - while (q.QueueLength != 0) await Task.Delay(1); + for (int i = 0; q.QueueLength != 0; i++) + { + Assert.True(i < 10_000, "the slow check was never taken"); + await Task.Delay(1, TestContext.Current.CancellationToken); + } var queued = q.TryVerifyAsync("password123"u8, Hash4Ascii); using var cts = new CancellationTokenSource(); await cts.CancelAsync(); diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs index 007affb..f428457 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs @@ -31,7 +31,7 @@ public class CompletionTests /// Pauses the first completion after its result is ready, until resume is set. sealed class Pause : IDisposable { - int _once; + int _once, _left; public readonly ManualResetEventSlim Paused = new(), Resume = new(); public Pause() => CompletionCore.AfterReadyForTests = () => @@ -39,12 +39,15 @@ public Pause() => CompletionCore.AfterReadyForTests = () => if (Interlocked.Exchange(ref _once, 1) != 0) return; Paused.Set(); Resume.Wait(TimeSpan.FromSeconds(30)); + Volatile.Write(ref _left, 1); }; public void Dispose() { CompletionCore.AfterReadyForTests = null; Resume.Set(); + // The paused thread may still be waking inside Wait: dispose the events only once it has left. + if (Paused.IsSet) SpinWait.SpinUntil(() => Volatile.Read(ref _left) != 0, TimeSpan.FromSeconds(30)); Paused.Dispose(); Resume.Dispose(); } diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs index 2171224..44b250b 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/Utf8Tests.cs @@ -150,9 +150,9 @@ public void ABytePastAsciiIsNotAHashCharacter() [Fact] public void ChecksTheOriginalRevision() { - const string hash = "$2$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK"; - Assert.Equal(Bcrypt.Verify("U*U*", hash), Bcrypt.Verify("U*U*"u8, Ascii(hash))); - string ours = Bcrypt.Hash("U*U*", hash[..28]); + string ours = Bcrypt.Hash("U*U*", "$2$05$CCCCCCCCCCCCCCCCCCCCC."); + Assert.Equal(59, ours.Length); + Assert.True(Bcrypt.Verify("U*U*", ours)); Assert.True(Bcrypt.Verify("U*U*"u8, Ascii(ours))); Assert.False(Bcrypt.Verify("U*U*\0"u8, Ascii(ours))); } From 11c0e71ac29adc8fbe17bf985d5fc47356f5981f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Paw=C5=82ow?= Date: Tue, 20 Oct 2026 07:16:02 +0200 Subject: [PATCH 3/8] Tests: reuse BcryptQueueTests.Source --- tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs | 3 ++- tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs | 6 +----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs index 8a53433..33f637f 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs @@ -435,6 +435,7 @@ public async Task DefaultOptionsWork() Assert.True(await q.VerifyAsync("password123", Hash4, Ct)); } - static object Source(ValueTask task) => + /// The pooled request behind a ValueTask. + internal static object Source(ValueTask task) => typeof(ValueTask).GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(task)!; } diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs index f428457..fbb35a8 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs @@ -1,6 +1,5 @@ using System; using System.Diagnostics; -using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -66,7 +65,7 @@ public async Task ACallerThatReadsAtOnceDoesNotGetTheCompletionInItsNextCall() Assert.True(first.GetAwaiter().GetResult()); // The next call gets that request back and waits on it with a continuation. var next = q.VerifyAsync("slow", SlowHash, Ct); - Assert.Same(Source(first), Source(next)); + Assert.Same(BcryptQueueTests.Source(first), BcryptQueueTests.Source(next)); var awaiting = AwaitIt(next); pause.Resume.Set(); @@ -173,7 +172,4 @@ public async Task OnCompletedFlowsTheExecutionContext() Assert.Equal("caller", await seen.Task); Assert.True(check.GetAwaiter().GetResult()); } - - static object Source(ValueTask task) => - typeof(ValueTask).GetField("_obj", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(task)!; } From 9d433c7f047e7c162cb51cc8f6797107520b0b9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Paw=C5=82ow?= Date: Tue, 20 Oct 2026 07:19:08 +0200 Subject: [PATCH 4/8] Port the contest server's byte API details: a slot taken only when free, CopyTo on the hash result, its test scenarios --- README.md | 2 +- .../BcryptHashResult.cs | 12 ++ src/CodeFusion.Security.Bcrypt/BcryptQueue.cs | 16 +- .../AllocationTests.cs | 26 +++ .../BcryptQueueUtf8Tests.cs | 155 +++++++++++++++++- 5 files changed, 203 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index dd13bea..a81f3d8 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ switch (await bcrypt.TryVerifyAsync(passwordUtf8, storedHash, aborted)) } BcryptHashResult made = await bcrypt.TryHashAsync(passwordUtf8, 12); -if (made.Status == BcryptStatus.Hashed) made.Hash.CopyTo(row.PasswordHash); +if (made.Status == BcryptStatus.Hashed) made.CopyTo(row.PasswordHash); // CopyTo throws when there is no hash ``` ## Passwords over 72 bytes diff --git a/src/CodeFusion.Security.Bcrypt/BcryptHashResult.cs b/src/CodeFusion.Security.Bcrypt/BcryptHashResult.cs index 98588ce..3f82870 100644 --- a/src/CodeFusion.Security.Bcrypt/BcryptHashResult.cs +++ b/src/CodeFusion.Security.Bcrypt/BcryptHashResult.cs @@ -1,3 +1,5 @@ +using System; + namespace CodeFusion.Security; /// What reports: holds the new hash when @@ -15,4 +17,14 @@ internal BcryptHashResult(BcryptStatus status, BcryptHash hash) /// The new hash; default unless is . public BcryptHash Hash { get; } + + /// Copies the new hash's ASCII bytes to the start of + /// . + /// There is no hash: is Busy or Cancelled. + /// is too short. + public void CopyTo(Span destination) + { + if (Status != BcryptStatus.Hashed) throw new InvalidOperationException($"there is no hash: the call was {Status}"); + Hash.CopyTo(destination); + } } diff --git a/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs b/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs index 4cc8662..f8ba2ad 100644 --- a/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs +++ b/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs @@ -388,13 +388,19 @@ public void Dispose() bool Enqueue(Request r, CancellationToken cancellationToken, out short version) { version = r.Version; // read before a worker can complete and recycle r - if (Interlocked.Increment(ref _queued) > _maxQueued) + // A slot is taken only when there is one, so a refused call never holds one that another call could use. + int queued; + do { - Interlocked.Decrement(ref _queued); - Interlocked.Increment(ref _refused); - Recycle(r); - return false; + queued = Volatile.Read(ref _queued); + if (queued >= _maxQueued) + { + Interlocked.Increment(ref _refused); + Recycle(r); + return false; + } } + while (Interlocked.CompareExchange(ref _queued, queued + 1, queued) != queued); r.Refs = 2; r.Enqueued = Stopwatch.GetTimestamp(); r.Token = cancellationToken; diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs index f5251ed..c319f45 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs @@ -214,4 +214,30 @@ public async Task BusyAndCancelledAllocateNothing() Assert.True(await slow); Assert.Equal(BcryptStatus.Match, await queued); } + + /// + /// The contest server's measure: 200 logins and 25 sign-ups once warm, through the workers and the pool, allocate + /// nothing anywhere in the process. On a pool thread, as a server without a synchronization context runs them. + /// + [Fact] + public async Task LoginsAndSignUpsAllocateNothing() + { + using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); + byte[] pw = "password123"u8.ToArray(), wrong = "password124"u8.ToArray(), destination = new byte[Bcrypt.HashLength]; + var (matched, allocated) = await Task.Run(async () => + { + int matches = 0; + long before = 0; + for (int i = 0; i < 250; i++) + { + if (i == 50) before = GC.GetTotalAllocatedBytes(precise: true); // warmed up + if (await q.TryVerifyAsync(i % 2 == 0 ? pw : wrong, Hash4Ascii) == BcryptStatus.Match && i >= 50) matches++; + if (i % 8 == 0) (await q.TryHashAsync(pw, 4)).CopyTo(destination); + } + return (matches, GC.GetTotalAllocatedBytes(precise: true) - before); + }, TestContext.Current.CancellationToken); + Assert.Equal(100, matched); + Assert.Equal(0, allocated); + Assert.True(Bcrypt.Verify("password123"u8, destination)); + } } diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs index b2122ac..e4d9441 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs @@ -17,8 +17,8 @@ public class BcryptQueueUtf8Tests static CancellationToken Ct => TestContext.Current.CancellationToken; - static BcryptQueue Queue(int threads = 1, int lanes = 5, int? maxQueued = null) => - new(new BcryptQueueOptions { Threads = threads, Lanes = lanes, MaxQueued = maxQueued }); + static BcryptQueue Queue(int threads = 1, int lanes = 5, int? maxQueued = null, int windowMs = 0) => + new(new BcryptQueueOptions { Threads = threads, Lanes = lanes, MaxQueued = maxQueued, BatchWindow = TimeSpan.FromMilliseconds(windowMs) }); static async Task> Occupy(BcryptQueue q) { @@ -316,4 +316,155 @@ public async Task EveryKindOfCallSharesThePoolSoundly() Assert.Equal(160, q.HashesRun); Assert.Equal(0, q.QueueLength); } + + // ---------- the contest server's scenarios (csharp-kestrel-xeonfx PasswordsBytesTests), on this queue ---------- + + static byte[] B(string s) => Encoding.UTF8.GetBytes(s); + + [Fact] + public async Task EachCallerGetsItsOwnAnswerFromABatch() + { + using var q = Queue(windowMs: 0); + bool[] good = [true, false, true, true, false, false, true, false, true]; + var checks = good.Select(g => q.TryVerifyAsync(B(g ? "password123" : "password124"), Hash4Ascii, Ct)).ToArray(); + string[] passwords = ["alpha", "beta", "gamma", "é😀"]; + var hashes = passwords.Select(p => q.TryHashAsync(B(p), 4, Ct)).ToArray(); + + for (int i = 0; i < good.Length; i++) Assert.Equal(good[i] ? BcryptStatus.Match : BcryptStatus.NoMatch, await checks[i]); + for (int i = 0; i < passwords.Length; i++) + { + var made = await hashes[i]; + Assert.Equal(BcryptStatus.Hashed, made.Status); + byte[] text = new byte[Bcrypt.HashLength]; + made.CopyTo(text); + string hash = Encoding.ASCII.GetString(text); + Assert.StartsWith("$2b$04$", hash, StringComparison.Ordinal); + Assert.True(BCrypt.Net.BCrypt.Verify(passwords[i], hash)); + Assert.False(BCrypt.Net.BCrypt.Verify(passwords[i] + "x", hash)); + Assert.Equal(BcryptStatus.Match, await q.TryVerifyAsync(B(passwords[i]), text, Ct)); + } + } + + [Theory] + [InlineData("not a hash")] + [InlineData("")] + [InlineData("$2a$10$ZSfEoPvlcsj2XfvsSeK25em4NZ9Jm7ntGqXuLgQfHEeZPYB8899w")] // 59 characters + [InlineData("$2a$10$ZSfEoPvlcsj2XfvsSeK25em4NZ9Jm7ntGqXuLgQfHEeZPYB8899wqq")] // 61 + [InlineData("$2x$10$ZSfEoPvlcsj2XfvsSeK25em4NZ9Jm7ntGqXuLgQfHEeZPYB8899wq")] + [InlineData("$2a$03$ZSfEoPvlcsj2XfvsSeK25em4NZ9Jm7ntGqXuLgQfHEeZPYB8899wq")] // cost below 4 + [InlineData("$2a$32$ZSfEoPvlcsj2XfvsSeK25em4NZ9Jm7ntGqXuLgQfHEeZPYB8899wq")] + [InlineData("$2a$1a$ZSfEoPvlcsj2XfvsSeK25em4NZ9Jm7ntGqXuLgQfHEeZPYB8899wq")] + [InlineData("$2a$10$ZSfEoPvlcsj2XfvsSeK2!em4NZ9Jm7ntGqXuLgQfHEeZPYB8899wq")] // not in the alphabet + public async Task AMalformedHashIsNoMatchAtOnceWithoutQueueing(string hash) + { + using var q = Queue(); + var check = q.TryVerifyAsync("password123"u8, B(hash), Ct); + Assert.True(check.IsCompletedSuccessfully); + Assert.Equal(BcryptStatus.NoMatch, await check); + Assert.Equal(0, q.HashesRun); + } + + /// Past the queue's limit a call is Busy at once: no exception, nothing queued, and the calls that got in + /// still get their answers. + [Fact] + public async Task AFloodPastTheLimitIsBusyAtOnce() + { + const int limit = 40, extra = 10; + using var q = Queue(maxQueued: limit); + var slow = await Occupy(q); + var all = Enumerable.Range(0, limit + extra).Select(i => q.TryVerifyAsync(i % 2 == 0 ? "password123"u8 : "password124"u8, Hash4Ascii, Ct)).ToArray(); + int busy = 0; + for (int i = 0; i < all.Length; i++) // each awaited exactly once + { + bool atOnce = all[i].IsCompleted; + var r = await all[i]; + if (r == BcryptStatus.Busy) + { + Assert.True(atOnce); + Assert.True(i >= limit, $"call {i} was refused with room left"); + busy++; + } + else Assert.Equal(i % 2 == 0 ? BcryptStatus.Match : BcryptStatus.NoMatch, r); + } + Assert.Equal(extra, busy); + Assert.Equal(extra, q.Refused); + Assert.True(await slow); + Assert.Equal(0, q.QueueLength); + } + + /// Reading a read result again (ValueTask.Result goes straight to GetResult) throws and must not pool the + /// request a second time: two later calls would then share it and could swap answers. + [Fact] + public async Task AStaleReadDoesNotPoolTheRequestTwice() + { + using var q = Queue(); + var check = q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct); + Assert.Equal(BcryptStatus.Match, await check); + Assert.Throws(() => check.Result); + await Assert.ThrowsAsync(async () => await check); + for (int round = 0; round < 20; round++) + { + // two calls sharing a request would leave one waiting for good: fail after a while instead of hanging + var good = q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), Ct); + var bad = q.TryVerifyAsync("password124"u8, Hash4Ascii, Ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), Ct); + Assert.Equal(BcryptStatus.Match, await good); + Assert.Equal(BcryptStatus.NoMatch, await bad); + } + } + + /// The stored hash is compared in full, its last character too (as Go's bcrypt does), and its salt counts. + [Fact] + public async Task AStoredHashDifferingInOneCharacterDoesNotMatch() + { + using var q = Queue(); + byte[] hash = (byte[])Hash4Ascii.Clone(); + Assert.Equal(BcryptStatus.Match, await q.TryVerifyAsync("password123"u8, hash, Ct)); + foreach (byte c in "./AZaz09"u8.ToArray()) + { + if (c == Hash4Ascii[^1]) continue; + hash[^1] = c; + Assert.Equal(BcryptStatus.NoMatch, await q.TryVerifyAsync("password123"u8, hash, Ct)); + } + hash[^1] = Hash4Ascii[^1]; + hash[20] = hash[20] == (byte)'a' ? (byte)'b' : (byte)'a'; // a salt character + Assert.Equal(BcryptStatus.NoMatch, await q.TryVerifyAsync("password123"u8, hash, Ct)); + } + + /// A result with no hash has nothing to copy. + [Fact] + public async Task ABusyOrCancelledHashHasNothingToCopy() + { + using var q = Queue(); + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + var none = await q.TryHashAsync("alpha"u8, 4, cts.Token); + Assert.Equal(BcryptStatus.Cancelled, none.Status); + Assert.Throws(() => none.CopyTo(new byte[60])); + var made = await q.TryHashAsync("alpha"u8, 4, Ct); + Assert.Throws(() => made.CopyTo(new byte[59])); + var text = new byte[60]; + made.CopyTo(text); + Assert.True(Bcrypt.Verify("alpha"u8, text)); + } + + /// + /// The batching window runs from the first call's arrival, not from when a worker takes it: a call that waited out + /// the window behind a long run runs at once instead of waiting a second window for company. + /// + [Fact] + public async Task ACallOlderThanTheWindowRunsWithoutWaitingAgain() + { + var window = TimeSpan.FromMilliseconds(300); + using var q = Queue(windowMs: (int)window.TotalMilliseconds); + var start = Stopwatch.StartNew(); + var slow = Enumerable.Range(0, Bcrypt.MaxLanes).Select(_ => q.HashAsync("pw"u8, 13, Ct)).ToArray(); // well over the window + var late = q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct); + foreach (var s in slow) Assert.Equal(60, (await s).Length); + var run = start.Elapsed; + Assert.True(run > window + TimeSpan.FromMilliseconds(200), $"the run took only {run}, so the late call wasn't older than the window"); + Assert.Equal(BcryptStatus.Match, await late); + var after = start.Elapsed - run; + Assert.True(after < window / 2, $"waited {after} after the run"); + Assert.Equal(2, q.Batches); + } } From e5377459ce3208c8624c3421fcd3211ed849215d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Paw=C5=82ow?= Date: Tue, 20 Oct 2026 07:25:27 +0200 Subject: [PATCH 5/8] Refuse a second await before it touches the first one's state; correct the docs on late continuations, NUL bytes and Dispose --- README.md | 4 ++-- src/CodeFusion.Security.Bcrypt/Bcrypt.cs | 3 ++- src/CodeFusion.Security.Bcrypt/BcryptQueue.cs | 4 ++++ src/CodeFusion.Security.Bcrypt/CompletionCore.cs | 6 +++++- .../BcryptQueueTests.cs | 13 +++++++++++++ 5 files changed, 26 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a81f3d8..4665be7 100644 --- a/README.md +++ b/README.md @@ -140,8 +140,8 @@ hash.CopyTo(row.PasswordHash); - The queue copies both spans before the call returns, so their buffers can be reused at once. - The password's bytes are the key as they are. UTF-8 gives the same hashes as the string overloads, and other bytes - are taken too, as OpenBSD and Go take them. Over 72 bytes is refused, as with strings. The enhanced hashes take - strings only. + are taken too, as Go takes them. A NUL counts, as it does in a string; C implementations stop at the first one. + Over 72 bytes is refused, as with strings. The enhanced hashes take strings only. - `BcryptHash` reads out with `CopyTo`, `TryFormat` (to bytes or chars) or `AsSpan`; `ToString` makes the string. `TryVerifyAsync` and `TryHashAsync` report a full queue or a fired token as a status instead of an exception, so diff --git a/src/CodeFusion.Security.Bcrypt/Bcrypt.cs b/src/CodeFusion.Security.Bcrypt/Bcrypt.cs index dd44806..47bc06a 100644 --- a/src/CodeFusion.Security.Bcrypt/Bcrypt.cs +++ b/src/CodeFusion.Security.Bcrypt/Bcrypt.cs @@ -44,7 +44,8 @@ public static unsafe partial class Bcrypt /// /// A new "$2b$" hash of the password in , written to /// as ASCII. Allocates nothing. The bytes are the key as they are: UTF-8 gives the hash - /// gives the same text, and other bytes are taken too, as OpenBSD and Go take them. + /// gives the same text, and other bytes are taken too, as Go takes them. A NUL + /// counts, as in the string overloads; C implementations stop at the first one, so they won't verify such a hash. /// /// The bytes written: . /// The password is over 72 bytes, or is shorter diff --git a/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs b/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs index f8ba2ad..dcfeb8a 100644 --- a/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs +++ b/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs @@ -272,6 +272,8 @@ public ValueTask VerifyAsync(ReadOnlySpan passwordUtf8, ReadOnlySpan /// throwing, so overload costs no exception: or /// otherwise. /// + /// The queue is disposed, or was disposed while the call waited (in + /// the returned task). public ValueTask TryVerifyAsync(ReadOnlySpan passwordUtf8, ReadOnlySpan hash, CancellationToken cancellationToken = default) { ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); @@ -331,6 +333,8 @@ public ValueTask HashAsync(ReadOnlySpan passwordUtf8, int cost /// , with the hash, otherwise. /// /// The password is over 72 bytes. + /// The queue is disposed, or was disposed while the call waited (in + /// the returned task). public ValueTask TryHashAsync(ReadOnlySpan passwordUtf8, int cost = Bcrypt.DefaultCost, CancellationToken cancellationToken = default) { Bcrypt.CheckCost(cost); diff --git a/src/CodeFusion.Security.Bcrypt/CompletionCore.cs b/src/CodeFusion.Security.Bcrypt/CompletionCore.cs index 6c59d83..7faa463 100644 --- a/src/CodeFusion.Security.Bcrypt/CompletionCore.cs +++ b/src/CodeFusion.Security.Bcrypt/CompletionCore.cs @@ -15,7 +15,8 @@ namespace CodeFusion.Security; /// nothing after marking the result ready. The result itself lives in the request; this keeps only whether it failed. /// /// A continuation registered after completion (the result arrived between the awaiter's look and its registration) -/// runs at once on the registering thread, as a Task's does, instead of being queued to the pool, which allocates. The +/// runs at once on the registering thread, unless the stack is deep, instead of being queued to the pool as the +/// runtime's core and Task do, which allocates. The compiler's state machines touch nothing after registering. The /// flags are honoured as the runtime's core honours them: the ExecutionContext flows, and a synchronization context or /// task scheduler gets the continuation. /// @@ -80,6 +81,9 @@ public void OnCompleted(Action continuation, object? state, short token { ArgumentNullException.ThrowIfNull(continuation); Validate(token); + // A second await is refused before it writes anything: it must not overwrite the first one's state. + Action? current = Volatile.Read(ref _continuation); + if (current is not null && !ReferenceEquals(current, Sentinel)) throw new InvalidOperationException("a pooled ValueTask was awaited twice"); // Everything goes in before the continuation: once it's published, Signal may run it at once. if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) _context = ExecutionContext.Capture(); if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) _scheduler = CurrentScheduler(); diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs index 33f637f..cbf9604 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueTests.cs @@ -258,6 +258,19 @@ public async Task AwaitingTwiceThrows() Assert.False(await next); } + /// A second await of a call still running throws, and the first await still gets its result: the refused + /// registration must not touch the first one's state. + [Fact] + public async Task ASecondAwaitWhileRunningThrowsAndTheFirstStillCompletes() + { + using var q = Queue(); + var check = q.VerifyAsync("slow", SlowHash, Ct); + var first = check.AsTask(); + var ex = Assert.Throws(() => { _ = check.AsTask(); }); + Assert.Contains("awaited twice", ex.Message, StringComparison.Ordinal); + Assert.True(await first.WaitAsync(TimeSpan.FromSeconds(10), Ct)); + } + /// /// A cancelled request stays in the queue until a worker passes it, so its result is read before the request can /// be reused. A second read then must not release it again: it would be reused while still queued. From 280a9b0ac36dad293a6cfe771c7805509eb66e80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Paw=C5=82ow?= Date: Tue, 20 Oct 2026 07:44:11 +0200 Subject: [PATCH 6/8] Time the window test on a fake clock instead of wall-clock bounds The queue reads arrival and window times from an internal TimeProvider (the system clock outside the tests). The test moves the clock past a 30 s window between stamping a call's arrival and linking it, so the worker always finds it too old to wait for. It failed CI on a loaded runner with its 150 ms bound. --- src/CodeFusion.Security.Bcrypt/BcryptQueue.cs | 8 +++-- .../BcryptQueueUtf8Tests.cs | 33 ++++++++++++------- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs b/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs index dcfeb8a..d839de7 100644 --- a/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs +++ b/src/CodeFusion.Security.Bcrypt/BcryptQueue.cs @@ -210,6 +210,10 @@ public BcryptQueue(BcryptQueueOptions? options = null) /// Calls cancelled before a worker took them. public long Cancelled => Interlocked.Read(ref _cancelled); + /// For the tests: the clock that times a request's arrival and its run's window, in + /// ticks. + internal TimeProvider Clock = TimeProvider.System; + /// For the tests: runs between a request's cancellation registration and its linking into the queue. internal Action? BeforeLinkForTests; @@ -406,7 +410,7 @@ bool Enqueue(Request r, CancellationToken cancellationToken, out short version) } while (Interlocked.CompareExchange(ref _queued, queued + 1, queued) != queued); r.Refs = 2; - r.Enqueued = Stopwatch.GetTimestamp(); + r.Enqueued = Clock.GetTimestamp(); r.Token = cancellationToken; // Registered before it's linked, so a callback only ever sees this call's request, never one reused for another // call. A token that fires before the link (even during the registration itself) marks the request, and it's @@ -592,7 +596,7 @@ int Collect(Request?[] batch) if (n == 0) ms = 1000; // wakes now and then to notice Dispose even if another worker took its wake-up else { - long left = deadline - Stopwatch.GetTimestamp(); + long left = deadline - Clock.GetTimestamp(); ms = left > 0 ? (int)((left * 1000 + Stopwatch.Frequency - 1) / Stopwatch.Frequency) : 0; } if (!_ready.Wait(ms)) diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs index e4d9441..c9264c6 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/BcryptQueueUtf8Tests.cs @@ -447,24 +447,35 @@ public async Task ABusyOrCancelledHashHasNothingToCopy() Assert.True(Bcrypt.Verify("alpha"u8, text)); } + /// A clock the test moves by hand, in Stopwatch ticks. + sealed class ManualClock : TimeProvider + { + long _now = Stopwatch.GetTimestamp(); + + public override long GetTimestamp() => Volatile.Read(ref _now); + + public void Advance(TimeSpan by) => Interlocked.Add(ref _now, (long)(by.TotalSeconds * Stopwatch.Frequency)); + } + /// /// The batching window runs from the first call's arrival, not from when a worker takes it: a call that waited out - /// the window behind a long run runs at once instead of waiting a second window for company. + /// the window (behind a long run, say) runs at once instead of waiting a second window for company. The clock moves + /// past the window after the call's arrival is stamped and before it is linked, so the worker always finds it too + /// old to wait for, however loaded the machine. Timed from its taking instead, it would wait the whole 30 seconds. /// [Fact] public async Task ACallOlderThanTheWindowRunsWithoutWaitingAgain() { - var window = TimeSpan.FromMilliseconds(300); + var window = TimeSpan.FromSeconds(30); using var q = Queue(windowMs: (int)window.TotalMilliseconds); - var start = Stopwatch.StartNew(); - var slow = Enumerable.Range(0, Bcrypt.MaxLanes).Select(_ => q.HashAsync("pw"u8, 13, Ct)).ToArray(); // well over the window + var clock = new ManualClock(); + q.Clock = clock; + q.BeforeLinkForTests = () => clock.Advance(window + TimeSpan.FromSeconds(1)); var late = q.TryVerifyAsync("password123"u8, Hash4Ascii, Ct); - foreach (var s in slow) Assert.Equal(60, (await s).Length); - var run = start.Elapsed; - Assert.True(run > window + TimeSpan.FromMilliseconds(200), $"the run took only {run}, so the late call wasn't older than the window"); - Assert.Equal(BcryptStatus.Match, await late); - var after = start.Elapsed - run; - Assert.True(after < window / 2, $"waited {after} after the run"); - Assert.Equal(2, q.Batches); + q.BeforeLinkForTests = null; + + // A third of the window: a cost-4 check on the slowest runner, with room to spare, and far short of a window. + Assert.Equal(BcryptStatus.Match, await late.AsTask().WaitAsync(window / 3, Ct)); + Assert.Equal(1, q.Batches); } } From 3b7e6db45d9be18f001d550eee4d0395858f8534 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Paw=C5=82ow?= Date: Tue, 20 Oct 2026 08:17:33 +0200 Subject: [PATCH 7/8] Correct the account of the completion core: 1.0.1 had no reachable race The runtime core's GetStatus stays Pending until its continuation slot is claimed, and the queue releases a request only once it isn't Pending, so 1.0.1 never reached the window. What the new core gives is a late continuation run inline instead of a pool work item (an allocation), and no window by construction. The paused test is named for that order. --- .../CompletionCore.cs | 17 +++++++++-------- .../CompletionTests.cs | 19 ++++++++++--------- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/src/CodeFusion.Security.Bcrypt/CompletionCore.cs b/src/CodeFusion.Security.Bcrypt/CompletionCore.cs index 7faa463..01ceae8 100644 --- a/src/CodeFusion.Security.Bcrypt/CompletionCore.cs +++ b/src/CodeFusion.Security.Bcrypt/CompletionCore.cs @@ -8,15 +8,16 @@ namespace CodeFusion.Security; /// -/// The completion half of the runtime's ManualResetValueTaskSourceCore, without its race. That core marks a result -/// ready before it claims the continuation slot (.NET 8 to 11). A caller that sees the result in that window reads it -/// and releases the request, which is reset for its next call at once; the completing thread's claim then lands in -/// that next call, whose continuation runs before its result exists. This core claims the slot first and touches -/// nothing after marking the result ready. The result itself lives in the request; this keeps only whether it failed. +/// The completion half of the runtime's ManualResetValueTaskSourceCore, for the queue's pooled requests. A continuation +/// registered after completion (the result arrived between the awaiter's look and its registration) runs at once on +/// the registering thread, unless the stack is deep, instead of being queued to the pool as the runtime's core and +/// Task do: that queueing allocates a work item, which the queue's 0 B per call can't afford. /// -/// A continuation registered after completion (the result arrived between the awaiter's look and its registration) -/// runs at once on the registering thread, unless the stack is deep, instead of being queued to the pool as the -/// runtime's core and Task do, which allocates. The compiler's state machines touch nothing after registering. The +/// It claims the continuation slot before it marks the result ready and touches nothing after, so whoever sees the +/// result may read it and reset the core for its next operation at once. (The runtime's core marks the result first +/// and claims the slot after; it stays safe only because its GetStatus reports Pending until the slot is claimed, and +/// the queue releases a request only once its status isn't Pending.) The result itself lives in the request; this +/// keeps only whether it failed. The compiler's state machines touch nothing after registering. The /// flags are honoured as the runtime's core honours them: the ExecutionContext flows, and a synchronization context or /// task scheduler gets the continuation. /// diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs index fbb35a8..e4174da 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/CompletionTests.cs @@ -4,16 +4,16 @@ using System.Threading.Tasks; using Xunit; -// The tests read results the moment they are ready, synchronously, as the callers that hit the race did. +// The tests read results the moment they are ready, synchronously, as a caller that polls does. #pragma warning disable xUnit1031 namespace CodeFusion.Security.Tests; /// -/// How a queued call completes. The runtime's ManualResetValueTaskSourceCore marks a result ready before it claims -/// the continuation slot; a caller that read the result in between and released the request had the completion land -/// in its next call, whose continuation then ran before its result existed. These tests pause the completing thread -/// right after the result is ready (a static hook, so they run alone) or oversubscribe the cores to widen that window. +/// How a queued call completes through . Its completion claims the continuation slot before +/// it marks the result ready, and touches nothing after: a caller that reads the result that moment and frees the +/// request must not get this completion in its next call. These tests pause the completing thread right after the +/// result is ready (a static hook, so they run alone) or load the cores while callers read and reuse requests at once. /// [Collection(nameof(Measuring))] public class CompletionTests @@ -53,7 +53,7 @@ public void Dispose() } [Fact] - public async Task ACallerThatReadsAtOnceDoesNotGetTheCompletionInItsNextCall() + public async Task CompletionTouchesNothingAfterTheResultIsReady() { using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); using var pause = new Pause(); @@ -69,7 +69,8 @@ public async Task ACallerThatReadsAtOnceDoesNotGetTheCompletionInItsNextCall() var awaiting = AwaitIt(next); pause.Resume.Set(); - // Had the completion claimed the slot only now, it would have run that continuation before next's result. + // Had the completion claimed the slot only now (the runtime core's order, without its Pending guard), it would + // have run that continuation before next's result. Assert.True(await awaiting); } @@ -92,8 +93,8 @@ public async Task AContinuationRegisteredAfterCompletionRunsAtOnceOnItsOwnThread /// /// Many callers each read their result the moment it is ready and queue their next call at once, which the pool /// most often hands the request just freed. With twice as many callers as cores, all spinning, and as many workers, - /// the threads that complete calls are preempted often. The runtime's window is a few instructions, so this can't - /// force it the way the paused test above does; it guards the whole path under load. + /// the threads that complete calls are preempted often. It guards the whole path under load; the paused test above + /// is what pins the completion's order. /// [Fact] public void CallersReadingAtOnceGetTheirOwnResultsWithTheCoresOversubscribed() From 3aee50ffa9e15d76afec664a0014a68c4de962aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Paw=C5=82ow?= Date: Tue, 20 Oct 2026 08:28:05 +0200 Subject: [PATCH 8/8] Measure the logins allocation test over up to six windows and keep the least A single window failed once in CI on .NET 11 with 1,160 B of the process's own allocations. Noise only ever adds, while an allocation per call shows in every window, as the queue's other allocation tests already assume. A failure now lists every window's bytes. --- .../AllocationTests.cs | 36 +++++++++++++------ 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs b/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs index c319f45..46ef934 100644 --- a/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs +++ b/tests/CodeFusion.Security.Bcrypt.Tests/AllocationTests.cs @@ -218,26 +218,42 @@ public async Task BusyAndCancelledAllocateNothing() /// /// The contest server's measure: 200 logins and 25 sign-ups once warm, through the workers and the pool, allocate /// nothing anywhere in the process. On a pool thread, as a server without a synchronization context runs them. + /// + /// Everything is made before the first window. The process may allocate meanwhile for reasons of its own (a pool + /// thread starting, a method tiering up; once 1,160 B on .NET 11 in CI), which only ever adds, while a real + /// allocation per call shows in every window. So it measures up to six windows and keeps the least, and a failure + /// lists them all. (GC allocation tick events sample every 100 KB, too coarse to name a few stray bytes.) + /// /// [Fact] public async Task LoginsAndSignUpsAllocateNothing() { + const int Logins = 200, Windows = 6; using var q = new BcryptQueue(new BcryptQueueOptions { Threads = 1 }); byte[] pw = "password123"u8.ToArray(), wrong = "password124"u8.ToArray(), destination = new byte[Bcrypt.HashLength]; - var (matched, allocated) = await Task.Run(async () => + long[] bytes = new long[Windows]; + int[] matched = new int[Windows]; + int windows = await Task.Run(async () => { - int matches = 0; - long before = 0; - for (int i = 0; i < 250; i++) + for (int w = -1; w < Windows; w++) // -1: the warm-up { - if (i == 50) before = GC.GetTotalAllocatedBytes(precise: true); // warmed up - if (await q.TryVerifyAsync(i % 2 == 0 ? pw : wrong, Hash4Ascii) == BcryptStatus.Match && i >= 50) matches++; - if (i % 8 == 0) (await q.TryHashAsync(pw, 4)).CopyTo(destination); + int matches = 0; + long before = GC.GetTotalAllocatedBytes(precise: true); + for (int i = 0; i < Logins; i++) + { + if (await q.TryVerifyAsync(i % 2 == 0 ? pw : wrong, Hash4Ascii) == BcryptStatus.Match) matches++; + if (i % 8 == 0) (await q.TryHashAsync(pw, 4)).CopyTo(destination); + } + long allocated = GC.GetTotalAllocatedBytes(precise: true) - before; + if (w < 0) continue; + bytes[w] = allocated; + matched[w] = matches; + if (allocated == 0) return w + 1; } - return (matches, GC.GetTotalAllocatedBytes(precise: true) - before); + return Windows; }, TestContext.Current.CancellationToken); - Assert.Equal(100, matched); - Assert.Equal(0, allocated); + Assert.All(matched[..windows], m => Assert.Equal(Logins / 2, m)); + Assert.True(bytes[windows - 1] == 0, $"every window allocated: {string.Join(", ", bytes)} B"); Assert.True(Bcrypt.Verify("password123"u8, destination)); } }