Skip to content

[Fix] refresh 쿠키 SameSite를 환경변수로 오버라이드 가능하게 함 - #36

Merged
LeeJeongHeon02 merged 4 commits into
devfrom
fix/31-refresh-cookie-samesite
Jul 14, 2026
Merged

[Fix] refresh 쿠키 SameSite를 환경변수로 오버라이드 가능하게 함#36
LeeJeongHeon02 merged 4 commits into
devfrom
fix/31-refresh-cookie-samesite

Conversation

@LeeJeongHeon02

@LeeJeongHeon02 LeeJeongHeon02 commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

🐛 버그 설명

로컬 프론트(http://localhost:5173)가 배포된 서버(issue #31 대응으로 app_frontend_url을 로컬로 임시 스왑한 인스턴스)를 호출해 소셜 로그인 테스트를 하면, 로그인 후 success로 리다이렉트는 정상 되는데 POST /api/v1/auth/token/refresh를 호출하면 항상 401이 뜬다.
Swagger UI(서버가 직접 서빙)에서 같은 흐름을 테스트하면 문제없이 된다.

원인

RefreshTokenService가 refresh 쿠키를 SameSite=Lax로 발급한다. SameSite=Lax 쿠키는 로그인 리다이렉트 같은 top-level navigation에는 붙지만, fetch/axios 같은 cross-site subresource 요청에는 브라우저가 아예 첨부하지 않는다.

  • 카카오 로그인 → success 리다이렉트: top-level navigation이라 쿠키가 정상 저장됨
  • 로컬 프론트가 배포 서버로 refresh를 fetch/axios로 호출: cross-site 요청이라 쿠키가 안 붙음 → refreshToken == nullAuthTokenController가 즉시 401
  • Swagger UI는 서버와 같은 origin(same-site)이라 이 문제가 드러나지 않음

예상 동작

로컬 프론트에서도 배포된 서버를 대상으로 refresh API까지 막힘없이 테스트할 수 있어야 한다.

📝 변경 사항

코드

  • RefreshTokenService: 쿠키의 SameSite 값을 하드코딩된 "Lax"에서 app.auth.refresh-cookie.same-site 프로퍼티(기본값 Lax)로 변경
  • RefreshTokenService: Lax/Strict/None 외의 값이 들어오면 기동 시점에 IllegalStateException으로 즉시 실패 — 오타가 조용히 401 재발로 이어지는 걸 막는다
  • application-prod.yml: REFRESH_COOKIE_SAME_SITE 환경변수로 오버라이드 가능하게 배선. 기본값을 두면 지금 운영 동작과 완전히 동일하다
  • RefreshTokenServiceTest: None으로 생성했을 때 실제로 SameSite=None, Secure=true가 나오는지, 잘못된 값이 기동을 막는지 검증하는 테스트 추가 (기존 Lax assertion도 그대로 통과)

인프라 (배포 파이프라인까지 전체 배선)

  • infra/variables.tf: refresh_cookie_same_site 변수 추가 (기본값 Lax — tfvars 안 건드려도 apply 가능)
  • infra/modules/ssm_params: /vision/prod/refresh-cookie-same-site SSM 파라미터 추가 (비밀 아님, String 타입)
  • .github/workflows/cd.yml: 배포 시 이 SSM 파라미터를 조회해 REFRESH_COOKIE_SAME_SITE 환경변수로 컨테이너에 전달 (기존 15개 파라미터와 동일한 패턴)

실제로 로컬 테스트를 풀려면 (머지 후)

  1. infra/terraform.tfvarsrefresh_cookie_same_site = "None" 추가
  2. terraform plan/apply로 SSM 파라미터 생성/변경 확인
  3. 다음 CD 배포에서 컨테이너가 새 값을 읽어감
  4. 로컬 프론트 테스트가 끝나면 issue #31의 app_frontend_url 원복과 함께 이 값도 Lax로 되돌려야 함 (docs/before-prod-deploy-revert-issue-31.md 체크리스트에 추가 권장)

Closes #31

Test plan

  • ./gradlew compileJava compileTestJava
  • ./gradlew test --tests RefreshTokenServiceTest (12개 전부 통과 — Lax/None/잘못된 값 케이스 포함)
  • terraform validate (backend 없이 init, 문법/참조 검증 통과)
  • terraform fmt -check (변경 파일만 대상, 포맷 이상 없음)
  • CD 배포 스크립트 부분을 추출해 bash -n 문법 검사 + mock aws/docker/curl로 dry-run, docker runREFRESH_COOKIE_SAME_SITE가 정상 전달되는지 확인

Summary by CodeRabbit

  • 개선 사항
    • 리프레시 토큰 쿠키의 SameSite 값을 설정으로 조정할 수 있습니다(기본값: Lax).
    • 허용 값(Lax/Strict/None) 외 입력 시 시작 시점에 오류가 발생하도록 검증을 강화했습니다.
  • 테스트
    • 쿠키에 설정된 SameSite가 반영되는지와 잘못된 값 입력 시 예외 발생을 검증하는 테스트를 보완/추가했습니다.
  • 배포/인프라
    • 운영 배포 시 REFRESH_COOKIE_SAME_SITE를 컨테이너에 전달하고, SSM 파라미터에도 저장되도록 확장했습니다.

로컬 프론트(localhost)가 배포된 서버를 호출해 테스트할 때, refresh_token
쿠키가 SameSite=Lax라 cross-site fetch/axios 요청에는 브라우저가 쿠키를
붙이지 않아 refresh API가 항상 401이었다 (로그인 리다이렉트는 top-level
navigation이라 문제없이 되는 것과 대조적). Swagger UI는 서버와 같은
origin이라 문제가 드러나지 않았다.

app.auth.refresh-cookie.same-site 프로퍼티(REFRESH_COOKIE_SAME_SITE
환경변수, 기본값 Lax)를 추가해, 로컬 프론트 테스트 기간에만 배포 시
None으로 오버라이드할 수 있게 한다. 기본값을 그대로 두면 기존 동작과
동일하다.
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 239842d1-4b2f-483d-97e2-88d84a36a1f4

📥 Commits

Reviewing files that changed from the base of the PR and between cb41448 and 26225dc.

📒 Files selected for processing (1)
  • infra/variables.tf

📝 Walkthrough

Walkthrough

Refresh 쿠키의 SameSite 값을 Terraform과 SSM을 거쳐 배포 환경에서 주입하고, RefreshTokenService가 허용값을 검증한 뒤 쿠키에 적용하도록 변경했다. 관련 운영 설정과 테스트가 갱신되었다.

Changes

Refresh 쿠키 SameSite 설정

Layer / File(s) Summary
SameSite 설정 주입 및 운영 구성
infra/variables.tf, infra/modules/ssm_params/*, infra/main.tf, .github/workflows/cd.yml, src/main/resources/application-prod.yml
Terraform이 Lax, Strict, None 값을 검증해 SSM에 저장하고, CD 배포 및 운영 설정이 REFRESH_COOKIE_SAME_SITE를 컨테이너에 전달하도록 구성되었다.
쿠키 적용 및 테스트 구성
src/main/java/com/shinhan/klljs/domain/auth/service/RefreshTokenService.java, src/test/java/com/shinhan/klljs/domain/auth/service/RefreshTokenServiceTest.java
서비스가 허용된 SameSite 값만 수용하고 주입된 값을 refresh 쿠키에 적용하며, 유효값과 잘못된 값에 대한 테스트가 추가되었다.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: itisyijy

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목이 refresh 쿠키 SameSite를 환경변수로 오버라이드 가능하게 한다는 핵심 변경을 간결하게 잘 요약합니다.
Linked Issues check ✅ Passed SameSite를 설정 가능하게 바꿔 로컬 프론트의 cross-site refresh 요청이 가능해지므로, #31의 정상 호출 목표와 부합합니다.
Out of Scope Changes check ✅ Passed Terraform, CD, 서비스, 테스트 변경이 모두 SameSite 설정 주입과 검증을 위한 범위 안에 있습니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/31-refresh-cookie-samesite

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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
`@src/main/java/com/shinhan/klljs/domain/auth/service/RefreshTokenService.java`:
- Line 50: RefreshTokenService의 cookieSameSite 설정이 허용된 값만 사용하도록 생성 시점에 검증하세요. 값이
Lax, Strict, None 중 하나인지 확인하고, 오타·빈 값 등 잘못된 설정이면 즉시 명확한 예외를 발생시키며, 검증된 값만
ResponseCookie.sameSite(...)에 전달되도록 수정하세요.

In
`@src/test/java/com/shinhan/klljs/domain/auth/service/RefreshTokenServiceTest.java`:
- Line 54: Update RefreshTokenServiceTest to construct RefreshTokenService with
the "None" SameSite setting and assert that buildCookie() produces a cookie
whose SameSite value is "None". Keep the assertion focused on the externally
observable cookie behavior and ensure it exercises the constructor configuration
path.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 7e058a4d-b529-48dd-8d2c-757823be97db

📥 Commits

Reviewing files that changed from the base of the PR and between ce2c976 and d01f5d6.

📒 Files selected for processing (3)
  • src/main/java/com/shinhan/klljs/domain/auth/service/RefreshTokenService.java
  • src/main/resources/application-prod.yml
  • src/test/java/com/shinhan/klljs/domain/auth/service/RefreshTokenServiceTest.java

- Terraform: refresh_cookie_same_site 변수(기본값 Lax) 추가, SSM 파라미터
  /vision/prod/refresh-cookie-same-site로 저장
- cd.yml: 배포 시 이 SSM 파라미터를 조회해 REFRESH_COOKIE_SAME_SITE 환경변수로
  컨테이너에 전달 (기존 SSM 파라미터들과 동일한 패턴)
- RefreshTokenService: Lax/Strict/None 외의 값이 들어오면 기동 시점에
  IllegalStateException으로 즉시 실패시킨다 - 오타가 조용히 401 재발로
  이어지는 걸 막는다
- RefreshTokenServiceTest: None으로 생성했을 때 실제로 SameSite=None,
  Secure=true가 나오는지, 잘못된 값이 기동을 막는지 검증하는 테스트 추가

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@infra/variables.tf`:
- Around line 114-123: variable "refresh_cookie_same_site"에 validation 블록을 추가해
값이 "Lax", "Strict", "None" 중 하나인지 Terraform 단계에서 검증하세요. 기존 default와 설명은 유지하고,
애플리케이션의 기동 시 검증도 제거하지 마세요.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5f9d09c2-fbb2-44c1-a4ae-010e0a37a51e

📥 Commits

Reviewing files that changed from the base of the PR and between d01f5d6 and c57d9c5.

📒 Files selected for processing (7)
  • .github/workflows/cd.yml
  • infra/main.tf
  • infra/modules/ssm_params/main.tf
  • infra/modules/ssm_params/variables.tf
  • infra/variables.tf
  • src/main/java/com/shinhan/klljs/domain/auth/service/RefreshTokenService.java
  • src/test/java/com/shinhan/klljs/domain/auth/service/RefreshTokenServiceTest.java

Comment thread infra/variables.tf
CodeRabbit 리뷰 반영. 애플리케이션 기동 시 검증(RefreshTokenService)은
그대로 두고, terraform plan/apply 단계에서도 Lax/Strict/None 외의 값을
미리 걸러내 오타를 더 빨리 잡는다.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@infra/variables.tf`:
- Line 126: Update the validation error_message for refresh_cookie_same_site so
it accurately describes failure during Terraform plan/apply validation and the
resulting deployment behavior, removing the contradictory claim that apply can
succeed despite a typo. Keep the allowed-value guidance for Lax, Strict, and
None.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: ef974941-c434-4faf-bb0d-6ee0279032a4

📥 Commits

Reviewing files that changed from the base of the PR and between c57d9c5 and cb41448.

📒 Files selected for processing (1)
  • infra/variables.tf

Comment thread infra/variables.tf Outdated
이 validation 블록이 있으면 오타는 plan/apply 단계에서 바로 막힌다 -
"apply는 성공해도"라는 이전 문구는 검증이 없던 상태를 설명한 것이라
지금 코드와 모순됐다.
@LeeJeongHeon02
LeeJeongHeon02 merged commit 9fc4967 into dev Jul 14, 2026
2 checks passed
@LeeJeongHeon02
LeeJeongHeon02 deleted the fix/31-refresh-cookie-samesite branch July 14, 2026 13:59
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.

[Fix] 프론트 개발자가 local에서 서버 호출할 수 있도록 수정

1 participant