From 35ee2fe3fbea43a1112151fb950226e7d6e23433 Mon Sep 17 00:00:00 2001 From: Uku Taht Date: Sat, 15 Jan 2022 08:57:25 -0600 Subject: [PATCH] Parse bunny header --- lib/plausible_web/remote_ip.ex | 23 ++++++++++++------- .../api/external_controller_test.exs | 17 ++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/lib/plausible_web/remote_ip.ex b/lib/plausible_web/remote_ip.ex index 110156eb2..c0a90293c 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=(?[^;,]+).*$/, 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 4a9108f8d..3203a2b9f 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