Skip to content

test(cors,csrf): cover remaining middleware branches#4462

Merged
ReneWerner87 merged 4 commits into
mainfrom
claude/cors-csrf-test-coverage-1cn4sy
Jun 26, 2026
Merged

test(cors,csrf): cover remaining middleware branches#4462
ReneWerner87 merged 4 commits into
mainfrom
claude/cors-csrf-test-coverage-1cn4sy

Conversation

@gaby

@gaby gaby commented Jun 25, 2026

Copy link
Copy Markdown
Member

Add targeted tests to push CORS and CSRF middleware coverage to their
practical maximum (CORS 96.2% -> 98.5%, CSRF 94.3% -> 99.6%).

CORS:

  • setSimpleHeaders nil-config guard
  • setSimpleHeaders wildcard origin with AllowCredentials (warning branch)
  • setPreflightHeaders nil-config guard

CSRF:

  • validateExtractorSecurity nil-config guard
  • raw origin surfaced in panic when DisableValueRedaction is set
    (regular and wildcard trusted-origin branches)
  • non-ErrNotFound extractor error forwarded to the error handler
  • storage fetch error after a successful double-submit comparison
  • DeleteToken: missing cookie and storage delete failure
  • DeleteToken with the session loaded by the session middleware
  • storage manager: memory unexpected-type assertion and storage
    success paths
  • session manager: store load and save error branches for
    getRaw/setRaw/delRaw

The only lines left uncovered are unreachable defensive branches in
subdomain.match, guarded by an earlier length check.

Co-Authored-By: Claude Opus 4.8 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_01MW3kyDqPzUUQ9iuRqWP94Y

claude added 3 commits June 25, 2026 23:26
Add targeted tests to push CORS and CSRF middleware coverage to their
practical maximum (CORS 96.2% -> 98.5%, CSRF 94.3% -> 99.6%).

CORS:
- setSimpleHeaders nil-config guard
- setSimpleHeaders wildcard origin with AllowCredentials (warning branch)
- setPreflightHeaders nil-config guard

CSRF:
- validateExtractorSecurity nil-config guard
- raw origin surfaced in panic when DisableValueRedaction is set
  (regular and wildcard trusted-origin branches)
- non-ErrNotFound extractor error forwarded to the error handler
- storage fetch error after a successful double-submit comparison
- DeleteToken: missing cookie and storage delete failure
- DeleteToken with the session loaded by the session middleware
- storage manager: memory unexpected-type assertion and storage
  success paths
- session manager: store load and save error branches for
  getRaw/setRaw/delRaw

The only lines left uncovered are unreachable defensive branches in
subdomain.match, guarded by an earlier length check.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MW3kyDqPzUUQ9iuRqWP94Y
Add dedicated security_test.go files covering attack/defense cases that
were not yet asserted directly.

CSRF (middleware/csrf/security_test.go):
- constant-time token/string comparison logical correctness
- Sec-Fetch-Site normalization: case-insensitive and whitespace-trimmed
  acceptance, with unknown/embedded-space values still rejected
- double-submit mismatch (valid header token vs different valid cookie
  token) rejected with ErrTokenInvalid
- forged token consistent across header/cookie but absent from storage
  is rejected and the stale cookie is expired
- cookie security attributes (HttpOnly, Secure, SameSite, Path) are
  reflected on the Set-Cookie response
- HTTPS request with an http:// Origin for the same host is rejected
  (scheme is part of the origin)
- trusting an origin under one scheme does not trust the other scheme

CORS (middleware/cors/security_test.go):
- AllowCredentials with a wildcard-subdomain pattern reflects a matching
  origin verbatim (never "*") with credentials, and denies non-matching,
  apex, and scheme-downgraded origins
- credentialed-origin reflection also applies to simple (non-preflight)
  requests
- a disallowed origin is never reflected back even with multiple
  configured origins

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MW3kyDqPzUUQ9iuRqWP94Y
Move the coverage and security tests out of the standalone
coverage_test.go / security_test.go files and into the existing test
files, matching each test to the source file it exercises:

- CORS: all tests (cors.go helpers and security scenarios) -> cors_test.go
- CSRF: validateExtractorSecurity nil guard -> config_test.go;
  constant-time comparison helpers -> helpers_test.go;
  remaining coverage and security tests (extractor, storage/session
  managers, DeleteToken, cookie attributes, Sec-Fetch-Site, double
  submit, etc.) -> csrf_test.go

No test logic changed; only relocation plus the required imports.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MW3kyDqPzUUQ9iuRqWP94Y
@gaby gaby requested a review from a team as a code owner June 25, 2026 23:58
@coderabbitai

coderabbitai Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d3583fad-b6c9-465a-b2c2-c8a2fe6b1865

📥 Commits

Reviewing files that changed from the base of the PR and between 6556530 and fc58569.

📒 Files selected for processing (1)
  • middleware/csrf/csrf_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/csrf/csrf_test.go

Walkthrough

Adds CORS tests for nil-config helper behavior and credentialed origin handling. Adds CSRF tests for nil-config validation, constant-time comparison helpers, storage and session error paths, and security checks for fetch-site, tokens, cookies, and origin matching.

Changes

Middleware test coverage

Layer / File(s) Summary
Nil-config and wildcard helper checks
middleware/cors/cors_test.go
setSimpleHeaders and setPreflightHeaders are exercised with nil config inputs, and setSimpleHeaders is exercised with wildcard origin handling under credentials.
Credentialed origin rules
middleware/cors/cors_test.go
Credentialed CORS requests are tested for subdomain wildcard reflection, simple-request reflection, and suppression of disallowed origin reflection.
Nil-config and constant-time checks
middleware/csrf/config_test.go, middleware/csrf/helpers_test.go
validateExtractorSecurity(nil) is covered for panic safety, and the comparison helpers are covered with constant-time equality tests.
Storage and session error paths
middleware/csrf/csrf_test.go
A flaky session storage helper is added and used to cover CSRF storage, delete-token, raw storage, and session manager error paths.
CSRF security flows
middleware/csrf/csrf_test.go
CSRF security tests cover fetch-site normalization, double-submit mismatch rejection, forged-token handling, cookie attributes, scheme downgrade rejection, and trusted-origin scheme isolation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

  • gofiber/fiber#4438: Related CORS wildcard subdomain matching changes are exercised by the new credentialed-origin tests.
  • gofiber/fiber#4449: Related CSRF scheme and trusted-origin matching changes are exercised by the new scheme-isolation tests.
  • gofiber/fiber#4439: Related validateExtractorSecurity changes are extended by the new nil-config extractor test.

Suggested labels

codex

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

A bunny tapped the test-suite drum,
For CORS and CSRF, here I come! 🐇
No wildcards snuck through the gate,
No forged token could tempt fate,
And every hop felt safe and snug.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding tests to cover remaining CORS and CSRF middleware branches.
Description check ✅ Passed The description clearly explains the purpose, key test areas, coverage gains, and remaining uncovered branches, so it is mostly complete.
Docstring Coverage ✅ Passed Docstring coverage is 85.29% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/cors-csrf-test-coverage-1cn4sy

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@ReneWerner87 ReneWerner87 added this to v3 Jun 25, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Jun 25, 2026
@codecov

codecov Bot commented Jun 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.02%. Comparing base (066809b) to head (fc58569).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4462      +/-   ##
==========================================
+ Coverage   91.73%   92.02%   +0.28%     
==========================================
  Files         138      138              
  Lines       13486    13486              
==========================================
+ Hits        12371    12410      +39     
+ Misses        705      682      -23     
+ Partials      410      394      -16     
Flag Coverage Δ
unittests 92.02% <ø> (+0.28%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
middleware/csrf/csrf_test.go (1)

2804-2854: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the session-backed token was actually deleted.

Line 2853 only checks the status code. If the in-context delRaw branch regresses to a no-op, this test still passes. Reusing the same session/token for a second unsafe request, or asserting the response expires the CSRF cookie, would validate the behavior instead of just the code path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@middleware/csrf/csrf_test.go` around lines 2804 - 2854, The CSRF delete-token
test only verifies the handler returns OK, so it can miss a regression where
DeleteToken is a no-op in the session-backed path. Update
Test_CSRF_DeleteToken_WithSessionMiddleware to assert the token was actually
removed by reusing the same session/token for a second unsafe request or by
checking the CSRF cookie is expired/cleared after calling
HandlerFromContext(c).DeleteToken(c), so the test validates the deletion
behavior rather than just the status code.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@middleware/cors/cors_test.go`:
- Around line 1726-1729: The test
`Test_CORS_setSimpleHeaders_WildcardWithCredentials` is changing package-global
logger state and restoring it to `os.Stderr`, which can clobber another test’s
redirected output. Update the setup/cleanup around `log.SetOutput` to use the
repo’s log-capture helper or save and restore the exact previous writer instead
of hardcoding `os.Stderr`. Keep the fix localized to this test so later
assertions don’t inherit the wrong logger destination.

In `@middleware/csrf/csrf_test.go`:
- Around line 3133-3162: The CSRF cookie attribute test in
Test_CSRF_Security_CookieAttributes should also assert the __Host- prefix
host-only requirement. Update the test to verify the cookie returned by
setCSRFCookie has an empty Domain field, alongside the existing HttpOnly,
Secure, SameSite, Path, and value checks, so regressions from copying
Config.CookieDomain into the response cookie are caught.

---

Nitpick comments:
In `@middleware/csrf/csrf_test.go`:
- Around line 2804-2854: The CSRF delete-token test only verifies the handler
returns OK, so it can miss a regression where DeleteToken is a no-op in the
session-backed path. Update Test_CSRF_DeleteToken_WithSessionMiddleware to
assert the token was actually removed by reusing the same session/token for a
second unsafe request or by checking the CSRF cookie is expired/cleared after
calling HandlerFromContext(c).DeleteToken(c), so the test validates the deletion
behavior rather than just the status code.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e5c63b30-3ab6-44d4-a8ad-4a0613e0b8e9

📥 Commits

Reviewing files that changed from the base of the PR and between 066809b and 6556530.

📒 Files selected for processing (4)
  • middleware/cors/cors_test.go
  • middleware/csrf/config_test.go
  • middleware/csrf/csrf_test.go
  • middleware/csrf/helpers_test.go

Comment thread middleware/cors/cors_test.go
Comment thread middleware/csrf/csrf_test.go
…-only

- Reorder the Sec-Fetch-Site table struct fields (error first) to satisfy
  the govet fieldalignment linter that was failing CI.
- Assert the CSRF cookie has an empty Domain in the cookie-attributes
  test so a regression that scopes the __Host- cookie to a domain is
  caught (addresses PR review feedback).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MW3kyDqPzUUQ9iuRqWP94Y
@ReneWerner87 ReneWerner87 merged commit 464387b into main Jun 26, 2026
20 checks passed
@github-project-automation github-project-automation Bot moved this to Done in v3 Jun 26, 2026
@ReneWerner87 ReneWerner87 deleted the claude/cors-csrf-test-coverage-1cn4sy branch June 26, 2026 06:19
@ReneWerner87 ReneWerner87 modified the milestones: v3, v3.4.0 Jul 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants