Skip to content

Commit

Permalink
Support MFArgs in rewrite_on
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed May 14, 2024
1 parent 30fa3f0 commit bd8a574
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/plug/rewrite_on.ex
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ defmodule Plug.RewriteOn do
* `:x_forwarded_port` - to override the port based on on the "x-forwarded-port" header
* `:x_forwarded_proto` - to override the protocol based on on the "x-forwarded-proto" header
A tuple representing a Module-Function-Args can also be given as argument
instead of a list.
Since rewriting the scheme based on `x-forwarded-*` headers can open up
security vulnerabilities, only use this plug if:
Expand All @@ -26,6 +29,7 @@ defmodule Plug.RewriteOn do
import Plug.Conn, only: [get_req_header: 2]

@impl true
def init(header) when is_tuple(header), do: header
def init(header), do: List.wrap(header)

@impl true
Expand Down Expand Up @@ -55,6 +59,10 @@ defmodule Plug.RewriteOn do
conn
end

def call(conn, {mod, fun, args}) do
call(conn, apply(mod, fun, args))
end

defp put_scheme(%{scheme: :http, port: 80} = conn, ["https"]),
do: %{conn | scheme: :https, port: 443}

Expand Down
10 changes: 10 additions & 0 deletions test/plug/rewrite_on_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ defmodule Plug.RewriteOnTest do
Plug.RewriteOn.call(conn, Plug.RewriteOn.init(rewrite))
end

test "rewrites http to https based on MFArgs" do
conn =
conn(:get, "http://example.com/")
|> put_req_header("x-forwarded-proto", "https")
|> call({List, :flatten, [[:x_forwarded_proto]]})

assert conn.scheme == :https
assert conn.port == 443
end

test "rewrites http to https based on x-forwarded-proto" do
conn =
conn(:get, "http://example.com/")
Expand Down

0 comments on commit bd8a574

Please sign in to comment.