Skip to content

Commit

Permalink
fix: Don't show detailed errors for anonymous users
Browse files Browse the repository at this point in the history
  • Loading branch information
RulaKhaled committed Nov 4, 2024
1 parent f0fcbcc commit b35b678
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
9 changes: 8 additions & 1 deletion graphql_api/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ async def test_when_debug_is_false_and_exception_we_know(self):
assert data["errors"][0]["type"] == "Unauthorized"
assert data["errors"][0].get("extensions") is None

@override_settings(DEBUG=False)
@override_settings(DEBUG=True)
async def test_when_bad_query(self):
schema = generate_schema_that_raise_with(Unauthorized())
data = await self.do_query(schema, " { fieldThatDoesntExist }")
Expand All @@ -123,6 +123,13 @@ async def test_when_bad_query(self):
== "Cannot query field 'fieldThatDoesntExist' on type 'Query'."
)

@override_settings(DEBUG=False)
async def test_when_bad_query_and_anonymous(self):
schema = generate_schema_that_raise_with(Unauthorized())
data = await self.do_query(schema, " { fieldThatDoesntExist }")
assert data["errors"] is not None
assert data["errors"][0]["message"] == "INTERNAL SERVER ERROR"

@override_settings(DEBUG=False, GRAPHQL_QUERY_COST_THRESHOLD=1000)
@patch("logging.Logger.error")
async def test_when_costly_query(self, mock_error_logger):
Expand Down
6 changes: 5 additions & 1 deletion graphql_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,8 @@ async def post(self, request, *args, **kwargs):

def context_value(self, request, *_):
request_body = json.loads(request.body.decode("utf-8")) if request.body else {}
self.request = request

return {
"request": request,
"service": request.resolver_match.kwargs["service"],
Expand All @@ -300,9 +302,11 @@ def context_value(self, request, *_):
}

def error_formatter(self, error, debug=False):
user = self.request.user
is_anonymous = user.is_anonymous if user else True
# the only way to check for a malformed query
is_bad_query = "Cannot query field" in error.formatted["message"]
if debug or is_bad_query:
if debug or (not is_anonymous and is_bad_query):
return format_error(error, debug)
formatted = error.formatted
formatted["message"] = "INTERNAL SERVER ERROR"
Expand Down

0 comments on commit b35b678

Please sign in to comment.