Skip to content

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

Open
@solsword

Description

@solsword

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions