Skip to content

Commit

Permalink
Fix small bug with :passthrough_non_cors_requests
Browse files Browse the repository at this point in the history
  • Loading branch information
whatyouhide committed Jul 24, 2023
1 parent 2bce890 commit c3e17ef
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
18 changes: 14 additions & 4 deletions lib/corsica.ex
Original file line number Diff line number Diff line change
Expand Up @@ -319,10 +319,20 @@ defmodule Corsica do
@impl Plug
def call(%Conn{} = conn, %Options{} = opts) do
cond do
opts.passthrough_non_cors_requests -> put_cors_preflight_resp_headers_no_check(conn, opts)
not cors_req?(conn) -> conn
not preflight_req?(conn) -> put_cors_simple_resp_headers(conn, opts)
true -> send_preflight_resp(conn, opts)
opts.passthrough_non_cors_requests and conn.method == "OPTIONS" ->
send_preflight_resp(conn, opts)

opts.passthrough_non_cors_requests ->
put_cors_simple_resp_headers(conn, opts)

not cors_req?(conn) ->
conn

not preflight_req?(conn) ->
put_cors_simple_resp_headers(conn, opts)

true ->
send_preflight_resp(conn, opts)
end
end

Expand Down
19 changes: 18 additions & 1 deletion test/corsica_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ defmodule CorsicaTest do
assert get_resp_header(conn, "access-control-allow-methods") == []
end

test "with :passthrough_non_cors_requests set to true" do
test "with :passthrough_non_cors_requests set to true and a simple request" do
conn =
conn(:get, "/")
|> Plug.run([
Expand All @@ -557,6 +557,23 @@ defmodule CorsicaTest do
assert conn.status == 200
assert conn.resp_body == "matched"
assert get_resp_header(conn, "access-control-allow-origin") == ["*"]
end

test "with :passthrough_non_cors_requests set to true and a preflight request" do
conn =
conn(:options, "/")
|> Plug.run([
{Corsica, origins: "*", passthrough_non_cors_requests: true, allow_headers: ~w(X-Foo)},
&send_resp(&1, 200, "matched")
])

# The whole point is that this is not even a valid CORS request.
assert get_req_header(conn, "origin") == []

assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body == ""
assert get_resp_header(conn, "access-control-allow-origin") == ["*"]
assert get_resp_header(conn, "access-control-allow-methods") == ["PUT,PATCH,DELETE"]
assert get_resp_header(conn, "access-control-allow-headers") == ["x-foo"]
end
Expand Down

0 comments on commit c3e17ef

Please sign in to comment.