Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Values in Plug.Conn.req_cookies aren't decrypted/verified #1249

Closed
LukasKnuth opened this issue Oct 28, 2024 · 0 comments
Closed

Values in Plug.Conn.req_cookies aren't decrypted/verified #1249

LukasKnuth opened this issue Oct 28, 2024 · 0 comments

Comments

@LukasKnuth
Copy link

I recently found out that Plug.Conn.fetch_cookies/2 populates Plug.Conn.req_cookies with the plain cookie values (as received by the client)

fetch_cookies(%{conn | req_cookies: req_cookies, cookies: cookies}, opts)

while Plug.Conn.cookies contains the encrypted/verified values (if signed: true or encrypted: true where specified)

plug/lib/plug/conn.ex

Lines 1513 to 1529 in e11e5c4

cookies =
verify_or_decrypt(
opts[:signed],
req_cookies,
cookies,
&Plug.Crypto.verify(secret_key_base, &1 <> "_cookie", &2, keys: Plug.Keys)
)
cookies =
verify_or_decrypt(
opts[:encrypted],
req_cookies,
cookies,
&Plug.Crypto.decrypt(secret_key_base, &1 <> "_cookie", &2, keys: Plug.Keys)
)
%{conn | cookies: cookies}

Here is a short piece of code to show what I mean

# A silly thing to get just the signed cookie value.
%Plug.Conn{resp_cookies: %{"testcookie" => %{value: signed_cookie}}} = Plug.Conn.put_resp_cookie(conn, "testcookie", "something", sign: true)

# Now pretend you "received" it and see the Conn
conn
|> Plug.Conn.put_req_header("cookie", "testcookie=#{signed_cookie};")
|> Plug.Conn.fetch_cookies(signed: ["testcookie"])
|> IO.inspect(label: "conn")

The output (shortned) looks like this:

conn: %Plug.Conn{
  cookies: %{"testcookie" => "something"},
  req_cookies: %{
    "testcookie" => "SFMyNTY.g2gDbQAAAAlzb21ldGhpbmduBgAlA7DUkgFiAAFRgA.Bmz7NvWxuHrUZkyB49kmzLKBXirDWs9aMhgwek1E0TY"
  },
  req_headers: [
    {"cookie", "testcookie=SFMyNTY.g2gDbQAAAAlzb21ldGhpbmduBgAlA7DUkgFiAAFRgA.Bmz7NvWxuHrUZkyB49kmzLKBXirDWs9aMhgwek1E0TY;"}
  ],
  resp_cookies: %{},
  ...
}

The only documentation on Plug.Conn.req_cookies I could find is this bit in the "Fetchable Fields" section:

  • req_cookies - the request cookies (without the response ones)

Is this behavior expected? I certainly didn't expect it. I was expecting req_cookies to simply be cookies but without the resp_cookies. If this is expected behavior, we should document it thoroughly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant