Skip to content

Commit 4a274b8

Browse files
phihagerikwrede
andauthored
fix: raise proper error when UUID parsing fails (#1582)
* Do not raise AttributeError when parsing non-string UUIDs When a user sends a dictionary or other object as a UUID variable like `{[123]}`, previously graphene crashed with an `AttributeError`, like this: ``` (…) File "…/lib/python3.12/site-packages/graphql/utils/is_valid_value.py", line 78, in is_valid_value parse_result = type.parse_value(value) ^^^^^^^^^^^^^^^^^^^^^^^ File "…/lib/python3.12/site-packages/graphene/types/uuid.py", line 33, in parse_value return _UUID(value) ^^^^^^^^^^^^ File "/usr/lib/python3.12/uuid.py", line 175, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') ^^^^^^^^^^^ AttributeError: 'dict' object has no attribute 'replace' ``` But an `AttributeError` makes it seem like this is the server's fault, when it's obviously the client's. Report a proper GraphQLError. * fix: adjust exception message structure --------- Co-authored-by: Erik Wrede <[email protected]>
1 parent b3db1c0 commit 4a274b8

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

Diff for: graphene/types/tests/test_uuid.py

+15
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,21 @@ def test_uuidstring_query_variable():
3636
assert result.data == {"uuid": uuid_value}
3737

3838

39+
def test_uuidstring_invalid_argument():
40+
uuid_value = {"not": "a string"}
41+
42+
result = schema.execute(
43+
"""query Test($uuid: UUID){ uuid(input: $uuid) }""",
44+
variables={"uuid": uuid_value},
45+
)
46+
assert result.errors
47+
assert len(result.errors) == 1
48+
assert (
49+
result.errors[0].message
50+
== "Variable '$uuid' got invalid value {'not': 'a string'}; UUID cannot represent value: {'not': 'a string'}"
51+
)
52+
53+
3954
def test_uuidstring_optional_uuid_input():
4055
"""
4156
Test that we can provide a null value to an optional input

Diff for: graphene/types/uuid.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from uuid import UUID as _UUID
22

3+
from graphql.error import GraphQLError
34
from graphql.language.ast import StringValueNode
45
from graphql import Undefined
56

@@ -28,4 +29,9 @@ def parse_literal(node, _variables=None):
2829

2930
@staticmethod
3031
def parse_value(value):
31-
return _UUID(value)
32+
if isinstance(value, _UUID):
33+
return value
34+
try:
35+
return _UUID(value)
36+
except (ValueError, AttributeError):
37+
raise GraphQLError(f"UUID cannot represent value: {repr(value)}")

0 commit comments

Comments
 (0)