maxcountryman / flask-seasurf

SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).
http://readthedocs.org/docs/flask-seasurf/
Other
190 stars 49 forks source link

CSRF validation crashes when app.secret_key is bytes, not str #137

Open solsword opened 1 year ago

solsword commented 1 year ago

I don't have time to throw together an MWE for this, but I got the following error message today and fixed it by changing my flask app secret_key variable to be a string instead of bytes:

...
File "/home/potluck/server-python/lib/python3.9/site-packages/flask_seasurf.py", line 441, in _before_request                                                                                
    self.validate()
File "/home/potluck/server-python/lib/python3.9/site-packages/flask_seasurf.py", line 341, in validate
    if some_none or not safe_str_cmp(request_csrf_token, server_csrf_token):
TypeError: a bytes-like object is required, not 'str'                                   

The flask docs say:

"It should be a long random bytes or str."

But it seems like flask_seasurf assumes it's a string, not bytes. Sadly, if it is bytes, converting to a str is not trivial due to encoding errors, although if only the entropy is needed, something like:

''.join(hex(c)[2:] for c in bytes)

Will work to convert to a string without dealing with non-decodable bytes.

If a fix like this is too complex, at least a more detailed warning message would be helpful for others running into this issue; it may be there aren't many since I couldn't find a post like this via web search.