Skip to content

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

Prioritize X-Plausible-IP header over everything else (#3689)

Cenk Kücük44fca0c95dfe
diff --git a/lib/plausible_web/remote_ip.ex b/lib/plausible_web/remote_ip.ex
index c0a90293cb..dd13aec7c3 100644
--- a/lib/plausible_web/remote_ip.ex
+++ b/lib/plausible_web/remote_ip.ex
@@ -1,11 +1,15 @@
defmodule PlausibleWeb.RemoteIp do
def get(conn) do
+ x_plausible_ip = List.first(Plug.Conn.get_req_header(conn, "x-plausible-ip"))
cf_connecting_ip = List.first(Plug.Conn.get_req_header(conn, "cf-connecting-ip"))
x_forwarded_for = List.first(Plug.Conn.get_req_header(conn, "x-forwarded-for"))
b_forwarded_for = List.first(Plug.Conn.get_req_header(conn, "b-forwarded-for"))
forwarded = List.first(Plug.Conn.get_req_header(conn, "forwarded"))
cond do
+ x_plausible_ip ->
+ clean_ip(x_plausible_ip)
+
cf_connecting_ip ->
clean_ip(cf_connecting_ip)
diff --git a/test/plausible_web/controllers/api/external_controller_test.exs b/test/plausible_web/controllers/api/external_controller_test.exs
index fdeb646121..ad5a61140a 100644
--- a/test/plausible_web/controllers/api/external_controller_test.exs
+++ b/test/plausible_web/controllers/api/external_controller_test.exs
@@ -963,6 +963,29 @@ defmodule PlausibleWeb.Api.ExternalControllerTest do
assert pageview.country_code == "US"
end
+ test "prioritizes x-plausible-ip header over everything else", %{
+ conn: conn,
+ site: site
+ } do
+ params = %{
+ name: "pageview",
+ domain: site.domain,
+ url: "http://example.com/"
+ }
+
+ conn
+ |> put_req_header("cf-connecting-ip", "0.0.0.0")
+ |> put_req_header("b-forwarded-for", "0.0.0.0")
+ |> put_req_header("x-forwarded-for", "0.0.0.0")
+ |> put_req_header("forwarded", "for=0.0.0.0;host=dashboard.site.com;proto=https")
+ |> put_req_header("x-plausible-ip", "216.160.83.56")
+ |> post("/api/event", params)
+
+ pageview = get_event(site)
+
+ assert pageview.country_code == "US"
+ end
+
test "Uses the Forwarded header when cf-connecting-ip and x-forwarded-for are missing", %{
site: site
} do