dream icon indicating copy to clipboard operation
dream copied to clipboard

CSRF tokens not sessioned when using scope and memory_sessions

Open keatonuw opened this issue 4 months ago • 1 comments

Hi!

I've encountered some strange behavior when using Dream.memory_sessions as middleware within a Dream.scope. Forms that contain injected CSRF tokens via Dream.csrf_tag do not seem to store these tokens in the sessions, per the logger:

dream.csrf  WARN REQ 2 CSRF token not for this session

Confusingly, all works as expected if the Dream.memory_sessions middleware is replaced with Dream.cookie_sessions.

I've created a modified version of d-form to reproduce the bug:

let show_form ?message request =
  <html>
  <body>

%   begin match message with
%   | None -> ()
%   | Some message ->
      <p>You entered: <b><%s message %>!</b></p>
%   end;

    <form method="POST" action="/">
      <%s! Dream.csrf_tag request %>
      <input name="message" autofocus>
    </form>

  </body>
  </html>

let () =
  Dream.run
  @@ Dream.logger
  @@ Dream.router [

        Dream.scope "/" [Dream.memory_sessions] [
            Dream.get  "/"
              (fun request ->
                Dream.html (show_form request));

            Dream.post "/"
              (fun request ->
                match%lwt Dream.form request with
                | `Ok ["message", message] ->
                  Dream.html (show_form ~message request)
                | _ ->
                  Dream.empty `Bad_Request);

        ];
  ]

I'm afraid I'm too new to the framework to tell whether this is a bug or mistake on my end. Hope this is enough info! Thanks!

keatonuw avatar Sep 26 '24 00:09 keatonuw