Skip to content

fix: configure auth cookie secure flag by environment#102

Open
ManthanSiroya wants to merge 6 commits into
roshankumar0036singh:mainfrom
ManthanSiroya:fix-auth-cookie-secure-flag
Open

fix: configure auth cookie secure flag by environment#102
ManthanSiroya wants to merge 6 commits into
roshankumar0036singh:mainfrom
ManthanSiroya:fix-auth-cookie-secure-flag

Conversation

@ManthanSiroya

@ManthanSiroya ManthanSiroya commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

Description

This PR fixes the issue where the auth cookie had Secure: false hardcoded, which could expose authentication cookies over unencrypted HTTP connections in production.

Changes Made

  • Configured the auth cookie Secure flag dynamically based on the environment.
  • Enabled Secure: true in production mode.
  • Preserved local development behavior for non-production environments.
  • Updated related handler initialization and tests where required.

Why This Change?

Previously, the auth cookie was always created with Secure: false, allowing cookies to be sent over non-HTTPS connections even in production. This change improves security by ensuring cookies are transmitted securely in production environments.

Testing

  • Ran go test ./...
  • Verified tests pass successfully.
  • Confirmed expected behavior for environment-based cookie security.

Checklist

  • I have read and signed the CLA by commenting I have read the CLA and agree to its terms. on this PR.
  • My changes follow the project's coding style.
  • I have tested my changes.

Fixes #57

Summary by CodeRabbit

Release Notes

  • New Features

    • Added COOKIE_DOMAIN configuration to control the domain used for authentication-related cookies.
    • Cookie behavior now adapts to the runtime environment, ensuring correct security settings (e.g., Secure) for production deployments.
  • Bug Fixes

    • Updated OAuth state cookie handling for login/callback flows to consistently use the configured cookie domain and environment security rules.
  • Tests

    • Added coverage to verify cookies are set with the expected Secure attribute and domain for login and OAuth flows.

@coderabbitai

coderabbitai Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a COOKIE_DOMAIN environment variable, extends AppConfig with a CookieDomain field, and threads isProd and cookieDomain through AuthHandler. All cookie set/clear operations for auth_token and oauth_state across login and OAuth flows now use these configurable values instead of hardcoded empty domain and false secure flag. Environment detection is normalized to case-insensitive, whitespace-tolerant comparison across the codebase.

Changes

Cookie Domain and Secure Flag Propagation

Layer / File(s) Summary
AppConfig CookieDomain field and env example
.env.example, internal/config/config.go
AppConfig gains CookieDomain string; LoadConfig reads COOKIE_DOMAIN from the environment defaulting to ""; .env.example documents the variable with .example.com.
AuthHandler cookie domain and isProd wiring
internal/handler/auth_handler.go
AuthHandler struct gains isProd bool and cookieDomain string; NewAuthHandler constructor expanded to accept these values; Login, GoogleLogin, GoogleCallback, GitHubLogin, and GitHubCallback all switch to h.cookieDomain and h.isProd when setting or clearing auth_token and oauth_state cookies.
Normalized environment detection and routes wiring
cmd/server/main.go, internal/routes/routes.go
SetupRoutes passes a case-insensitive, whitespace-trimmed production boolean and cfg.App.CookieDomain to NewAuthHandler; cmd/server/main.go applies the same normalization pattern for consistency.
Test updates and production security validation
internal/handler/auth_handler_test.go, internal/handler/auth_handler_protected_test.go
All test call sites updated to the expanded NewAuthHandler constructor signature with nil, false, ""; two new tests validate that auth_token and oauth_state cookies are marked Secure and use the expected Domain.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐇 Hop hop, the cookie's now secure,
No more bare HTTP to endure!
Domain config flows from .env to route,
isProd and cookieDomain leave no doubt.
The rabbit stamps each Set-Cookie right,
Keeping session tokens snug and tight! 🍪

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly addresses the main change: configuring auth cookie security flag by environment, which is the core fix addressing issue #57.
Description check ✅ Passed The description covers the security issue, changes made, rationale, testing performed, and includes the checklist. All required sections are present with sufficient detail.
Linked Issues check ✅ Passed The PR successfully implements dynamic Secure flag configuration based on environment [#57], sets cookie Domain appropriately [#57], and adds test coverage validating production cookie security behavior [#57].
Out of Scope Changes check ✅ Passed All changes are scoped to issue #57: adding COOKIE_DOMAIN config variable, updating auth handlers for environment-aware cookie security, hardening production detection logic, and adding security tests. No unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

Hi @roshankumar0036singh , I am recreating this PR because the previous one was automatically closed after the head repository (my fork) was deleted accidentally.

This PR contains the same implementation and changes as the original PR. Re-verified locally before submission.

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

recheck

@roshankumar0036singh

Copy link
Copy Markdown
Owner

@ManthanSiroya isProd source is inconsistent there is a bug risk here
Login cookie now uses h.isProd for Secure, but oauth_state cookies still use local gin.Mode() check
COOKIE_DOMAIN default is empty string verify this is the desired default for non-prod
SameSite not addressed.

The main thing to fix is the inconsistency between h.isProd (new, config-based) and the pre-existing gin.Mode() == gin.ReleaseMode checks in the OAuth handlers pick one source of truth and use it everywhere

@github-actions

github-actions Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA. ✅ Thank you!
Posted by the CLA Assistant Lite bot.

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

Addressed the inconsistency by updating OAuth cookie handling to use the config-based h.isProd check everywhere instead of mixing gin.Mode() == gin.ReleaseMode.

This makes production detection consistent across login and OAuth cookie flows.

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

recheck

github-actions Bot added a commit that referenced this pull request Jun 15, 2026

@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

🤖 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 `@internal/handler/auth_handler_test.go`:
- Line 23: The test file for auth_handler_test.go currently instantiates
NewAuthHandler with isProd=false and empty domain strings at multiple locations,
which fails to validate the production cookie security behavior added in this
PR. Add at least two new test functions: one that tests the login flow with
NewAuthHandler instantiated using isProd=true and a non-empty domain value, and
another that tests the OAuth-state flow with the same production parameters. In
each test, verify that the Set-Cookie response header contains both the Secure
flag and the expected Domain value to ensure the cookie security behavior works
correctly in production mode.

In `@internal/routes/routes.go`:
- Line 65: The production detection on line 65 in the NewAuthHandler call uses a
simple string equality check that is vulnerable to case sensitivity and
whitespace issues. Harden this check by normalizing cfg.App.Env before comparing
it to "production" — convert it to lowercase and trim any whitespace before the
equality comparison. This ensures that environment variables with different
casing or accidental whitespace do not silently disable cookie security in
production deployments.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 61b67b3d-138f-4de0-96bf-14f4ffe154dc

📥 Commits

Reviewing files that changed from the base of the PR and between b73c079 and 93d5a98.

📒 Files selected for processing (6)
  • .env.example
  • internal/config/config.go
  • internal/handler/auth_handler.go
  • internal/handler/auth_handler_protected_test.go
  • internal/handler/auth_handler_test.go
  • internal/routes/routes.go

Comment thread internal/handler/auth_handler_test.go
Comment thread internal/routes/routes.go Outdated
@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

Addressed the production environment detection concern by making the production check more robust against casing/whitespace mismatches.

@sonarqubecloud

Copy link
Copy Markdown

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

🧹 Nitpick comments (2)
internal/handler/auth_handler_test.go (2)

260-334: 💤 Low value

Excellent test coverage for production cookie security!

This test successfully addresses the past review feedback and validates that auth_token cookies are marked Secure with the correct Domain in production mode.

Minor improvements:

  1. Use httptest.NewRequestWithContext instead of httptest.NewRequest (Lines 288, 306): The linter correctly flags that NewRequestWithContext should be preferred for proper context propagation and cancellation support.

  2. Remove redundant nil check (Lines 330-333): The if authCookie != nil guard is unnecessary because require.NotNil(t, authCookie) on Line 328 already fails the test immediately if the cookie is nil.

♻️ Suggested cleanup
 	req = httptest.NewRequest(
 		http.MethodPost,
 		"/api/auth/login",
 		bytes.NewBuffer(loginJSON),
 	)
+	// Or use: req = httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/auth/login", bytes.NewBuffer(loginJSON))
 	req.Header.Set("Content-Type", "application/json")
 	require.NotNil(t, authCookie)
 
-	if authCookie != nil {
-		assert.True(t, authCookie.Secure)
-		assert.Equal(t, "example.com", authCookie.Domain)
-	}
+	assert.True(t, authCookie.Secure)
+	assert.Equal(t, "example.com", authCookie.Domain)
🤖 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 `@internal/handler/auth_handler_test.go` around lines 260 - 334, In the
TestAuthHandler_Login_ProductionCookieSecurity test function, replace both
httptest.NewRequest calls with httptest.NewRequestWithContext to enable proper
context propagation and cancellation support as preferred by the linter.
Additionally, remove the redundant if authCookie != nil block after the
require.NotNil assertion since that assertion already guarantees the cookie is
not nil and will fail the test immediately if it is.

Source: Linters/SAST tools


336-389: 💤 Low value

Excellent test coverage for OAuth state cookie security!

This test successfully validates that oauth_state cookies are marked Secure with the correct Domain in production mode, even when the OAuth flow encounters an error.

Minor improvements (same as the login test):

  1. Use httptest.NewRequestWithContext instead of httptest.NewRequest (Line 364): Prefer NewRequestWithContext for proper context propagation.

  2. Remove redundant nil check (Lines 385-388): The if stateCookie != nil guard is unnecessary because require.NotNil(t, stateCookie) on Line 383 already fails the test if the cookie is nil.

♻️ Suggested cleanup
 	req := httptest.NewRequest(
 		http.MethodGet,
 		"/api/auth/google/login?client_id=test-client",
 		nil,
 	)
+	// Or use: req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/auth/google/login?client_id=test-client", nil)
 	require.NotNil(t, stateCookie)
 
-	if stateCookie != nil {
-		assert.True(t, stateCookie.Secure)
-		assert.Equal(t, "example.com", stateCookie.Domain)
-	}
+	assert.True(t, stateCookie.Secure)
+	assert.Equal(t, "example.com", stateCookie.Domain)
🤖 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 `@internal/handler/auth_handler_test.go` around lines 336 - 389, In the
TestAuthHandler_GoogleLogin_ProductionCookieSecurity test function, replace the
httptest.NewRequest call with httptest.NewRequestWithContext to ensure proper
context propagation. Additionally, remove the redundant if stateCookie != nil
check that guards the assertions at the end of the function, since the
require.NotNil call immediately before it already validates that stateCookie is
not nil and would fail the test if it were, making the additional guard
unnecessary.

Source: Linters/SAST tools

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

Nitpick comments:
In `@internal/handler/auth_handler_test.go`:
- Around line 260-334: In the TestAuthHandler_Login_ProductionCookieSecurity
test function, replace both httptest.NewRequest calls with
httptest.NewRequestWithContext to enable proper context propagation and
cancellation support as preferred by the linter. Additionally, remove the
redundant if authCookie != nil block after the require.NotNil assertion since
that assertion already guarantees the cookie is not nil and will fail the test
immediately if it is.
- Around line 336-389: In the
TestAuthHandler_GoogleLogin_ProductionCookieSecurity test function, replace the
httptest.NewRequest call with httptest.NewRequestWithContext to ensure proper
context propagation. Additionally, remove the redundant if stateCookie != nil
check that guards the assertions at the end of the function, since the
require.NotNil call immediately before it already validates that stateCookie is
not nil and would fail the test if it were, making the additional guard
unnecessary.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d31f7d17-9434-491d-b088-cc530f01de75

📥 Commits

Reviewing files that changed from the base of the PR and between 93d5a98 and d868d4a.

📒 Files selected for processing (3)
  • cmd/server/main.go
  • internal/handler/auth_handler_test.go
  • internal/routes/routes.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/routes/routes.go

@roshankumar0036singh

roshankumar0036singh commented Jun 15, 2026

Copy link
Copy Markdown
Owner

@ManthanSiroya Fantastic work adding explicit test vectors (TestAuthHandler_Login_ProductionCookieSecurity) to cover our production cookie domain parameters! This directly ensures our sub-domain context isolation won't suffer from silent regressions in future rollouts.

I have left two action items on the file:

OAuth Test Realignment: We need to mock seed our test DB data rather than asserting against an HTTP 500 context block inside our Google Login security test case. This prevents pipeline test flakes down the road.

Dry Optimization: Centralizing the environment string cleanup behavior straight into our core config structural pattern for better internal reuse

This sanitization routine (strings.EqualFold(strings.TrimSpace(...))) is duplicated across our application entry layers.(reson for 2.5% duplication detection)

@ManthanSiroya

Copy link
Copy Markdown
Contributor Author

Hi @roshankumar0036singh,

I wanted to share an update regarding this PR. I’ve spent 5–6+ hours working through the cookie security fixes, production handling updates, review feedback, testing, and follow-up changes.

I’m currently unable to continue further on the remaining review items for this PR. I’ve already pushed the latest completed fixes and tried to address the requested feedback as much as possible.

If the completed work is acceptable, I’d really appreciate consideration for merge and recognition of the effort already contributed. For the remaining requested improvements/comments, I kindly request creating separate follow-up issues so they can be worked on independently later.

Thanks for the reviews and guidance throughout the process.

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.

CRITICAL: Auth cookie set with Secure: false in production

2 participants