Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/hexdocs/plug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ defmodule Hexdocs.Plug do
conn
|> put_session("oauth_code_verifier", code_verifier)
|> put_session("oauth_state", state)
|> put_session("oauth_return_path", conn.request_path)
|> put_session("oauth_return_path", safe_return_path(conn.request_path))
|> redirect(url)
end

Expand Down Expand Up @@ -362,6 +362,16 @@ defmodule Hexdocs.Plug do
end)
end

defp safe_return_path("/" <> rest = path) do
if String.starts_with?(rest, "/") do
"/"
else
path
end
end

defp safe_return_path(_), do: "/"

defp redirect(conn, url) do
html = Plug.HTML.html_escape(url)
body = "<html><body>You are being <a href=\"#{html}\">redirected</a>.</body></html>"
Expand Down
18 changes: 18 additions & 0 deletions test/hexdocs/plug_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ defmodule Hexdocs.PlugTest do
assert get_session(conn, "oauth_return_path") == "/foo"
end

test "sanitize protocol-relative return path to prevent open redirect" do
conn = conn(:get, "http://plugtest.localhost:5002//evil.com") |> call()
assert conn.status == 302
assert get_session(conn, "oauth_return_path") == "/"
end

test "sanitize protocol-relative return path with extra slashes" do
conn = conn(:get, "http://plugtest.localhost:5002///evil.com/foo") |> call()
assert conn.status == 302
assert get_session(conn, "oauth_return_path") == "/"
end

test "preserve valid return path" do
conn = conn(:get, "http://plugtest.localhost:5002/some/path") |> call()
assert conn.status == 302
assert get_session(conn, "oauth_return_path") == "/some/path"
end

test "OAuth callback with invalid state returns error" do
conn =
conn(:get, "http://plugtest.localhost:5002/oauth/callback?code=abc&state=wrong")
Expand Down