Fix IP address parsing for ipv6 with port number

pull/1106/head
Uku Taht 6 years ago
parent fa60ebd6b0
commit c0083815d4

@ -7,28 +7,38 @@ defmodule PlausibleWeb.RemoteIp do
cond do
cf_connecting_ip ->
cf_connecting_ip
|> clean_ip
forwarded_for ->
String.split(forwarded_for, ",")
|> Enum.map(&String.trim/1)
|> List.first()
|> remove_port
|> clean_ip
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("]")
|> clean_ip
true ->
to_string(:inet_parse.ntoa(conn.remote_ip))
end
end
defp remove_port(ip) do
String.split(ip, ":")
|> List.first()
# Removes port from both IPv4 and IPv6 addresses. From https://regexr.com/3hpvt
# Removes surrounding [] of an IPv6 address
@port_regex ~r/((\.\d+)|(\]))(?<port>:[0-9]+)$/
defp clean_ip(ip_and_port) do
ip =
case Regex.named_captures(@port_regex, ip_and_port) do
%{"port" => port} -> String.trim_trailing(ip_and_port, port)
_ -> ip_and_port
end
ip
|> String.trim_leading("[")
|> String.trim_trailing("]")
end
end

@ -504,6 +504,38 @@ defmodule PlausibleWeb.Api.ExternalControllerTest do
assert pageview.country_code == "US"
end
test "works with ipv6 without port in x-forwarded-for", %{conn: conn} do
params = %{
name: "pageview",
domain: "external-controller-test-x-forwarded-for-ipv6.com",
url: "http://gigride.live/"
}
conn
|> put_req_header("x-forwarded-for", "1:1:1:1:1:1:1:1")
|> post("/api/event", params)
pageview = get_event("external-controller-test-x-forwarded-for-ipv6.com")
assert pageview.country_code == "US"
end
test "works with ipv6 with a port number in x-forwarded-for", %{conn: conn} do
params = %{
name: "pageview",
domain: "external-controller-test-x-forwarded-for-ipv6-port.com",
url: "http://gigride.live/"
}
conn
|> put_req_header("x-forwarded-for", "[1:1:1:1:1:1:1:1]:123")
|> post("/api/event", params)
pageview = get_event("external-controller-test-x-forwarded-for-ipv6-port.com")
assert pageview.country_code == "US"
end
test "uses cloudflare's special header for client IP address if present", %{conn: conn} do
params = %{
name: "pageview",

Loading…
Cancel
Save