보안 리뷰에서 고친 세 가지: IP 신뢰, 환경 변수, 쿠키 사이트
PostButter
로그인 단계 끝의 보안 리뷰와 배포 단계에서 바뀐 세 가지. X-Forwarded-For는 오른쪽에서 세고, APP_ENV는 허용 목록 밖이거나 비어 있으면 시작을 거부하고, Railway 기본 도메인 대신 커스텀 도메인 하나 아래로 web과 api를 묶었다.
Butter의 로그인 핵심(3단계)이 끝난 뒤 보안 리뷰를 받았고, 전체 리뷰(7단계 뒤)에서 한 번 더 고쳤으며, 배포 단계에서 도메인 결정을 하나 내렸다. 바뀐 것은 세 가지다. 클라이언트 IP를 어디서 읽는지, 환경 변수 APP_ENV를 어떻게 판단하는지, web과 api가 쿠키 기준으로 같은 사이트인지. 세 수정의 공통 원칙은 fail-closed(모르겠으면 거부하는 쪽으로 닫는 것)다.
X-Forwarded-For: 왼쪽을 믿으면 안 되는 이유
요청 횟수 제한(/auth/refresh는 IP당 1분 60회, 토큰당 1분 10회)의 키와 로그인 실패 이벤트의 ip_hash(HMAC)가 클라이언트 IP에 의존한다. Spring의 forward-headers-strategy=framework는 X-Forwarded-For의 맨 왼쪽 값을 쓰는데, 그 값은 클라이언트가 마음대로 넣는다. 그래서 none으로 끄고, TRUSTED_PROXY_HOPS만큼 오른쪽에서 센 값을 직접 읽는 ClientIpResolver를 두었다.
Source: butter @ c6cdf7a · api/src/main/resources/application.yml
# Never trust X-Forwarded-For/Forwarded here: Spring would take the leftmost (client-controlled) entry.
# auth's ClientIpResolver reads X-Forwarded-For itself, from the right, per TRUSTED_PROXY_HOPS.
forward-headers-strategy: none
Source: butter @ c6cdf7a · api/src/main/kotlin/com/butter/auth/internal/ClientIpResolver.kt
/**
* The client IP for rate-limit keys and `ip_hash`. The only place that reads it: `server.forward-headers-strategy` is
* `none`, because Spring's handling takes the leftmost (client-controlled) X-Forwarded-For entry.
*
* TRUSTED_PROXY_HOPS = how many proxies in front of the app append to X-Forwarded-For.
* - 0: the socket peer (`remoteAddr`); X-Forwarded-For is ignored.
* - N ≥ 1: the N-th entry from the right (the address the outermost trusted proxy saw). Fewer entries, or an entry
* that is not an IP literal → `remoteAddr`. `Forwarded` is never read.
*/
@Component
class ClientIpResolver(@Value("\${app.client-ip.trusted-proxy-hops:0}") private val trustedProxyHops: Int) {
init {
require(trustedProxyHops >= 0) { "TRUSTED_PROXY_HOPS must be 0 or more" }
}
fun resolve(request: HttpServletRequest): String {
if (trustedProxyHops == 0) return request.remoteAddr
val entries = request.getHeaders(FORWARDED_FOR).toList().flatMap { it.split(',') }
if (entries.size < trustedProxyHops) return request.remoteAddr
return normalize(entries[entries.size - trustedProxyHops]) ?: request.remoteAddr
}
// ...
}
X-Forwarded-For는 경로상의 프록시가 자기가 본 발신 주소를 끝에 덧붙이는 헤더라서, 맨 왼쪽은 클라이언트가 직접 넣은 값일 수 있고 믿을 수 있는 것은 신뢰하는 프록시가 덧붙인 자리, 즉 오른쪽에서 프록시 수만큼 센 자리뿐이다.
기본값 0은 헤더를 무시하고 소켓 주소를 쓰고(프록시 뒤에서는 제한이 빡빡해지지만 우회는 불가능하다), Forwarded(RFC 7239) 헤더는 공격면이 둘이 되지 않게 읽지 않는다.
ClientIpResolverTest가 홉 수별 동작, 위조·깨진 값·IPv6를 테스트로 고정한다.
APP_ENV: 기본값의 위험
APP_ENV=production이면 서명 키·암호화 키·IP 해시 비밀이 필수이고 DEV 로그인이 꺼진다. local·test면 없는 값을 메모리에서 생성한다(토큰은 재시작 때 죽는다). 처음에는 APP_ENV의 기본값이 local이었다. 여기에 "production이 아니면 로컬"이라는 판단이 붙으면, prod 같은 오타나 변수 누락만으로 운영에서 임시 키가 생성되고 DEV 로그인이 켜진다(fail-open, 모르면 열어 주는 쪽으로 떨어지는 것).
Source: butter @ c6cdf7a · api/src/main/kotlin/com/butter/auth/internal/AuthSecrets.kt
/**
* Startup rules (fail fast; messages name the env var, never its value):
* - APP_ENV is required and must be `local`, `test` or `production` (trimmed, case-insensitive); missing or anything
* else refuses to start, so a typo or a forgotten variable can never fall back to development behaviour.
* - `production`: DEV login off; JWT_SIGNING_KEYS, JWT_ACTIVE_KID, IP_HASH_SECRET (≥ 32 bytes), REFRESH_TOKEN_ENC_KEY
* set; WEB_ORIGIN an https:// origin; the refresh cookie Secure.
* - `local`/`test`: missing ones are generated in memory with one WARN line (tokens die on restart).
* // ...
*/
object AuthSecretsLoader {
// ...
private val APP_ENVS = setOf("local", "test", "production")
fun load(properties: AuthProperties, rawAppEnv: String): AuthSecrets {
val appEnv = rawAppEnv.trim().lowercase()
if (appEnv.isEmpty()) fail("APP_ENV is required (one of ${APP_ENVS.joinToString()})")
if (appEnv !in APP_ENVS) fail("APP_ENV must be one of ${APP_ENVS.joinToString()}")
val production = appEnv == "production"
if (production && properties.devLoginEnabled) fail("DEV_LOGIN_ENABLED=true is not allowed when APP_ENV=production")
// ...
if (production) {
val missing = buildList {
if (properties.signingKeys.isBlank()) add("JWT_SIGNING_KEYS")
if (properties.activeKid.isBlank()) add("JWT_ACTIVE_KID")
if (properties.ipHashSecret.isBlank()) add("IP_HASH_SECRET")
if (properties.refreshTokenEncKey.isBlank()) add("REFRESH_TOKEN_ENC_KEY")
}
if (missing.isNotEmpty()) fail("APP_ENV=production requires ${missing.joinToString()}")
if (!properties.webOrigin.startsWith("https://")) fail("APP_ENV=production requires WEB_ORIGIN to be an https:// origin")
if (!properties.cookie.secure) fail("APP_ENV=production requires AUTH_COOKIE_SECURE=true")
// ...
}
// ...
}
}
3단계 구현 초안은 결정 기록 0015의 표현으로 "production이 아니면 로컬"로 판단했는데, 커밋 전 보안 리뷰에서 허용 목록(local·test·production)으로 바뀌어 커밋됐다(db634ee 본문: "APP_ENV 엄격화"). 그래서 fail-open 코드는 저장소 이력에 없다. 그 뒤 전체 리뷰(ae38954)에서 기본값을 없앴다. 이제 변수가 비어 있어도 시작을 거부한다.
실패 메시지가 변수 이름만 말하는 것도 규칙이다. "JWT_SIGNING_KEYS가 필요하다"는 로그에 남아도 되지만, 값이 조금이라도 섞이면 안 된다. AuthStartupTest는 APP_ENV is required, production refuses to start without keys and secrets and names only the variables 등 11개로 시작 규칙을 고정한다.
SameSite 쿠키와 같은 사이트
리프레시 토큰 쿠키는 HttpOnly; Secure; SameSite=Strict; Path=/auth다(결정 기록 0013). Railway 기본 도메인 up.railway.app은 공개 접미사 목록(Public Suffix List)에 올라 있어서, 브라우저가 butter-web.up.railway.app과 butter-api.up.railway.app을 다른 사이트로 취급하고 쿠키가 리프레시 요청에 실리지 않는다(로그인은 되는데 새로고침하면 로그아웃된다).
SameSite=None으로 풀거나 Caddy 프록시로 같은 출처를 만드는 대신, 커스텀 도메인 하나 아래 루트(butter.today)와 api.butter.today로 배포해 등록 가능 도메인(eTLD+1)을 같게 만들었다(결정 기록 0021, 2026-10-20 연결).
쿠키는 로그인 콜백과 리프레시 토큰에도 쓰인다. state를 서버 DB에 두면 흐름의 출처는 검증되지만 로그인 CSRF는 막지 못한다. 브라우저 바인딩 쿠키로 같은 브라우저인지 확인한다. 리프레시 토큰은 쓸 때마다 교체하고 재사용을 탈취로 본다(RFC 9700).
배포 뒤 확인한 것
디버그 엔드포인트 없이 요청 횟수 제한으로 TRUSTED_PROXY_HOPS를 검증한다(docs/deploy.md 7절). 65개 요청을 병렬로 보내 IP당 제한이 걸리는지 확인했다. Railway에서는 홉 수가 2였다(2026-10-20, 커밋 8219503). Railway가 프록시 구성을 바꾸면 달라질 수 있으니, 이 절차는 배포 환경이 바뀔 때마다 다시 돌린다.
참고 자료
- Butter 결정 기록 0010 "기기별 세션 모델"(감수한 것: X-Forwarded-For), 0013 "웹과 네이티브 토큰 보관 방식의 차이와 CSRF", 0015 "로그인 제공자 구조와 이메일 자동 연결 금지"(APP_ENV), 0021 "배포 도메인과 쿠키 같은 사이트 문제",
docs/deploy.md7절, 커밋8219503"배포 검증: Railway TRUSTED_PROXY_HOPS=2" (저장소 내부 문서) - 커밋
db634ee"3단계: 로그인 핵심"(본문: "보안 리뷰 반영: X-Forwarded-For 위조 방지, APP_ENV 엄격화, 만료 bearer 무시 등"),ae38954"검증 패스: 전체 리뷰 반영"(본문: "APP_ENV 필수(기본값 없음, local·test·production만)") - Spring Boot 문서, Running Behind a Front-end Proxy Server (
server.forward-headers-strategy의 세 값): https://docs.spring.io/spring-boot/how-to/webserver.html#howto.webserver.use-behind-a-proxy-server (opens in a new tab) - Spring Framework 문서,
ForwardedHeaderFilter(framework전략이 켜는 필터; 맨 왼쪽 항목을 쓴다): https://docs.spring.io/spring-framework/reference/web/webmvc/filters.html#filters-forwarded-headers (opens in a new tab) - MDN,
X-Forwarded-For(보안 주의: 신뢰하는 프록시가 덧붙인 값만, 오른쪽에서 센다): https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For (opens in a new tab) - Public Suffix List (
up.railway.app항목이 "Railway Corporation" 절에 있다): https://publicsuffix.org/list/public_suffix_list.dat (opens in a new tab) - MDN,
Set-CookieSameSite와 "site"의 정의: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie#samesitesamesite-value (opens in a new tab) - Railway 문서, Public Networking — Specs and Limits (
X-Real-IP헤더): https://docs.railway.com/networking/public-networking/specs-and-limits (opens in a new tab) - RFC 9700, Best Current Practice for OAuth 2.0 Security: https://www.rfc-editor.org/rfc/rfc9700 (opens in a new tab)
StackSpring BootKotlinRailwayCaddyHTTP cookies
Tagsdeep-divesecuritydeployment