Skip to content

feat: add opt-in RefitSettings.ValidateHeaders#2225

Merged
glennawatson merged 11 commits into
mainfrom
feat/optional-header-validation
Jul 15, 2026
Merged

feat: add opt-in RefitSettings.ValidateHeaders#2225
glennawatson merged 11 commits into
mainfrom
feat/optional-header-validation

Conversation

@glennawatson

@glennawatson glennawatson commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

What kind of change does this PR introduce?

Feature - a new opt-in RefitSettings.ValidateHeaders setting. Additive and off by default, so existing behaviour is unchanged.

What is the new behavior?

  • Adds RefitSettings.ValidateHeaders (default false).
  • When set to true, Refit applies header values with HttpHeaders.Add, which validates each value against its header parser. A malformed value (for example an invalid If-Modified-Since, a bad User-Agent, or a date header that does not parse) now throws FormatException while the request is being built, instead of being sent as-is.
  • Both request builders honour the flag identically: the source-generated path (GeneratedRequestRunner) and the reflection path (Refit.Reflection).
  • CR/LF stripping still applies to header names and values in both modes.

What is the current behavior?

Header values are always added verbatim with HttpHeaders.TryAddWithoutValidation, so malformed values are sent to the server untouched and are never surfaced as an exception.

Closes #1853

What might this PR break?

  • Nothing by default. The setting is opt-in and defaults to false, so the current verbatim behaviour is preserved unless a caller explicitly sets ValidateHeaders = true.
  • Callers who turn the flag on will start seeing FormatException at request-build time for header values the framework parser rejects. This is the intended effect of enabling validation.

Checklist

  • I have read the Contribute guide
  • Tests have been added or updated (for bug fixes / features)
  • Docs have been added or updated (for bug fixes / features)
  • Changes target the main branch
  • PR title follows Conventional Commits

Additional information

  • Threaded the flag through both request builders in parity (generated + reflection); preserved CR/LF stripping, the request/content header split, and the same-name removal guard in both modes.
  • Tests added for both builders: validation enabled throws FormatException; validation disabled sends the value verbatim. The pair used to prove validation throws is If-Modified-Since with the value not a date - verified empirically: HttpHeaders.Add("If-Modified-Since", "not a date") throws FormatException, while TryAddWithoutValidation stores it verbatim.
  • Updated PublicAPI files, README ("Validating header values"), and docs/breaking-changes.md.
  • Builds clean (Refit, Refit.Reflection, generators, test projects) with analyzers satisfied; new/affected tests pass on net8.0.
  • Investigation concluded that switching to validated Add by default would reject many currently-valid header values with no security benefit (CR/LF is already stripped), so this is strictly opt-in.

…alues

- add `RefitSettings.ValidateHeaders` (default false); when true, header
  values are applied with `HttpHeaders.Add` so malformed values throw
  `FormatException` at request-build time instead of being sent verbatim
- thread the flag through both request builders in parity: the generated
  `GeneratedRequestRunner.SetHeader`/`AddHeaderCollection` and the
  reflection `RequestBuilderImplementation.SetHeader`
- keep CR/LF stripping in both modes and preserve the request/content
  header split and same-name removal guard
- emit `refitSettings.ValidateHeaders` into generated header application
- promote pending PublicAPI to shipped and record the new setting
- document the opt-in in the README and breaking-changes notes

Closes #1853
@codecov

codecov Bot commented Jul 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (1e35cc9) to head (4077c61).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #2225   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          182       183    +1     
  Lines         9541      9553   +12     
  Branches      1795      1796    +1     
=========================================
+ Hits          9541      9553   +12     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@glennawatson
glennawatson marked this pull request as ready for review July 14, 2026 14:43
…ders branches

- Extract the validated/verbatim header-apply logic and the request/content
  InvalidOperationException fallback into a single internal HttpHeaderApplier
  in Refit, called by both GeneratedRequestRunner and the reflection
  RequestBuilderImplementation via ProjectReference + InternalsVisibleTo,
  removing the copy-pasted duplication.
- Add TUnit tests covering the validated success path, the content-header
  fallback, and the no-content drop branches for both the generated runner
  and the reflection builder.
…validation

# Conflicts:
#	docs/breaking-changes.md
…validation

# Conflicts:
#	docs/breaking-changes.md
#	src/InterfaceStubGenerator.Shared/Emitter.Inline.cs
…validation

# Conflicts:
#	docs/breaking-changes.md
#	src/tests/Refit.GeneratorTests/_snapshots/InterfaceStubGeneratorTests.FindInterfacesSmokeTest#IGitHubApi.g.verified.cs
#	src/tests/Refit.GeneratorTests/_snapshots/InterfaceStubGeneratorTests.FindInterfacesSmokeTest#INestedGitHubApi.g.verified.cs
…validation

# Conflicts:
#	docs/breaking-changes.md
…validation

# Conflicts:
#	docs/breaking-changes.md
#	src/Refit.Reflection/RequestBuilderImplementation.RequestBuilding.cs
…validation

# Conflicts:
#	docs/breaking-changes.md
…validation

# Conflicts:
#	docs/breaking-changes.md
@sonarqubecloud

Copy link
Copy Markdown

@glennawatson
glennawatson merged commit 7c33871 into main Jul 15, 2026
12 checks passed
@glennawatson
glennawatson deleted the feat/optional-header-validation branch July 15, 2026 10:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Investigate changing TryAddWithoutValidation to Add

2 participants