diff --git a/config/test.exs b/config/test.exs index 3d3b6d9a7..5ea4ce0e7 100644 --- a/config/test.exs +++ b/config/test.exs @@ -23,7 +23,10 @@ config :geolix, %{ id: :country, adapter: Geolix.Adapter.Fake, - data: %{{1, 1, 1, 1} => %{country: %{iso_code: "US"}}} + data: %{ + {1, 1, 1, 1} => %{country: %{iso_code: "US"}}, + {1, 1, 1, 1, 1, 1, 1, 1} => %{country: %{iso_code: "US"}} + } } ] diff --git a/lib/plausible_web/remote_ip.ex b/lib/plausible_web/remote_ip.ex index e8ad3792b..fd7dcf816 100644 --- a/lib/plausible_web/remote_ip.ex +++ b/lib/plausible_web/remote_ip.ex @@ -2,6 +2,7 @@ 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")) + forwarded = List.first(Plug.Conn.get_req_header(conn, "forwarded")) cond do cf_connecting_ip -> @@ -12,6 +13,14 @@ defmodule PlausibleWeb.RemoteIp do |> Enum.map(&String.trim/1) |> List.first() + forwarded -> + Regex.named_captures(~r/for=(?[^;,]+).*$/, forwarded) + |> Map.get("for") + # IPv6 addresses are enclosed in quote marks and square brackets: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded + |> String.trim("\"") + |> String.trim_leading("[") + |> String.trim_trailing("]") + true -> to_string(:inet_parse.ntoa(conn.remote_ip)) end diff --git a/test/plausible_web/controllers/api/external_controller_test.exs b/test/plausible_web/controllers/api/external_controller_test.exs index 014067cd9..4c28d0694 100644 --- a/test/plausible_web/controllers/api/external_controller_test.exs +++ b/test/plausible_web/controllers/api/external_controller_test.exs @@ -510,6 +510,45 @@ defmodule PlausibleWeb.Api.ExternalControllerTest do assert pageview.country_code == "US" end + test "Uses the Forwarded header when cf-connecting-ip and x-forwarded-for are missing", %{ + conn: conn + } do + params = %{ + name: "pageview", + domain: "external-controller-test-forwarded.com", + url: "http://gigride.live/" + } + + conn + |> put_req_header("content-type", "text/plain") + |> put_req_header("forwarded", "by=0.0.0.0;for=1.1.1.1;host=somehost.com;proto=https") + |> post("/api/event", Jason.encode!(params)) + + pageview = get_event("external-controller-test-forwarded.com") + + assert pageview.country_code == "US" + end + + test "Forwarded header can parse ipv6", %{conn: conn} do + params = %{ + name: "pageview", + domain: "external-controller-test-forwarded-ipv6.com", + url: "http://gigride.live/" + } + + conn + |> put_req_header("content-type", "text/plain") + |> put_req_header( + "forwarded", + "by=0.0.0.0;for=\"[1:1:1:1:1:1:1:1]\",for=0.0.0.0;host=somehost.com;proto=https" + ) + |> post("/api/event", Jason.encode!(params)) + + pageview = get_event("external-controller-test-forwarded-ipv6.com") + + assert pageview.country_code == "US" + end + test "URL is decoded", %{conn: conn} do params = %{ name: "pageview",