Skip to content

Reduce allocations in DataProtection string Protect/Unprotect - #70187

Merged
DeagleGross merged 4 commits into
mainfrom
perf/dataprotection-string-overloads
Nov 6, 2026
Merged

DeagleGross merged 4 commits into
mainfrom
perf/dataprotection-string-overloads

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

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-8 byte[] of the plaintext, then the protected byte[], then the Base64Url string (and the reverse for Unprotect). On .NET, when the protector implements ISpanDataProtector (which CreateProtector always returns on .NET), these overloads now:

  • encode the string to UTF-8 into an ArrayPool<byte> buffer (cleared on return),
  • protect/unprotect into the shared 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),
  • Base64Url-encode directly from the written span (WebEncoders.Base64UrlEncode(ReadOnlySpan<byte>)).

Unprotect(string) still uses WebEncoders.Base64UrlDecode so 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_protect allocations were in DataProtectionCommonExtensions itself.

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.

Alg Scenario main PR main alloc PR alloc
CBC Protect(string) 100 B 10.03 us 10.00 us 2,040 B 1,304 B (-36%)
CBC Protect(string) 2 KB 14.99 us 14.43 us 12,281 B 6,120 B (-50%)
CBC Unprotect(string) 100 B 7.58 us 7.68 us 1,144 B 1,016 B (-11%)
CBC Unprotect(string) 2 KB 10.66 us 10.57 us 8,368 B 6,432 B (-23%)
GCM Protect(string) 100 B 8.03 us 7.97 us 1,152 B 832 B (-28%)
GCM Protect(string) 2 KB 9.57 us 9.36 us 9,584 B 5,648 B (-41%)
GCM Unprotect(string) 100 B 5.83 us 5.79 us 832 B 704 B (-15%)
GCM Unprotect(string) 2 KB 7.38 us 7.08 us 8,056 B 6,120 B (-24%)

Time is neutral (within noise); the win is allocation.

Custom (byte[]-only) encryptors

All built-in encryptors (managed CBC/GCM, CNG CBC/GCM) implement ISpanAuthenticatedEncryptor and take the zero-copy path. For a custom IAuthenticatedEncryptor that only implements the byte[] API, KeyRingBasedSpanDataProtector falls back to copying the ciphertext span to an array, so Unprotect(string) pays one extra ciphertext-sized copy; Protect(string) is neutral. 728fd91 removes the avoidable AAD copy in that fallback (GetAadForKey already returns an array). The same change and measurements are on #70191.

Security reasoning

  • Payload format unchanged / byte-identical: the span path calls the same key ring protector with the same plaintext bytes and AAD. New known-answer theory StringProtect_SpanProtector_ProducesSamePayloadAsByteArrayPath (CBC and GCM, 0 B–70 KB) uses a deterministic RNG to assert the string output equals Base64UrlEncode(Protect(byte[])) from the existing path, and round-trips both ways.
  • Plaintext hygiene improves: the UTF-8 plaintext buffer (protect) and the decrypted plaintext buffer (unprotect) are pooled and returned with clearArray: true; the shared writer now also clears every array it outgrows. Previously these plaintext byte[]s were left to the GC without being zeroed. No key material passes through these buffers.
  • Nothing pooled is caller-reachable: the writer is an internal ref struct scoped to a single call; only the resulting string (the same value as before) escapes.
  • Exceptions unchanged: invalid UTF-8 still throws from SecureUtf8Encoding (same type/message); invalid base64 still throws from Base64UrlDecode; protector exceptions propagate unchanged (covered by new tests). No public API change, no PublicAPI.*.txt changes, no unsafe code.
  • No crypto primitives, comparisons or validation logic are touched.

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)

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]>
Copilot AI balanced review requested due to automatic review settings October 31, 2026 15:47
@github-actions github-actions Bot added the area-dataprotection Includes: DataProtection label Oct 31, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 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]>
@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 5, 2026 — with Copilot SWE Agent
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]>
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 5, 2026
davidfowl added a commit that referenced this pull request Nov 5, 2026
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]>
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 5, 2026 — with Copilot SWE Agent

Copy link
Copy Markdown
Member Author

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)

@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 5, 2026
@DeagleGross
DeagleGross merged commit 15a0197 into main Nov 6, 2026
27 checks passed
@DeagleGross
DeagleGross deleted the perf/dataprotection-string-overloads branch November 6, 2026 11:26
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

✅ 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

  • Conceptual article: Not required — Internal allocation reduction; no public API changes, and payload format and exceptions are unchanged.
  • Migration guidance: Not required — No action needed for users upgrading.
  • Breaking change: Not required — No compatibility impact; output is byte-identical and accepted input is unchanged.

DeagleGross added a commit that referenced this pull request Nov 6, 2026
* 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]>
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 8, 2026

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 2f1cdfb9 Deployed Nov 6, 2026 by DeagleGross via conclusion #204
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-dataprotection Includes: DataProtection

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants