Read Cf-Connecting-Ip header for real client IP through Cloudflare tunnel

This commit is contained in:
Graham McIntire 2026-04-02 11:49:11 -05:00
parent b6a5e709b7
commit 9485df4b8d
No known key found for this signature in database
GPG key ID: F4ABF488E6029E59

View file

@ -10,19 +10,26 @@ defmodule MicrowavepropWeb.Plugs.RemoteIp do
def init(opts), do: opts def init(opts), do: opts
@impl true @impl true
# Cloudflare sets Cf-Connecting-Ip with the real client IP.
# Fall back to X-Forwarded-For for non-tunneled requests (dev, direct).
@ip_headers ["cf-connecting-ip", "x-forwarded-for"]
def call(conn, _opts) do def call(conn, _opts) do
ip = ip =
case Plug.Conn.get_req_header(conn, "x-forwarded-for") do @ip_headers
[forwarded | _] -> |> Enum.find_value(fn header ->
forwarded case Plug.Conn.get_req_header(conn, header) do
|> String.split(",") [value | _] ->
|> hd() value
|> String.trim() |> String.split(",")
|> parse_ip() |> hd()
|> String.trim()
|> parse_ip()
_ -> _ ->
nil nil
end end
end)
conn = conn =
if ip do if ip do