zeratax / matrix-registration

a token based matrix registration api

Home Page:https://zeratax.github.io/matrix-registration/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

UnboundLocalError: local variable 'token' referenced before assignment

jfmontanaro opened this issue · comments

Describe the bug
The /token endpoint returns a 500 error when the request has an empty body or is missing the Content-Type: application/json header.

To Reproduce

  • Send a POST request to /token with no body or no content-type header

Expected behavior

  1. In the case of no body, the API should return a token created with default parameters.
  2. In the case of no Content-Type header, the API should assume application/json and proceed accordingly, possibly returning a more descriptive error if JSON fails to parse.

System:
Ubuntu, matrix-registration v0.8.1.dev3 (from dockerhub)

In api.py the token object is being created inside the if data: block, so if data is {} then it never gets created. It doesn't look like there should be any problem with moving that statement out of the block.

The content-type issue can be solved by supplying force=True to the get_json call (weird that Flask doesn't default to this IMO, it's bitten me before) assuming you want to support that use case.

I'd be happy to submit a pull request to make these changes if you think they make sense.

yes that does sound sensible, thank you!

Ok, unfortunately it looks like Flask returns a 400 error when force_json=True and the request body is empty. This can be overridden by extending the default flask.Request class object with a custom on_json_loading_failed() method that returns None in that particular case. Not sure if this is worth the added complexity, however.

As an alternative we could also specify silent=False, which would cause get_json() to return None any time JSON parsing fails. This seems like a really bad idea to me though because it would result in the server silently substituting default values any time the user supplies invalid JSON, which would be surprising at best and catastrophic at worst (e.g. someone tries to create a one-time use token with a short lifetime and ends up creating an unlimited-use token that lives forever.)

What do you think? Worth customizing the Request class or no?

actually, wait - BadRequest is an exception, so we can just catch that and handle it. Let me just make sure that works.

Edit: Ok, looks like it does.

Getting the same error when attempting to list tokens as documented, related?

curl -H "Authorization: SharedSecret verysecuresecret" \
     http://localhost:5000/token

Looks like it could be related, does including a Content-Type: application/json header eliminate the issue?