Skip to content

Commit bf4546a

Browse files
committed
Reject 0x, signs, underscores and stray hyphens in uuid()
UUID() drops every hyphen wherever it is and parses the rest with int(), so strings like "0x" plus 30 hex digits or a UUID with a moved hyphen were accepted. The regex fallback meant to catch this never ran because a UUID object is always truthy. Match the forms UUID() documents directly instead.
1 parent 22786cc commit bf4546a

2 files changed

Lines changed: 17 additions & 6 deletions

File tree

‎src/validators/uuid.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ def uuid(value: Union[str, UUID], /):
3535
return False
3636
if isinstance(value, UUID):
3737
return True
38-
try:
39-
return UUID(value) or re.match(
40-
r"^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$", value
41-
)
42-
except ValueError:
43-
return False
38+
# Not UUID(value): it drops hyphens wherever they are and reads the rest with int(),
39+
# which also takes "0x", signs, underscores, surrounding spaces and non-ASCII digits.
40+
return re.fullmatch(
41+
r"(?:urn:uuid:)?(\{)?[0-9a-fA-F]{8}(-?)(?:[0-9a-fA-F]{4}\2){3}[0-9a-fA-F]{12}(?(1)\})",
42+
value,
43+
)

‎tests/test_uuid.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
("2bc1c94f-0deb-43e9-92a1-4775189ec9f8",),
1919
(uuid4(),),
2020
("888256d7c49341f19fa33f29d3f820d7",),
21+
("2BC1C94F-0DEB-43E9-92A1-4775189EC9F8",),
22+
("{2bc1c94f-0deb-43e9-92a1-4775189ec9f8}",),
23+
("{888256d7c49341f19fa33f29d3f820d7}",),
24+
("urn:uuid:2bc1c94f-0deb-43e9-92a1-4775189ec9f8",),
2125
],
2226
)
2327
def test_returns_true_on_valid_uuid(value: Union[str, UUID]):
@@ -32,6 +36,13 @@ def test_returns_true_on_valid_uuid(value: Union[str, UUID]):
3236
("2bc1c94f-0deb-43e9-92a1-4775189ec9f",),
3337
("gbc1c94f-0deb-43e9-92a1-4775189ec9f8",),
3438
("2bc1c94f 0deb-43e9-92a1-4775189ec9f8",),
39+
("2bc1c94f-0deb4-3e9-92a1-4775189ec9f8",),
40+
("2bc1c94f-0deb43e992a14775189ec9f8",),
41+
("0xc1c94f0deb43e992a14775189ec9f8",),
42+
("+bc1c94f0deb43e992a14775189ec9f8",),
43+
("2bc1c94f_deb43e992a14775189ec9f8",),
44+
(" bc1c94f0deb43e992a14775189ec9f ",),
45+
("2bc1c94f-0deb-43e9-92a1-4775189ec9f8}",),
3546
],
3647
)
3748
def test_returns_failed_validation_on_invalid_uuid(value: Union[str, UUID]):

0 commit comments

Comments
 (0)