Repository navigation
Reduce allocations in DataProtection string Protect/Unprotect - #70187
Conversation
Use ISpanDataProtector from the string Protect/Unprotect extension methods so the UTF-8 plaintext and the protected payload are written into pooled buffers that are cleared on return, instead of allocating intermediate byte arrays. Co-authored-by: Copilot <[email protected]>
There was a problem hiding this comment.
🟢 Approval recommended
There are no active review issues for the pooled-buffer changes to string protection and unprotection.
No open issues 🎉
What changed in this PR
Reduces allocations in DataProtection’s string Protect and Unprotect overloads by using pooled buffers when the protector supports ISpanDataProtector. Existing paths remain for non-span protectors and non-.NET targets.
Changes:
- Adds span-based string processing while retaining the existing Base64 decoding behavior.
- Introduces a pooled buffer writer that clears returned buffers and supports growth.
- Adds tests for span dispatch, buffer growth, error handling, and payload equivalence with the byte-array path.
| File | Description |
|---|---|
| src/DataProtection/shared/src/ClearingPooledBufferWriter.cs | Adds the internal growable pooled buffer writer. |
| src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/KeyRingBasedDataProtectorTests.cs | Adds CBC and GCM payload-equivalence and round-trip tests. |
| src/DataProtection/Abstractions/test/DataProtectionCommonExtensionsTests.cs | Adds span-path, growth, and failure-case tests. |
| src/DataProtection/Abstractions/src/DataProtectionCommonExtensions.cs | Routes supported string operations through pooled span-based helpers. |
Review effort: Balanced
GetAadForKey already returns an array, so pass it directly to the byte[]-based encryptor instead of copying it. Co-authored-by: Copilot <[email protected]>
|
/review |
Replace the custom ClearingPooledBufferWriter with the shared RefPooledArrayBufferWriter seeded with a 256-byte stack buffer, removing the size-estimate constants. The shared writer now clears an outgrown rented array before returning it to the pool, and the Unprotect path clears the stack buffer since it may hold plaintext. Co-authored-by: Copilot <[email protected]>
Replace the custom ClearingPooledBufferWriter with the shared
RefPooledArrayBufferWriter, starting from a 256-byte stack buffer that
grows from the pool as needed. This removes the size-estimate constant.
The { expiration || plaintext } buffer is a 'using' writer; writers passed
by ref are disposed in finally (CS1657). Stack buffers holding plaintext
are cleared, and RefPooledArrayBufferWriter now clears arrays it returns
to the pool when it grows (same change as #70187).
Add tests on both sides of the 256-byte initial buffer.
Co-authored-by: Copilot <[email protected]>
|
Retriggered CI with an empty commit (2f1cdfb, tree identical to c16e8bc) after one failure on c16e8bc that looks unrelated to this change.
🤖 Posted by ASP.NET Core Perf 2 (AI Agent) |
|
✅ No documentation PR was created. Confidence that documentation is needed: 5% No docs needed: this is an internal performance optimization with no user-visible behavior change. Confident, not an insufficient-evidence result. Documentation surfaces considered
|
* Avoid intermediate copies in TimeLimitedDataProtector
Use ISpanDataProtector so the { expiration || plaintext } buffer and the
unprotected payload use pooled buffers that are cleared on return.
Co-authored-by: Copilot <[email protected]>
* Avoid copying the AAD in the span Unprotect fallback path
GetAadForKey already returns an array, so pass it directly to the
byte[]-based encryptor instead of copying it.
Co-authored-by: Copilot <[email protected]>
* Use shared RefPooledArrayBufferWriter in TimeLimitedDataProtector
Replace the custom ClearingPooledBufferWriter with the shared
RefPooledArrayBufferWriter, starting from a 256-byte stack buffer that
grows from the pool as needed. This removes the size-estimate constant.
The { expiration || plaintext } buffer is a 'using' writer; writers passed
by ref are disposed in finally (CS1657). Stack buffers holding plaintext
are cleared, and RefPooledArrayBufferWriter now clears arrays it returns
to the pool when it grows (same change as #70187).
Add tests on both sides of the 256-byte initial buffer.
Co-authored-by: Copilot <[email protected]>
---------
Co-authored-by: davidfowl <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Korolev Dmitry <[email protected]>
Reduce allocations in DataProtection string Protect/Unprotect
Description
DataProtectionCommonExtensions.Protect(string)/Unprotect(string)(used by TempData, antiforgery-style consumers, and many apps) allocated a UTF-8byte[]of the plaintext, then the protectedbyte[], then the Base64Url string (and the reverse forUnprotect). On .NET, when the protector implementsISpanDataProtector(whichCreateProtectoralways returns on .NET), these overloads now:ArrayPool<byte>buffer (cleared on return),RefPooledArrayBufferWriter<byte>seeded with a 256-byte stack buffer (rented arrays are cleared when outgrown and on dispose; the stack buffer is cleared after Unprotect),WebEncoders.Base64UrlEncode(ReadOnlySpan<byte>)).Unprotect(string)still usesWebEncoders.Base64UrlDecodeso the accepted input format (base64 and base64url) is unchanged. Non-span protectors and non-.NET TFMs keep the existing code path.Found by profiling (EventPipe CPU + allocation sampling) realistic DataProtection scenarios: 59% of
str_protectallocations were inDataProtectionCommonExtensionsitself.Benchmarks
Linux x64, 2 cores, BenchmarkDotNet in-process, 3 interleaved rounds vs main (median). Cookie-style purpose chain, cached protector, default managed CBC+HMAC and AES-256-GCM.
Time is neutral (within noise); the win is allocation.
Custom (byte[]-only) encryptors
All built-in encryptors (managed CBC/GCM, CNG CBC/GCM) implement
ISpanAuthenticatedEncryptorand take the zero-copy path. For a customIAuthenticatedEncryptorthat only implements the byte[] API,KeyRingBasedSpanDataProtectorfalls back to copying the ciphertext span to an array, soUnprotect(string)pays one extra ciphertext-sized copy;Protect(string)is neutral. 728fd91 removes the avoidable AAD copy in that fallback (GetAadForKeyalready returns an array). The same change and measurements are on #70191.Security reasoning
StringProtect_SpanProtector_ProducesSamePayloadAsByteArrayPath(CBC and GCM, 0 B–70 KB) uses a deterministic RNG to assert the string output equalsBase64UrlEncode(Protect(byte[]))from the existing path, and round-trips both ways.clearArray: true; the shared writer now also clears every array it outgrows. Previously these plaintextbyte[]s were left to the GC without being zeroed. No key material passes through these buffers.ref structscoped to a single call; only the resulting string (the same value as before) escapes.SecureUtf8Encoding(same type/message); invalid base64 still throws fromBase64UrlDecode; protector exceptions propagate unchanged (covered by new tests). No public API change, no PublicAPI.*.txt changes, no unsafe code.Overlap
No overlap with #70146 (managed encryptor internals); this change is in the Abstractions extension methods only and composes with it.
Tests
Microsoft.AspNetCore.DataProtection.Abstractions.Tests: 36 passed (9 new span-path tests: growth, empty, invalid UTF-8, invalid base64, exception propagation).Microsoft.AspNetCore.DataProtection.Tests: 345 passed (new known-answer theory).🤖 Posted by ASP.NET Core Perf 2 (AI Agent)