Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Use CF-Connecting-IP when present for remote IP address

Uku Taht5efa15f38191
diff --git a/lib/plausible_web/remote_ip.ex b/lib/plausible_web/remote_ip.ex
index 05fc77789c..e8ad3792b2 100644
--- a/lib/plausible_web/remote_ip.ex
+++ b/lib/plausible_web/remote_ip.ex
@@ -1,13 +1,19 @@
defmodule PlausibleWeb.RemoteIp do
def get(conn) do
+ cf_connecting_ip = List.first(Plug.Conn.get_req_header(conn, "cf-connecting-ip"))
forwarded_for = List.first(Plug.Conn.get_req_header(conn, "x-forwarded-for"))
- if forwarded_for do
- String.split(forwarded_for, ",")
- |> Enum.map(&String.trim/1)
- |> List.first()
- else
- to_string(:inet_parse.ntoa(conn.remote_ip))
+ cond do
+ cf_connecting_ip ->
+ cf_connecting_ip
+
+ forwarded_for ->
+ String.split(forwarded_for, ",")
+ |> Enum.map(&String.trim/1)
+ |> List.first()
+
+ true ->
+ to_string(:inet_parse.ntoa(conn.remote_ip))
end
end
end
diff --git a/test/plausible_web/controllers/api/external_controller_test.exs b/test/plausible_web/controllers/api/external_controller_test.exs
index 96c8dfaecf..014067cd95 100644
--- a/test/plausible_web/controllers/api/external_controller_test.exs
+++ b/test/plausible_web/controllers/api/external_controller_test.exs
@@ -492,6 +492,24 @@ defmodule PlausibleWeb.Api.ExternalControllerTest do
assert pageview.country_code == "US"
end
+ test "uses cloudflare's special header for client IP address if present", %{conn: conn} do
+ params = %{
+ name: "pageview",
+ domain: "external-controller-test-cloudflare.com",
+ url: "http://gigride.live/"
+ }
+
+ conn
+ |> put_req_header("content-type", "text/plain")
+ |> put_req_header("x-forwarded-for", "0.0.0.0")
+ |> put_req_header("cf-connecting-ip", "1.1.1.1")
+ |> post("/api/event", Jason.encode!(params))
+
+ pageview = get_event("external-controller-test-cloudflare.com")
+
+ assert pageview.country_code == "US"
+ end
+
test "URL is decoded", %{conn: conn} do
params = %{
name: "pageview",