1.9 KiB · text History 4b6fe3b
defmodule OhMyExOhIrcd.IRC.ProxyTest do
  use ExUnit.Case, async: true

  alias OhMyExOhIrcd.IRC.Proxy

  @v2_sig <<0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A>>

  describe "v1" do
    test "parses a TCP4 header and returns leftover" do
      blob = "PROXY TCP4 198.51.100.7 10.0.0.1 56324 6697\r\nNICK alice\r\n"
      assert {:ok, "198.51.100.7", leftover} = Proxy.parse(blob)
      assert leftover == "NICK alice\r\n"
    end

    test "TCP6" do
      blob = "PROXY TCP6 2001:db8::1 fd00::2 1234 6667\r\n"
      assert {:ok, "2001:db8::1", ""} = Proxy.parse(blob)
    end

    test "UNKNOWN" do
      blob = "PROXY UNKNOWN\r\n"
      assert {:ok, "unknown", ""} = Proxy.parse(blob)
    end

    test "truncated v1 errors" do
      assert {:error, :truncated_v1} = Proxy.parse("PROXY TCP4 1.2.3.4 5.6.7.8 1 2")
    end
  end

  describe "v2" do
    test "parses an IPv4 TCP header" do
      addr =
        <<198::8, 51::8, 100::8, 7::8, 10::8, 0::8, 0::8, 1::8, 56_324::16-big, 6697::16-big>>

      header = @v2_sig <> <<0x21>> <> <<0x11>> <> <<byte_size(addr)::16-big>> <> addr
      blob = header <> "NICK alice\r\n"

      assert {:ok, "198.51.100.7", "NICK alice\r\n"} = Proxy.parse(blob)
    end

    test "LOCAL command (healthcheck) is reported with a synthetic IP" do
      header = @v2_sig <> <<0x20>> <> <<0x00>> <> <<0::16-big>>
      assert {:ok, "local-healthcheck", ""} = Proxy.parse(header)
    end

    test "truncated v2 errors" do
      header = @v2_sig <> <<0x21>> <> <<0x11>> <> <<100::16-big>> <> "\x01\x02\x03"
      assert {:error, :truncated_v2} = Proxy.parse(header)
    end
  end

  describe "fall-through" do
    test "non-PROXY data returns :no_header" do
      assert :no_header = Proxy.parse("NICK foo\r\n")
    end

    test "PROXY without space returns :no_header" do
      assert :no_header = Proxy.parse("PROXYish")
    end
  end
end