diff --git a/Lib/encodings/__init__.py b/Lib/encodings/__init__.py index 04594eab8224b39..95335d7ccb85890 100644 --- a/Lib/encodings/__init__.py +++ b/Lib/encodings/__init__.py @@ -163,8 +163,14 @@ def win32_code_page_search_function(encoding): encoding = encoding.lower() if not encoding.startswith('cp'): return None + # The codec registry caches results by name. + code_page = encoding[2:] + if not code_page.isascii() or not code_page.isdecimal(): + return None + if code_page != '0' and code_page.startswith('0'): + return None try: - cp = int(encoding[2:]) + cp = int(code_page) except ValueError: return None # Test if the code page is supported diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py index 4492e4d874189fa..1606062a41e1586 100644 --- a/Lib/test/test_codecs.py +++ b/Lib/test/test_codecs.py @@ -3454,6 +3454,17 @@ def test_invalid_code_page(self): self.assertRaises(OSError, codecs.code_page_encode, 123, 'a') self.assertRaises(OSError, codecs.code_page_decode, 123, b'a') + def test_lookup_code_page(self): + # Code page 0 selects the current Windows ANSI code page. + self.assertEqual(codecs.lookup('CP0').name, 'cp0') + self.assertEqual(codecs.lookup('windows-1252').name, 'cp1252') + + def test_lookup_invalid_code_page_names(self): + # gh-162462: only the canonical cpXXX spelling is accepted. + for encoding in ('cp01252', 'cp1_252', 'cp+1252', 'cp-1'): + with self.subTest(encoding=encoding): + self.assertRaises(LookupError, codecs.lookup, encoding) + def test_code_page_name(self): self.assertRaisesRegex(UnicodeEncodeError, 'cp932', codecs.code_page_encode, 932, '\xff') diff --git a/Misc/NEWS.d/next/Library/2026-11-23-17-51-17.gh-issue-162462.7bd940.rst b/Misc/NEWS.d/next/Library/2026-11-23-17-51-17.gh-issue-162462.7bd940.rst new file mode 100644 index 000000000000000..c1d2209c71eb38c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-23-17-51-17.gh-issue-162462.7bd940.rst @@ -0,0 +1,2 @@ +Reject noncanonical ``cpXXX`` codec names in the Windows code page lookup, +including numbers with leading zeros, signs, or underscores.