Skip to content

gh-75223: Reject undotted extensions in mimetypes.add_type #2895

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
5 changes: 5 additions & 0 deletions Lib/mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,12 @@ def add_type(self, type, ext, strict=True):
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.

Valid extensions are empty or start with a '.'.
Raise a ValueError for invalid extensions.
"""
if ext and not ext.startswith('.'):
raise ValueError("Extensions should start with a '.' or be empty")
self.types_map[strict][ext] = type
exts = self.types_map_inv[strict].setdefault(type, [])
if ext not in exts:
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import sys
import unittest.mock
import warnings

from test import support
from test.support import os_helper
Expand Down Expand Up @@ -305,6 +306,24 @@ def test_keywords_args_api(self):
self.assertEqual(self.db.guess_extension(
type='image/jpg', strict=False), '.jpg')

def test_added_types_are_used(self):
mimetypes.add_type('testing/default-type', '')
mime_type, _ = mimetypes.guess_type('')
self.assertEqual(mime_type, 'testing/default-type')

mime_type, _ = mimetypes.guess_type('test.myext')
self.assertEqual(mime_type, None)

mimetypes.add_type('testing/type', '.myext')
mime_type, _ = mimetypes.guess_type('test.myext')
self.assertEqual(mime_type, 'testing/type')

def test_add_type_with_undotted_extension_raises_exception(self):
with self.assertRaisesRegex(
ValueError, "Extensions should start with a '.' or be empty"
):
mimetypes.add_type('testing/type', 'undotted')


@unittest.skipUnless(sys.platform.startswith("win"), "Windows only")
class Win32MimeTypesTestCase(unittest.TestCase):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Reject undotted extensions in :meth:`mimetypes.MimeTypes.add_type`.
Loading