0

I work on a number of Rails sites with forms and take advantage of Rails built-in authenticity token support. Works like a charm. Happy Happy Joy Joy.

It varies, but I would say I average about a SQL injection attack once a month that is successfully caught as having a failed authenticity token check. Wonderful.

The problem is the failed authenticity token check generates an ActionController::InvalidAuthenticityToken exception which returns an HTTP 5xx error because it is an unhandled exception. Good: the bad request is not allowed. Bad: The hacker is functionally informed that my server crashed which is hacker-code for KEEP ATTACKING THIS INTERFACE AT ALL COSTS because they aren't catching this error.

So what is the best way to handle this? If I simply try to wrap my controller method in a try/except, it doesn't even get to my method. It seems that if I want to respond with an access denied or some similar "bad user input" error (HTTP 4xx) then I would have to plug into the pipeline which seems like overkill for something the entire world has to deal with.

Also, what is the proper HTTP response? 400 (Bad Request)? Seems correct, but the other common scenario that generates this error is when a user pulls up your form from cache after the access token has timed out. In this case, the best user experience would be to simply refresh the form with a message saying it took too long for them to fill out the form or something like that. I suppose that could be in the body of an HTTP 400 response.

So how do I build this? Maybe something in the ApplicationController? Why isn't this the default? Maybe it is being handled properly and my "Unhandled Exception" reports are earlier in the pipeline?

MattPo
  • 36
  • 4
  • Does this answer your question? [Gracefully handling InvalidAuthenticityToken exceptions in Rails 4](https://stackoverflow.com/questions/36509300/gracefully-handling-invalidauthenticitytoken-exceptions-in-rails-4) – engineersmnky Oct 05 '22 at 12:54
  • I'm looking into this too and seeing how I can tie it into https://github.com/rack/rack-attack to block the IP. – dylanfm Oct 17 '22 at 10:45

0 Answers0