diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py index 33045a78721aac..88a9d693ed6c6e 100755 --- a/Lib/test/test_uuid.py +++ b/Lib/test/test_uuid.py @@ -277,9 +277,17 @@ def test_exceptions(self): # Badly formed hex strings. badvalue(lambda: self.uuid.UUID('')) badvalue(lambda: self.uuid.UUID('abc')) + badvalue(lambda: self.uuid.UUID('123_4567812345678123456781234567')) + badvalue(lambda: self.uuid.UUID('123_4567812345678123456781_23456')) badvalue(lambda: self.uuid.UUID('1234567812345678123456781234567')) badvalue(lambda: self.uuid.UUID('123456781234567812345678123456789')) badvalue(lambda: self.uuid.UUID('123456781234567812345678z2345678')) + badvalue(lambda: self.uuid.UUID('0x123456781234567812345678z23456')) + badvalue(lambda: self.uuid.UUID('0X123456781234567812345678z23456')) + badvalue(lambda: self.uuid.UUID('+123456781234567812345678z234567')) + badvalue(lambda: self.uuid.UUID(' 123456781234567812345678z23456 ')) + badvalue(lambda: self.uuid.UUID(' 123456781234567812345678z2345 ')) + badvalue(lambda: self.uuid.UUID('\uff10123456781234567812345678z234567')) # Badly formed bytes. badvalue(lambda: self.uuid.UUID(bytes='abc')) diff --git a/Lib/uuid.py b/Lib/uuid.py index c0150a59d7cb9a..b5641112d65a56 100644 --- a/Lib/uuid.py +++ b/Lib/uuid.py @@ -83,6 +83,7 @@ _MAC_DELIM = b'.' _MAC_OMITS_LEADING_ZEROES = True +_HEX_TT = str.maketrans('', '', 'abcdefABCDEF0123456789') RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [ 'reserved for NCS compatibility', 'specified in RFC 4122', 'reserved for Microsoft compatibility', 'reserved for future definition'] @@ -215,7 +216,8 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, elif hex is not None: hex = hex.replace('urn:', '').replace('uuid:', '') hex = hex.strip('{}').replace('-', '') - if len(hex) != 32: + # ensure that only 32 hex characters pass through + if len(hex) != 32 or hex.translate(_HEX_TT): raise ValueError('badly formed hexadecimal UUID string') int = int_(hex, 16) elif bytes_le is not None: diff --git a/Misc/NEWS.d/next/Library/2024-10-18-09-45-34.gh-issue-125651.M0wSAS.rst b/Misc/NEWS.d/next/Library/2024-10-18-09-45-34.gh-issue-125651.M0wSAS.rst new file mode 100644 index 00000000000000..00c79d2dd87366 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-10-18-09-45-34.gh-issue-125651.M0wSAS.rst @@ -0,0 +1 @@ +Fix HEX parsing of :class:`uuid.UUID`.