Skip to content

[Caching] Distinguish absent and empty cache key values - #69233

Merged
javiercn merged 2 commits into
mainfrom
javiercn/cache-empty-value-keys
Sep 28, 2026
Merged

javiercn merged 2 commits into
mainfrom
javiercn/cache-empty-value-keys

Conversation

@javiercn

@javiercn javiercn commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Fixes #68943

Overview

Output Caching and Response Caching previously serialized an absent configured query/header value identically to a present empty value, even though application code can distinguish them with ContainsKey. This changes the four affected configured paths and their shared wildcard/multi-value query serialization so cache keys represent presence and value boundaries injectively. The change is limited to the two internal key providers and focused tests; no public API changes.

Design

None (no public contract change).

The existing ASCII group separator (\x1d) remains the name/value delimiter and now also marks each empty value. This was preferred over introducing another reserved character: delimiter validation already prevents user values from containing \x1d, so the representation is unambiguous and composes with the existing record (\x1e) and unit (\x1f) separators.

  • Absent configured value: Name\x1d
  • One empty value: Name\x1d\x1d
  • Empty then non-empty: Name\x1d\x1d\x1fValue

Implementation

// src/Middleware/OutputCaching/src/OutputCacheKeyProvider.cs
// All header, configured-query, and wildcard-query loops use this helper.
// Delimiter-bearing values still disable caching; only empty values gain a marker.
private static bool TryAppendValue(StringBuilder builder, string? value)
{
    if (ContainsDelimiters(value))
    {
        return false;
    }

    if (string.IsNullOrEmpty(value))
    {
        builder.Append(KeyNameValueDelimiter);
    }
    else
    {
        builder.Append(value);
    }

    return true;
}

Response Caching applies the same encoding through AppendValue, preserving its existing behavior of throwing CacheKeyDelimiterException for unsafe values. The affected equivalence classes are:

  • Output Caching: varied headers, configured query keys, wildcard query values, and empty elements in multi-value sequences.
  • Response Caching: varied headers, configured query keys, wildcard query values, and empty elements in multi-value sequences.

Existing non-empty serialization, original value ordering, wildcard query-key discovery/sorting, and delimiter rejection are unchanged.

Outcome

Case Before After
Output Caching configured header: absent vs present-empty Failed: identical keys Passed
Output Caching configured query: absent vs ?QueryA= Failed: identical keys Passed
Response Caching varied header: absent vs present-empty Failed: identical keys Passed
Response Caching configured query: absent vs ?QueryA= Failed: identical keys Passed

Each regression was observed failing for the expected identical-key reason before the production change and passing afterward. Additional focused coverage protects wildcard empty query values and empty elements in multi-value query/header sequences. Full validation passed:

  • Microsoft.AspNetCore.OutputCaching.Tests: 399 passed
  • Microsoft.AspNetCore.ResponseCaching.Tests: 283 passed

Compatibility: absent and non-empty keys remain byte-for-byte unchanged. Present-empty values intentionally move to corrected keys, causing a one-time miss and safe cache repopulation. Existing distributed cache entries are not proactively purged and continue to expire or be evicted normally.

@github-actions github-actions Bot added the area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlewares label Sep 11, 2026
@javiercn javiercn changed the title Distinguish absent and empty cache key values [Caching] Distinguish absent and empty cache key values Sep 11, 2026
@javiercn
javiercn marked this pull request as ready for review September 14, 2026 10:05
Copilot AI lite review requested due to automatic review settings September 14, 2026 10:05

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

Only minor test-coverage nits remain; no blocking issues were identified.

Pull request overview

Updates Output Caching and Response Caching key serialization to distinguish absent and present-empty header/query values.

Changes:

  • Encodes empty values distinctly.
  • Applies encoding across header and configured/wildcard query paths.
  • Adds regression coverage for key collision prevention.
File summaries
File Description
src/Middleware/ResponseCaching/test/ResponseCachingKeyProviderTests.cs Tests header and query collision prevention.
src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs Encodes empty values distinctly.
src/Middleware/OutputCaching/test/OutputCacheKeyProviderTests.cs Tests header and query collision prevention.
src/Middleware/OutputCaching/src/OutputCacheKeyProvider.cs Encodes empty values distinctly.
Review details
  • Files reviewed: 4/4 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@javiercn
javiercn requested a review from cincuranet September 14, 2026 10:22
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Sep 26, 2026
Assert.NotEqual(cacheKeyProvider.CreateStorageKey(absentContext), cacheKeyProvider.CreateStorageKey(emptyContext));
}

[Fact]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

add another test to lock in behavior with multiple empty-value keys? like ?HeaderA=fast&HeaderA= and ?HeaderA=&HeaderA=

[Fact]
public void OutputCachingKeyProvider_CreateStorageKey_EncodesMultipleEmptyHeaderValuesInSequence()
{
    var cacheKeyProvider = TestUtils.CreateTestKeyProvider();
    var context = TestUtils.CreateTestContext();
    context.HttpContext.Request.Headers["HeaderA"] = string.Empty;
    context.HttpContext.Request.Headers.Append("HeaderA", string.Empty);
    context.CacheVaryByRules.HeaderNames = new string[] { "HeaderA" };

    Assert.Equal($"{EmptyBaseKey}{KeyDelimiter}H{KeyDelimiter}HeaderA{KeyNameValueDelimiter}{KeyNameValueDelimiter}{KeySubDelimiter}{KeyNameValueDelimiter}",
        cacheKeyProvider.CreateStorageKey(context));
}

@javiercn
javiercn merged commit 6bdb349 into main Sep 28, 2026
34 checks passed
@javiercn
javiercn deleted the javiercn/cache-empty-value-keys branch September 28, 2026 16:32
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlewares pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Output and Response Caching treat absent and empty query/header values as the same cache key

3 participants