Whys csrf token is valid after server restart?

Hello,

according to [https://github.com/elixir-plug/plug/blob/master/lib/plug/csrf_protection.ex#L226](http://csrf source code) csrf tokens are saved in process memory.
However I can open any form with generated csrf token, then restart server. After restart I can successfully submit that form and csrf token will be correct. How is that possible?
Process memory should be empty again.

Few more questions:

  • How csrf tokens are invalidated?
  • It sounds like we should setup some kind of ttl for csrf tokens.
  • Is it possible to generate infinite number of tokens and fill up computer memory?

Thanks for answering my newbi questions :slight_smile:

That refers to the temporary state during request processing that allows the CSRF token to be injected automatically in any form rendered in the response. It does not refer to the reference value against which the CSRF token value in the form is verified in subsequent requests. That reference value is stored in the session, e.g. in the session cookie or in whichever session store is configured.

They have the same lifespan as the session. So if a user keeps a form open and their session does not expire in some way, the form submission should succeed without a CSRF error. Unless the server explicitly resets the CSRF token value in the session (which is only effective if the session store is not the session cookie store, since it cannot modify the session that was already sent to the user’s browser).

This is why DB-backed session stores are often preferable to session cookies: they allow for server-side invalidation of the session (and, as part of that, the CSRF token) due to inactivity timeout or some master session timeout.

If you are referring to the CSRF token in the process dictionary, then no, because it is short-lived and is garbage collected when request processing completes and the process terminates.