1.4 KiB · text History b868907
defmodule GitGudWeb.Plugs.ClientIpTest do
  use ExUnit.Case, async: true

  alias GitGudWeb.Plugs.ClientIp

  @proxy {10, 42, 0, 5}
  @client {203, 0, 113, 7}

  test "a request straight from a client keeps its address, whatever it claims" do
    assert ClientIp.client_ip(@client, ["198.51.100.1"]) == @client
  end

  test "through a trusted proxy, the client is the address the proxy appended" do
    assert ClientIp.client_ip(@proxy, ["203.0.113.7"]) == @client
  end

  test "addresses the client wrote itself, left of the real one, are ignored" do
    assert ClientIp.client_ip(@proxy, ["198.51.100.1, 203.0.113.7"]) == @client
    assert ClientIp.client_ip(@proxy, ["198.51.100.1", "203.0.113.7"]) == @client
  end

  test "trusted hops on the right are skipped" do
    assert ClientIp.client_ip(@proxy, ["203.0.113.7, 10.42.0.9"]) == @client
  end

  test "a garbled entry stops the walk at the proxy" do
    assert ClientIp.client_ip(@proxy, ["not-an-ip"]) == @proxy
    assert ClientIp.client_ip(@proxy, []) == @proxy
  end

  test "IPv6 clients and proxies" do
    assert ClientIp.client_ip({0xFD00, 0, 0, 0, 0, 0, 0, 1}, ["2001:db8::7"]) ==
             {0x2001, 0xDB8, 0, 0, 0, 0, 0, 7}
  end

  test "the plug rewrites remote_ip" do
    conn =
      Plug.Test.conn(:get, "/")
      |> Map.put(:remote_ip, @proxy)
      |> Plug.Conn.put_req_header("x-forwarded-for", "203.0.113.7")
      |> ClientIp.call([])

    assert conn.remote_ip == @client
  end
end