Skip to content

Commit ba22e8f

Browse files
authored
bpo-30566: Fix IndexError when using punycode codec (GH-18632)
Trying to decode an invalid string with the punycode codec shoud raise UnicodeError.
1 parent 8af4712 commit ba22e8f

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

Lib/encodings/punycode.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def decode_generalized_number(extended, extpos, bias, errors):
143143
digit = char - 22 # 0x30-26
144144
elif errors == "strict":
145145
raise UnicodeError("Invalid extended code point '%s'"
146-
% extended[extpos])
146+
% extended[extpos-1])
147147
else:
148148
return extpos, None
149149
t = T(j, bias)

Lib/test/test_codecs.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1343,6 +1343,18 @@ def test_decode(self):
13431343
puny = puny.decode("ascii").encode("ascii")
13441344
self.assertEqual(uni, puny.decode("punycode"))
13451345

1346+
def test_decode_invalid(self):
1347+
testcases = [
1348+
(b"xn--w&", "strict", UnicodeError()),
1349+
(b"xn--w&", "ignore", "xn-"),
1350+
]
1351+
for puny, errors, expected in testcases:
1352+
with self.subTest(puny=puny, errors=errors):
1353+
if isinstance(expected, Exception):
1354+
self.assertRaises(UnicodeError, puny.decode, "punycode", errors)
1355+
else:
1356+
self.assertEqual(puny.decode("punycode", errors), expected)
1357+
13461358

13471359
# From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html
13481360
nameprep_tests = [
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :exc:`IndexError` when trying to decode an invalid string with punycode
2+
codec.

0 commit comments

Comments
 (0)