cappslock reported that when using the Discourse API to create a post on behalf of a non-existent user via the api_username parameter, the server returns a generic 500 error with no response body, making it impossible to distinguish between an invalid username and an invalid API key. codinghorror acknowledged the need for better error descriptions. techAPJ initially explained that the Discourse::InvalidAccess exception is by design to prevent leaking information, noting that a 403 with a specific message occurs if credentials are valid but access is denied. However, cappslock clarified that their raw HTTP requests resulted in a 500 with an empty body. After cappslock provided a curl example demonstrating the issue, techAPJ identified the root cause: the request headers. By switching to Accept: application/json and Content-Type: application/json, the API correctly returns a 403 Forbidden status with a descriptive JSON error message (invalid_access), rather than a 500 error.
On the beta branch, when attempting to create a POST on behalf of a user, I use the API and provide the username as the api_username. Because of the way I’m managing users, the user may not exist in Discourse at this time and I’d like to be able to respond to that exception by creating the user. It would be useful if the error had enough context to determine that this case occurred, but instead, it’s raising a Discourse::InvalidAccess and the server is returning a 500.
I can work around this, but it would be nice if the server responded with something in the 4xx range and enough information to determine the cause of the issue.
Just curious, is there an issue or something else I can follow related to this bug? I have a bit of code to work around it that I’d like to rip out once I know that I can
Thanks for the reply. In my tests, it would reply with a 500 with no
response body. It’s impossible to know the reason for the failure in that
case. I would think something in the 4xx range with some information
indicating the cause of the error (a username that does not exist) would be
more helpful and appropriate, no?
Here’s an example curl command with sensitive data stripped out:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'raw=demo of failing post on behalf of non-existent api-user&title=herp derp jerp' "<my_discourse_instance>/posts?api_key=<valid_api_key>&api_username=<nonexistent_username>" -i