Skip to content

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

Parse bunny header

Uku Taht35ee2fe3fbea
diff --git a/lib/plausible_web/remote_ip.ex b/lib/plausible_web/remote_ip.ex
index 110156eb23..c0a90293cb 100644
--- a/lib/plausible_web/remote_ip.ex
+++ b/lib/plausible_web/remote_ip.ex
@@ -1,19 +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"))
+ 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
cf_connecting_ip ->
- cf_connecting_ip
- |> clean_ip
+ clean_ip(cf_connecting_ip)
- forwarded_for ->
- String.split(forwarded_for, ",")
- |> Enum.map(&String.trim/1)
- |> List.first()
- |> clean_ip
+ b_forwarded_for ->
+ parse_forwarded_for(b_forwarded_for)
+
+ x_forwarded_for ->
+ parse_forwarded_for(x_forwarded_for)
forwarded ->
Regex.named_captures(~r/for=(?<for>[^;,]+).*$/, forwarded)
@@ -41,4 +41,11 @@ defmodule PlausibleWeb.RemoteIp do
|> String.trim_leading("[")
|> String.trim_trailing("]")
end
+
+ defp parse_forwarded_for(header) do
+ String.split(header, ",")
+ |> Enum.map(&String.trim/1)
+ |> List.first()
+ |> clean_ip
+ 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 4a9108f8d6..3203a2b9fe 100644
--- a/test/plausible_web/controllers/api/external_controller_test.exs
+++ b/test/plausible_web/controllers/api/external_controller_test.exs
@@ -623,6 +623,23 @@ defmodule PlausibleWeb.Api.ExternalControllerTest do
assert pageview.country_code == "US"
end
+ test "uses BunnyCDN's custom header for client IP address if present", %{conn: conn} do
+ params = %{
+ name: "pageview",
+ domain: "external-controller-test-bunny.com",
+ url: "http://gigride.live/"
+ }
+
+ conn
+ |> put_req_header("x-forwarded-for", "0.0.0.0")
+ |> put_req_header("b-forwarded-for", "1.1.1.1,9.9.9.9")
+ |> post("/api/event", params)
+
+ pageview = get_event("external-controller-test-bunny.com")
+
+ assert pageview.country_code == "US"
+ end
+
test "Uses the Forwarded header when cf-connecting-ip and x-forwarded-for are missing", %{
conn: conn
} do