Use `forwarded` header when X-Forwarded-For is missing

pull/1073/head
Uku Taht 6 years ago
parent 5ee3167786
commit 2cf0c1a456

@ -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"}}
}
}
]

@ -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=(?<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

@ -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",

Loading…
Cancel
Save