"""리버스 프록시 뒤에서 클라이언트 공인 IP 추출 (Meta 전환 추적 · 트래픽 통계 공용).""" import ipaddress from fastapi import Request def is_public_ip(value: str) -> bool: """공인 IP 인지 검사합니다. 사설/루프백 대역(Docker 내부 172.x, 로컬 127.0.0.1 등)은 손님 IP 가 아니라 프록시·컨테이너 주소이므로 거릅니다. """ try: ip = ipaddress.ip_address(value) except ValueError: return False return not ( ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast or ip.is_unspecified ) def extract_client_ip(request: Request) -> str | None: """리버스 프록시 환경을 고려하여 클라이언트 공인 IP를 추출합니다. 후보를 순서대로 검사하여 처음 발견된 공인 IP를 반환합니다. 1. X-Real-IP: nginx가 $remote_addr로 덮어쓰므로 위조 불가 (최우선) 2. X-Forwarded-For: 클라이언트가 보낸 값 뒤에 nginx가 덧붙이는 구조라 맨 앞 항목이 위조될 수 있으므로, 항목을 순회하며 공인 IP를 찾음 3. 소켓 peer 주소: 프록시가 없는 환경 대비 공인 IP를 하나도 찾지 못하면 None을 반환합니다. """ candidates: list[str] = [] real_ip = request.headers.get("x-real-ip") if real_ip: candidates.append(real_ip.strip()) forwarded_for = request.headers.get("x-forwarded-for") if forwarded_for: candidates.extend(part.strip() for part in forwarded_for.split(",")) if request.client: candidates.append(request.client.host) for candidate in candidates: if is_public_ip(candidate): return candidate return None