Version in base suite: 4.2.28-0+deb13u2 Base version: python-django_4.2.28-0+deb13u2 Target version: python-django_4.2.30-0+deb13u1 Base file: /srv/ftp-master.debian.org/ftp/pool/main/p/python-django/python-django_4.2.28-0+deb13u2.dsc Target file: /srv/ftp-master.debian.org/policy/pool/main/p/python-django/python-django_4.2.30-0+deb13u1.dsc Django.egg-info/PKG-INFO | 2 Django.egg-info/SOURCES.txt | 2 PKG-INFO | 2 debian/changelog | 125 +++++ debian/patches/0007-CVE-2026-15337.patch | 151 ++++++ debian/patches/0008-CVE-2026-15920.patch | 82 +++ debian/patches/0009-CVE-2026-77050.patch | 171 +++++++ debian/patches/0010-CVE-2026-84429.patch | 192 ++++++++ debian/patches/0011-CVE-2026-108147.patch | 232 ++++++++++ debian/patches/0012-CVE-2026-113593.patch | 71 +++ debian/patches/0013-Adjust-the-scaling-factor-in-the-test-for-CVE-2025-6.patch | 22 debian/patches/series | 7 django/__init__.py | 2 django/contrib/admin/options.py | 3 django/contrib/contenttypes/admin.py | 15 django/core/cache/backends/filebased.py | 10 django/core/files/storage/filesystem.py | 13 django/core/handlers/asgi.py | 3 django/forms/fields.py | 42 - django/http/multipartparser.py | 15 django/http/request.py | 45 + django/test/client.py | 5 django/utils/_os.py | 58 ++ docs/releases/4.2.29.txt | 45 + docs/releases/4.2.30.txt | 69 ++ docs/releases/index.txt | 2 docs/releases/security.txt | 91 +++ tests/admin_views/admin.py | 10 tests/admin_views/tests.py | 17 tests/asgi/tests.py | 170 +++++++ tests/forms_tests/field_tests/test_urlfield.py | 84 +++ tests/generic_inline_admin/tests.py | 116 ++++- tests/requests_tests/tests.py | 114 ++++ tests/utils_tests/test_os_utils.py | 166 +++++++ 34 files changed, 2076 insertions(+), 78 deletions(-) dpkg-source: warning: cannot verify inline signature for /srv/release.debian.org/tmp/tmpqpq8nstk/python-django_4.2.28-0+deb13u2.dsc: no acceptable signature found dpkg-source: warning: cannot verify inline signature for /srv/release.debian.org/tmp/tmpqpq8nstk/python-django_4.2.30-0+deb13u1.dsc: no acceptable signature found diff -Nru python-django-4.2.28/Django.egg-info/PKG-INFO python-django-4.2.30/Django.egg-info/PKG-INFO --- python-django-4.2.28/Django.egg-info/PKG-INFO 2026-02-03 13:31:34.000000000 +0000 +++ python-django-4.2.30/Django.egg-info/PKG-INFO 2026-04-07 11:46:37.000000000 +0000 @@ -1,6 +1,6 @@ Metadata-Version: 2.4 Name: Django -Version: 4.2.28 +Version: 4.2.30 Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design. Author-email: Django Software Foundation License: BSD-3-Clause diff -Nru python-django-4.2.28/Django.egg-info/SOURCES.txt python-django-4.2.30/Django.egg-info/SOURCES.txt --- python-django-4.2.28/Django.egg-info/SOURCES.txt 2026-02-03 13:31:34.000000000 +0000 +++ python-django-4.2.30/Django.egg-info/SOURCES.txt 2026-04-07 11:46:38.000000000 +0000 @@ -4212,7 +4212,9 @@ docs/releases/4.2.26.txt docs/releases/4.2.27.txt docs/releases/4.2.28.txt +docs/releases/4.2.29.txt docs/releases/4.2.3.txt +docs/releases/4.2.30.txt docs/releases/4.2.4.txt docs/releases/4.2.5.txt docs/releases/4.2.6.txt diff -Nru python-django-4.2.28/PKG-INFO python-django-4.2.30/PKG-INFO --- python-django-4.2.28/PKG-INFO 2026-02-03 13:31:37.694834700 +0000 +++ python-django-4.2.30/PKG-INFO 2026-04-07 11:46:40.550823200 +0000 @@ -1,6 +1,6 @@ Metadata-Version: 2.4 Name: Django -Version: 4.2.28 +Version: 4.2.30 Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design. Author-email: Django Software Foundation License: BSD-3-Clause diff -Nru python-django-4.2.28/debian/changelog python-django-4.2.30/debian/changelog --- python-django-4.2.28/debian/changelog 2026-05-26 21:35:49.000000000 +0000 +++ python-django-4.2.30/debian/changelog 2026-11-05 17:27:41.000000000 +0000 @@ -1,3 +1,128 @@ +python-django (3:4.2.30-0+deb13u1) trixie-security; urgency=high + + * New upstream security release (4.2.30): + + - CVE-2026-3902: ASGI header spoofing via underscore/hyphen conflation. + ASGIRequest normalizes header names following WSGI conventions, mapping + hyphens to underscores. As a result, even in configurations where reverse + proxies carefully strip security-sensitive headers named with hyphens, + such a header could be spoofed by supplying a header named with + underscores. Under WSGI, it is the responsibility of the server or proxy + to avoid ambiguous mappings. (Django's runserver was patched via + CVE-2015-0219.) But under ASGI, there is not the same uniform + expectation, even if many proxies protect against this under default + configuration (including nginx via underscores_in_headers off;). Headers + containing underscores are now ignored by ASGIRequest, matching the + behavior of Daphne, the reference server for ASGI. + + - CVE-2026-4277: Privilege abuse in GenericInlineModelAdmin. Add + permissions on inline model instances were not validated on submission of + forged POST data in GenericInlineModelAdmin. + + - CVE-2026-4292: Privilege abuse in ModelAdmin.list_editable. Admin + changelist forms using ModelAdmin.list_editable incorrectly allowed new + instances to be created via forged POST data. + + - CVE-2026-33033: Potential denial-of-service vulnerability in + MultiPartParser via base64-encoded file upload. When using + django.http.multipartparser.MultiPartParser, multipart uploads with + Content-Transfer-Encoding: base64 that include excessive whitespace may + trigger repeated memory copying, potentially degrading performance. + + - CVE-2026-33034: Potential denial-of-service vulnerability in ASGI + requests via memory upload limit bypass. ASGI requests with a missing or + understated Content-Length header could bypass the + DATA_UPLOAD_MAX_MEMORY_SIZE limit when reading HttpRequest.body, + potentially loading an unbounded request body into memory and causing + service degradation. + + * New upstream security release (4.2.29): + + - CVE-2026-25674: Potential incorrect permissions on newly created file + system objects. + + Django's file-system storage and file-based cache backends used the + process umask to control permissions when creating directories. In + multi-threaded environments, one thread's temporary umask change can + affect other threads' file and directory creation, resulting in file + system objects being created with unintended permissions. Django now + applies the requested permissions via os.chmod() after os.mkdir(), + removing the dependency on the process-wide umask. + + - One additional issue (CVE-2026-25673) to address a Windows-specific issue + is also fixed in this version. This is potential denial-of-service + vulnerability in URLField via Unicode normalization. + + * In addition: + + - CVE-2026-15337: Avoid a potential denial-of-service vulnerability in the + check_for_language() method in the django.utils.translation method. This + was subject to a potential denial-of-service (DoS) attack when checking + many distinct, very long language codes. Each code was used as a key in + an in-memory cache, consuming process memory. + + The language value reaches this function through the set_language() view + of django.views.i18n (which is not active by default) from POST data. + Since request data is limited by the DATA_UPLOAD_MAX_MEMORY_SIZE setting + and the cache is configured to store a maximum number of entries, the + memory that could be consumed was bounded. To mitigate this + vulnerability, language codes longer than 500 characters are now rejected + before the cached lookup. + + - CVE-2026-15920: Prevent a potential cross-site scripting (XSS) attack via + URLField values in the Django admin. The admin renders URLField values as + clickable links on changelist views and read-only fields. The link was + generated without validating the value as a safe URL, so a stored value + using a potentially dangerous scheme was rendered as a link. URLField + values shown via display_for_field are now validated using URLValidator + before a link is rendered and displayed as plain text if validation is + failed. + + - CVE-2026-77050: Potential denial-of-service vulnerability in + get_supported_language_variant. This method was subject to a potential + denial-of-service attack when processing many distinct and very long + language codes. Language codes were used as keys in an in-memory cache + before their length was limited, potentially consuming excessive process + memory. To mitigate this vulnerability, language codes longer than 500 + characters are now rejected or truncated before the cached lookup. + + - CVE-2026-84429: Potential denial-of-service vulnerability in HTTP header + parsing. django.utils.http.parse_header_parameters() was subject to a + potential denial-of-service attack due to quadratic time complexity when + parsing a value with many separators inside a quoted parameter. An + unauthenticated request could reach this through common headers such as + Accept or Content-Type, for instance via the content negotiation + performed by HttpRequest.accepts(). The per-call length limit does not + bound the combined size of repeated headers. The undocumented + django.utils.http.parse_header_parameters() function now uses Python's + email.message.Message for parsing. As a result, parsing of some malformed + or unusual header values may differ, for example, RFC 2231 values with a + missing encoding are now decoded. + + - CVE-2026-108147: Prevent a potential memory exhaustion in MultiPartParser + via base64-encoded file uploads. When using django.http.multipartparser's + MultiPartParser, multipart uploads with a "Content-Transfer-Encoding: + base64" header could be buffered entirely in memory regardless of the + value of FILE_UPLOAD_MAX_MEMORY_SIZE before being passed to upload + handlers, potentially consuming excessive memory. + + - CVE-2026-113593: Avoid a potential exposure of private data via empty and + missing 'Vary' headers. UpdateCacheMiddleware and cache_page() generated + the same cache key for a request that omitted a header listed in the + response's 'Vary' header and a request that sent that header with an + empty value. As a result, a response cached for one of these requests + could be served to the other which could lead to the exposure of private + data. Cache keys now distinguish between absent and empty header values + as required by RFC 9111#section-4.1. Responses previously cached for + requests that omitted a header listed in 'Vary' will no longer be + matched and will be cached again on the next request. + + * Lastly, we adjust the scaling factor in the test for CVE-2025-64460 added + in 3:4.2.27-0+deb13u1 as it causes flakiness on loaded machines, and, in + particular, on the runners for Debian autopkgtests. (Closes: #1126323) + + -- Chris Lamb Thu, 05 Nov 2026 09:27:41 -0800 + python-django (3:4.2.28-0+deb13u2) stable-proposed-updates; urgency=medium * The fix for CVE-2025-6069 in the python3.13 source package (released diff -Nru python-django-4.2.28/debian/patches/0007-CVE-2026-15337.patch python-django-4.2.30/debian/patches/0007-CVE-2026-15337.patch --- python-django-4.2.28/debian/patches/0007-CVE-2026-15337.patch 1970-01-01 00:00:00.000000000 +0000 +++ python-django-4.2.30/debian/patches/0007-CVE-2026-15337.patch 2026-11-05 17:27:41.000000000 +0000 @@ -0,0 +1,151 @@ +From: Natalia <124304+nessita@users.noreply.github.com> +Date: Fri, 10 Jul 2026 18:30:21 -0300 +Subject: [PATCH] [5.2.x] Fixed CVE-2026-15337 -- Mitigated potential DoS in + check_for_language(). + +Language codes longer than 500 characters are now rejected before the +cached lookup, so they are no longer retained as cache keys consuming +memory from each process. + +Thanks Jaeyoung Jang for the report, and Sarah Boyce for reviews. + +Backport of 27137e655e442e81095f1f8f77ff3870d9fdf169 from main. + +Origin: upstream, https://github.com/django/django/commit/c72a5dbb64d0777f3f471f1be94e8b2ca91e0959.patch +--- + django/test/signals.py | 2 +- + django/utils/translation/trans_real.py | 27 +++++++++++++++++++-------- + docs/ref/utils.txt | 3 +++ + tests/i18n/tests.py | 24 +++++++++++++++++++++++- + 4 files changed, 46 insertions(+), 10 deletions(-) + +diff --git a/django/test/signals.py b/django/test/signals.py +index 1358101b9802..553c5a664e2b 100644 +--- a/django/test/signals.py ++++ b/django/test/signals.py +@@ -153,7 +153,7 @@ def language_changed(*, setting, **kwargs): + from django.utils.translation import trans_real + + trans_real._translations = {} +- trans_real.check_for_language.cache_clear() ++ trans_real.translation_catalog_exists.cache_clear() + + + @receiver(setting_changed) +diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py +index 4677610e13d2..a7a47e297982 100644 +--- a/django/utils/translation/trans_real.py ++++ b/django/utils/translation/trans_real.py +@@ -30,9 +30,10 @@ _default = None + # magic gettext number to separate context from message + CONTEXT_SEPARATOR = "\x04" + +-# Maximum number of characters that will be parsed from the Accept-Language +-# header or cookie to prevent possible denial of service or memory exhaustion +-# attacks. About 10x longer than the longest value shown on MDN’s ++# Maximum length of a language code that will be processed, to prevent possible ++# denial of service or memory exhaustion attacks. Language codes are taken from ++# the Accept-Language header, the language cookie, the URL path prefix, or the ++# set_language() view. 500 is about 10x the longest value shown on MDN's + # Accept-Language page. + LANGUAGE_CODE_MAX_LENGTH = 500 + +@@ -64,7 +65,7 @@ def reset_cache(*, setting, **kwargs): + languages should no longer be accepted. + """ + if setting in ("LANGUAGES", "LANGUAGE_CODE"): +- check_for_language.cache_clear() ++ translation_catalog_exists.cache_clear() + get_languages.cache_clear() + get_supported_language_variant.cache_clear() + +@@ -459,19 +460,29 @@ def all_locale_paths(): + return [globalpath, *settings.LOCALE_PATHS, *app_paths] + + +-@functools.lru_cache(maxsize=1000) + def check_for_language(lang_code): + """ + Check whether there is a global language file for the given language + code. This is used to decide whether a user-provided language is + available. + +- lru_cache should have a maxsize to prevent from memory exhaustion attacks, +- as the provided language codes are taken from the HTTP request. See also ++ Reject over-length codes before the cached lookup so that oversized, ++ attacker-controlled values are not retained as cache keys. ++ """ ++ if lang_code is None or len(lang_code) > LANGUAGE_CODE_MAX_LENGTH: ++ return False ++ return translation_catalog_exists(lang_code) ++ ++ ++@functools.lru_cache(maxsize=1000) ++def translation_catalog_exists(lang_code): ++ """Return whether a translation catalog exists for the given language code. ++ ++ lru_cache should have a maxsize to prevent memory exhaustion attacks. See: + . + """ + # First, a quick check to make sure lang_code is well-formed (#21458) +- if lang_code is None or not language_code_re.search(lang_code): ++ if not language_code_re.search(lang_code): + return False + return any( + gettext_module.find("django", path, [to_locale(lang_code)]) is not None +diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt +index acf7afd4a780..c65fea4c808b 100644 +--- a/docs/ref/utils.txt ++++ b/docs/ref/utils.txt +@@ -1124,6 +1124,9 @@ For a complete discussion on the usage of the following see the + code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided + language is available. + ++ ``lang_code`` has a maximum accepted length of 500 characters. ``False`` ++ is returned if it exceeds this limit, before any language-file lookup. ++ + .. function:: get_language() + + Returns the currently selected language code. Returns ``None`` if +diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py +index a2a747f6ea27..e0b2106d4f7a 100644 +--- a/tests/i18n/tests.py ++++ b/tests/i18n/tests.py +@@ -65,7 +65,10 @@ from django.utils.translation.reloader import ( + translation_file_changed, + watch_for_translation_changes, + ) +-from django.utils.translation.trans_real import LANGUAGE_CODE_MAX_LENGTH ++from django.utils.translation.trans_real import ( ++ LANGUAGE_CODE_MAX_LENGTH, ++ translation_catalog_exists, ++) + + from .forms import CompanyForm, I18nForm, SelectDateForm + from .models import Company, TestModel +@@ -2211,6 +2214,25 @@ class CountrySpecificLanguageTests(SimpleTestCase): + self.assertFalse(check_for_language("tr-TR.UTF8")) + self.assertFalse(check_for_language("de-DE.utf-8")) + ++ def test_check_for_language_lang_code_max_length(self): ++ self.addCleanup(translation_catalog_exists.cache_clear) ++ ++ # Overly long codes are rejected before the cached lookup, so they are ++ # not retained as cache keys, potentially consuming too much memory. ++ # Codes at the maximum length can reach the cached lookup. ++ for length, cache_size in [ ++ (LANGUAGE_CODE_MAX_LENGTH - 1, 1), ++ (LANGUAGE_CODE_MAX_LENGTH, 1), ++ (LANGUAGE_CODE_MAX_LENGTH + 1, 0), ++ ]: ++ translation_catalog_exists.cache_clear() ++ with self.subTest(length=length): ++ self.assertIs(check_for_language("a" * length), False) ++ self.assertEqual( ++ translation_catalog_exists.cache_info().currsize, ++ cache_size, ++ ) ++ + def test_check_for_language_null(self): + self.assertIs(trans_null.check_for_language("en"), True) + diff -Nru python-django-4.2.28/debian/patches/0008-CVE-2026-15920.patch python-django-4.2.30/debian/patches/0008-CVE-2026-15920.patch --- python-django-4.2.28/debian/patches/0008-CVE-2026-15920.patch 1970-01-01 00:00:00.000000000 +0000 +++ python-django-4.2.30/debian/patches/0008-CVE-2026-15920.patch 2026-11-05 17:27:41.000000000 +0000 @@ -0,0 +1,82 @@ +From: Natalia <124304+nessita@users.noreply.github.com> +Date: Mon, 13 Jul 2026 20:12:05 -0300 +Subject: [PATCH] [5.2.x] Fixed CVE-2026-15920 -- Made display_for_field() + validate URLs before rendering admin links. + +The admin renders URLField values as clickable links on changelists and +read-only change forms. The link was built without validating the URL, +so a potentially dangerous stored value could be rendered as a link that +runs script in a staff member's authenticated session when clicked. + +The admin renders URLField values as clickable links on changelists and +read-only change forms. The link was built without validating the URL, +so a stored value using a potentially dangerous value was rendered as a +link, which could lead to cross-site scripting in an authenticated admin +session. + +Refs CVE-2019-12308, #36032. + +Thanks to Egor Saltykov for the report, and Sarah Boyce for reviews. + +Backport of 47511a21026cdd721d8fbf8571cc079bc38bb46d from main. + +Origin: upstream, https://github.com/django/django/commit/b9adb81339cc418f8f56b1050cca6dfec3ab6349.patch +--- + django/contrib/admin/utils.py | 12 +++++++++++- + tests/admin_utils/tests.py | 13 +++++++++++++ + 2 files changed, 24 insertions(+), 1 deletion(-) + +diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py +index b971bd528f98..8d191bff2902 100644 +--- a/django/contrib/admin/utils.py ++++ b/django/contrib/admin/utils.py +@@ -3,7 +3,8 @@ import decimal + import json + from collections import defaultdict + +-from django.core.exceptions import FieldDoesNotExist ++from django.core.exceptions import FieldDoesNotExist, ValidationError ++from django.core.validators import URLValidator + from django.db import models, router + from django.db.models.constants import LOOKUP_SEP + from django.db.models.deletion import Collector +@@ -426,6 +427,15 @@ def display_for_field(value, field, empty_value_display): + return formats.number_format(value) + elif isinstance(field, models.FileField) and value: + return format_html('{}', value.url, value) ++ elif isinstance(field, models.URLField) and value: ++ # Only render a clickable link for URLs with a safe scheme, so that a ++ # potentially dangerous stored value is shown as plain text rather than ++ # an executable link. The check is deliberately independent of the ++ # field's own validators, which may permit such schemes. ++ try: ++ URLValidator()(value) ++ except ValidationError: ++ return display_for_value(value, empty_value_display) + elif isinstance(field, models.JSONField) and value: + try: + return json.dumps(value, ensure_ascii=False, cls=field.encoder) +diff --git a/tests/admin_utils/tests.py b/tests/admin_utils/tests.py +index 113f5f7024bd..6fed029eb253 100644 +--- a/tests/admin_utils/tests.py ++++ b/tests/admin_utils/tests.py +@@ -200,6 +200,19 @@ class UtilsTests(SimpleTestCase): + display_value, + ) + ++ def test_url_display_for_field_invalid_url(self): ++ # An invalid URL, such as one with an unsafe scheme, is rendered as ++ # plain text instead of a clickable link. ++ model_field = models.URLField() ++ for value in [ ++ "javascript:alert(1)", ++ "data:text/html,", ++ ]: ++ with self.subTest(value=value): ++ display_value = display_for_field(value, model_field, self.empty_value) ++ self.assertNotIn(" +Date: Wed, 19 Aug 2026 12:44:41 +0200 +Subject: [PATCH] [5.2.x] Fixed CVE-2026-77050 -- Prevented memory exhaustion + in get_supported_language_variant(). + +The fix for CVE-2024-39614 limited the length of language codes processed by +get_supported_language_variant(), but the full language code was retained as +an lru_cache key before the length check. + +Moved caching after language code truncation and validation to prevent +excessively long language codes from being retained in memory. + +Thank you to Gleb Lizunov for the report and Jacob Walls for the review. + +Backport of c88b304cc2d90fc37d3bd1f5f3829706fa6c13bc from main. + +Origin: upstream, https://github.com/django/django/commit/02a69e3791e3df23d45ea4ea7e7fc489f0eef2be.patch +--- + django/utils/translation/trans_real.py | 72 +++++++++++++++++----------------- + tests/i18n/tests.py | 39 ++++++++++++++++++ + 2 files changed, 74 insertions(+), 37 deletions(-) + +diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py +index a7a47e297982..c5c9084e3b30 100644 +--- a/django/utils/translation/trans_real.py ++++ b/django/utils/translation/trans_real.py +@@ -67,7 +67,7 @@ def reset_cache(*, setting, **kwargs): + if setting in ("LANGUAGES", "LANGUAGE_CODE"): + translation_catalog_exists.cache_clear() + get_languages.cache_clear() +- get_supported_language_variant.cache_clear() ++ _get_supported_language_variant.cache_clear() + + + class TranslationCatalog: +@@ -500,6 +500,31 @@ def get_languages(): + + + @functools.lru_cache(maxsize=1000) ++def _get_supported_language_variant(lang_code, strict=False): ++ # If 'zh-hant-tw' is not supported, try special fallback or subsequent ++ # language codes i.e. 'zh-hant' and 'zh'. ++ possible_lang_codes = [lang_code] ++ try: ++ possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"]) ++ except KeyError: ++ pass ++ i = None ++ while (i := lang_code.rfind("-", 0, i)) > -1: ++ possible_lang_codes.append(lang_code[:i]) ++ generic_lang_code = possible_lang_codes[-1] ++ supported_lang_codes = get_languages() ++ ++ for code in possible_lang_codes: ++ if code.lower() in supported_lang_codes and check_for_language(code): ++ return code ++ if not strict: ++ # if fr-fr is not supported, try fr-ca. ++ for supported_code in supported_lang_codes: ++ if supported_code.startswith(generic_lang_code + "-"): ++ return supported_code ++ raise LookupError(lang_code) ++ ++ + def get_supported_language_variant(lang_code, strict=False): + """ + Return the language code that's listed in supported languages, possibly +@@ -510,44 +535,17 @@ def get_supported_language_variant(lang_code, strict=False): + + The language code is truncated to a maximum length to avoid potential + denial of service attacks. +- +- lru_cache should have a maxsize to prevent from memory exhaustion attacks, +- as the provided language codes are taken from the HTTP request. See also +- . + """ + if lang_code: +- # Truncate the language code to a maximum length to avoid potential +- # denial of service attacks. +- if len(lang_code) > LANGUAGE_CODE_MAX_LENGTH: +- if ( +- not strict +- and (index := lang_code.rfind("-", 0, LANGUAGE_CODE_MAX_LENGTH)) > 0 +- ): +- # There is a generic variant under the maximum length accepted length. +- lang_code = lang_code[:index] +- else: +- raise LookupError(lang_code) +- # If 'zh-hant-tw' is not supported, try special fallback or subsequent +- # language codes i.e. 'zh-hant' and 'zh'. +- possible_lang_codes = [lang_code] +- try: +- possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"]) +- except KeyError: +- pass +- i = None +- while (i := lang_code.rfind("-", 0, i)) > -1: +- possible_lang_codes.append(lang_code[:i]) +- generic_lang_code = possible_lang_codes[-1] +- supported_lang_codes = get_languages() +- +- for code in possible_lang_codes: +- if code.lower() in supported_lang_codes and check_for_language(code): +- return code +- if not strict: +- # if fr-fr is not supported, try fr-ca. +- for supported_code in supported_lang_codes: +- if supported_code.startswith(generic_lang_code + "-"): +- return supported_code ++ if len(lang_code) <= LANGUAGE_CODE_MAX_LENGTH: ++ return _get_supported_language_variant(lang_code, strict=strict) ++ if ( ++ not strict ++ and (index := lang_code.rfind("-", 0, LANGUAGE_CODE_MAX_LENGTH)) > 0 ++ ): ++ # There is a generic variant under the maximum accepted length. ++ lang_code = lang_code[:index] ++ return _get_supported_language_variant(lang_code, strict=strict) + raise LookupError(lang_code) + + +diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py +index e0b2106d4f7a..21ab852594ca 100644 +--- a/tests/i18n/tests.py ++++ b/tests/i18n/tests.py +@@ -1902,6 +1902,45 @@ class MiscTests(SimpleTestCase): + g("en-" * 167, strict=True) + self.assertEqual(g("en-" * 30000), "en") # catastrophic test + ++ def test_get_supported_language_variant_strict_long_lang_code_not_cached(self): ++ g = trans_real.get_supported_language_variant ++ g_cached = trans_real._get_supported_language_variant ++ self.addCleanup(g_cached.cache_clear) ++ ++ for lang_code in ( ++ "e" * 501, ++ "en-" * 167, # Length 501 which is LANGUAGE_CODE_MAX_LENGTH + 1. ++ "en-" * 30000, ++ ): ++ g_cached.cache_clear() ++ with self.subTest(length=len(lang_code)): ++ with self.assertRaises(LookupError): ++ g(lang_code, strict=True) ++ ++ cache_info = g_cached.cache_info() ++ self.assertEqual(cache_info.currsize, 0) ++ self.assertEqual(cache_info.misses, 0) ++ ++ def test_get_supported_language_variant_truncated_cache_key(self): ++ g = trans_real.get_supported_language_variant ++ g_cached = trans_real._get_supported_language_variant ++ self.addCleanup(g_cached.cache_clear) ++ g_cached.cache_clear() ++ ++ long_code = "en-" * 167 # Length 501. ++ truncated_code = "en-" * 165 + "en" # Length 497. ++ catastrophic_long_code = "en-" * 3000 ++ ++ for hits, code in enumerate( ++ [long_code, truncated_code, catastrophic_long_code] ++ ): ++ with self.subTest(code_length=len(code)): ++ self.assertEqual(g(code), "en") ++ cache_info = g_cached.cache_info() ++ self.assertEqual(cache_info.currsize, 1) ++ self.assertEqual(cache_info.hits, hits) ++ self.assertEqual(cache_info.misses, 1) ++ + def test_get_supported_language_variant_null(self): + g = trans_null.get_supported_language_variant + self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE) diff -Nru python-django-4.2.28/debian/patches/0010-CVE-2026-84429.patch python-django-4.2.30/debian/patches/0010-CVE-2026-84429.patch --- python-django-4.2.28/debian/patches/0010-CVE-2026-84429.patch 1970-01-01 00:00:00.000000000 +0000 +++ python-django-4.2.30/debian/patches/0010-CVE-2026-84429.patch 2026-11-05 17:27:41.000000000 +0000 @@ -0,0 +1,192 @@ +From: Natalia <124304+nessita@users.noreply.github.com> +Date: Tue, 1 Sep 2026 15:17:57 -0300 +Subject: [PATCH] [5.2.x] Fixed CVE-2026-84429 -- Simplified + parse_header_parameters by leveraging stdlib's Message. + +The `parse_header_parameters` function historically used Python's `cgi` +module (now deprecated). In 34e2148fc725e7200050f74130d7523e3cd8507a, +the logic was inlined to work around this deprecation (#33173). Later, +in d4d5427571b4bf3a21c902276c2a00215c2a37cc, the header parsing logic +was further cleaned up to align with multipartparser.py (#33697). It was +then replaced with Python's email.message.Message API in #35440, and +reverted in #36520 over a performance concern on common headers. + +But recently, a security report showed that `parse_header_parameters()` +parsed header values in time quadratic in the number of separators +inside a quoted parameter. Because the per-call length limit does not +bound the combined size of a repeated header, an unauthenticated request +could consume excessive CPU, for example via the `Accept` header, which +is parsed by `HttpRequest.accepted_types`. + +Therefore, this change restores the `email.message.Message` approach, +which parses in linear time, while keeping the fast path for headers +without parameters and continuing to reject invalid RFC 2231 encodings +(#36991). + +Thanks to Raphael Gaschignard for testing, and to Jake Howard, +Adam Johnson, and Shai Berger for reviews. Thanks to Jisung Chae and +Peter Thomassen for the security report. + +Co-authored-by: Khudyakov Artem +Co-authored-by: Ben Cail + +Backport of 7ff7fcc0508864a4bc39693128ace38b1e95a890 from main. + +Origin: upstream, https://github.com/django/django/commit/6ecd66e09a383be004a78a3a738ea9727ff07b0e.patch +--- + django/utils/http.py | 66 +++++++++++++++++++----------------------- + tests/utils_tests/test_http.py | 29 +++++++++++++++++-- + 2 files changed, 57 insertions(+), 38 deletions(-) + +diff --git a/django/utils/http.py b/django/utils/http.py +index 0804937f38cb..76f27106cfc5 100644 +--- a/django/utils/http.py ++++ b/django/utils/http.py +@@ -1,10 +1,12 @@ ++import codecs + import base64 + import datetime + import ipaddress + import re + import unicodedata + from binascii import Error as BinasciiError +-from email.utils import formatdate ++from email.message import Message ++from email.utils import collapse_rfc2231_value, formatdate + from urllib.parse import ( + ParseResult, + SplitResult, +@@ -13,7 +15,6 @@ from urllib.parse import ( + _splitparams, + quote, + scheme_chars, +- unquote, + ) + from urllib.parse import urlencode as original_urlencode + from urllib.parse import uses_params +@@ -406,46 +407,39 @@ def escape_leading_slashes(url): + return url + + +-def _parseparam(s): +- while s[:1] == ";": +- s = s[1:] +- end = s.find(";") +- while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: +- end = s.find(";", end + 1) +- if end < 0: +- end = len(s) +- f = s[:end] +- yield f.strip() +- s = s[end:] +- +- + def parse_header_parameters(line): + """ + Parse a Content-type like header. + Return the main content-type and a dictionary of options. + """ +- parts = _parseparam(";" + line) +- key = parts.__next__().lower() ++ if not line: ++ return "", {} ++ ++ # Fast path for no params. ++ if ";" not in line: ++ return line.strip().lower(), {} ++ ++ m = Message() ++ m["content-type"] = line ++ params = m.get_params() ++ + pdict = {} +- for p in parts: +- i = p.find("=") +- if i >= 0: +- has_encoding = False +- name = p[:i].strip().lower() +- if name.endswith("*"): +- # Lang/encoding embedded in the value (like "filename*=UTF-8''file.ext") +- # https://tools.ietf.org/html/rfc2231#section-4 +- name = name[:-1] +- if p.count("'") == 2: +- has_encoding = True +- value = p[i + 1 :].strip() +- if len(value) >= 2 and value[0] == value[-1] == '"': +- value = value[1:-1] +- value = value.replace("\\\\", "\\").replace('\\"', '"') +- if has_encoding: +- encoding, lang, value = value.split("'") +- value = unquote(value, encoding=encoding) +- pdict[name] = value ++ key = params.pop(0)[0].lower() ++ for name, value in params: ++ if not name: ++ continue ++ if isinstance(value, tuple): ++ # An RFC 2231 encoded value: (charset, language, value). Reject an ++ # unknown charset rather than let collapse_rfc2231_value() fallback ++ # to us-ascii and silently accept it. ++ if encoding := value[0]: ++ try: ++ codecs.lookup(encoding) ++ except LookupError: ++ msg = f"Invalid encoding {encoding!r} for RFC 2231 param." ++ raise ValueError(msg) ++ value = collapse_rfc2231_value(value) ++ pdict[name] = value + return key, pdict + + +diff --git a/tests/utils_tests/test_http.py b/tests/utils_tests/test_http.py +index 265f74346c9f..f72d48ed7894 100644 +--- a/tests/utils_tests/test_http.py ++++ b/tests/utils_tests/test_http.py +@@ -539,13 +539,14 @@ class ParseHeaderParameterTests(unittest.TestCase): + def test_rfc2231_wrong_title(self): + """ + Test wrongly formatted RFC 2231 headers (missing double single quotes). +- Parsing should not crash (#24209). ++ Parsing should not crash (#24209), but stdlib email still decodes the ++ value (#35440). + """ + test_data = ( + ( + "Content-Type: application/x-stuff; " + "title*='This%20is%20%2A%2A%2Afun%2A%2A%2A", +- "'This%20is%20%2A%2A%2Afun%2A%2A%2A", ++ "'This is ***fun***", + ), + ("Content-Type: application/x-stuff; title*='foo.html", "'foo.html"), + ("Content-Type: application/x-stuff; title*=bar.html", "bar.html"), +@@ -554,6 +555,30 @@ class ParseHeaderParameterTests(unittest.TestCase): + parsed = parse_header_parameters(raw_line) + self.assertEqual(parsed[1]["title"], expected_title) + ++ def test_rfc2231_invalid_encoding(self): ++ test_data = [ ++ # Invalid encoding name with percent-encoded value ++ "text/plain; charset*=BOGUS''%20", ++ # Another invalid encoding with different value ++ "text/plain; filename*=INVALID''%s%s%s", ++ # Invalid encoding with multi-line encoded content ++ "text/plain; title*=NOTACODEC''%E2%80%A6", ++ ] ++ msg = "Invalid encoding" ++ for header in test_data: ++ with self.subTest(raw_line=header), self.assertRaisesRegex(ValueError, msg): ++ parse_header_parameters(header) ++ ++ def test_many_separators_in_quoted_value(self): ++ # A quoted value containing many semicolons is a single parameter, and ++ # trailing unquoted parameters are still parsed. ++ value = ";" * 5000 ++ header = 'attachment; filename="%s"; size=1' % value ++ self.assertEqual( ++ parse_header_parameters(header), ++ ("attachment", {"filename": value, "size": "1"}), ++ ) ++ + + class ContentDispositionHeaderTests(unittest.TestCase): + def test_basic(self): diff -Nru python-django-4.2.28/debian/patches/0011-CVE-2026-108147.patch python-django-4.2.30/debian/patches/0011-CVE-2026-108147.patch --- python-django-4.2.28/debian/patches/0011-CVE-2026-108147.patch 1970-01-01 00:00:00.000000000 +0000 +++ python-django-4.2.30/debian/patches/0011-CVE-2026-108147.patch 2026-11-05 17:27:41.000000000 +0000 @@ -0,0 +1,232 @@ +From: Natalia <124304+nessita@users.noreply.github.com> +Date: Thu, 8 Oct 2026 22:22:41 -0300 +Subject: [PATCH] [5.2.x] Fixed CVE-2026-108147 -- Bounded memory use of + base64 file uploads in MultiPartParser. + +The mitigation for CVE-2026-33033 aligned base64 data to a multiple of +4 by reading whole chunks. As the chunk size is itself a multiple of 4, +those reads never restored the alignment, so a misaligned upload was +read and decoded in full before reaching upload handlers. + +Trailing undecoded bytes are now carried over to the next chunk, so no +extra reads are needed and memory use stays bounded by the chunk size. + +Thanks Ignacy Kujawa for the report, and Jake Howard for the review. + +Backport of 5d95d9236fa4ededfb1931c60a65432385ece85f from main. + +Origin: upstream, https://github.com/django/django/commit/4bd1f59a80adafddbd47527c66d92d6a224244d8.patch +--- + django/http/multipartparser.py | 34 +++++++------ + tests/file_uploads/tests.py | 2 +- + tests/requests_tests/tests.py | 110 +++++++++++++++++++++++++++++++++++------ + 3 files changed, 116 insertions(+), 30 deletions(-) + +diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py +index 856ab680594e..cf24111c570d 100644 +--- a/django/http/multipartparser.py ++++ b/django/http/multipartparser.py +@@ -296,27 +296,27 @@ class MultiPartParser: + except StopFutureHandlers: + break + ++ base64_remainder = b"" + for chunk in field_stream: + if transfer_encoding == "base64": + # We only special-case base64 transfer encoding + # We should always decode base64 chunks by +- # multiple of 4, ignoring whitespace. +- +- stripped_parts = [b"".join(chunk.split())] +- stripped_length = len(stripped_parts[0]) +- +- while stripped_length % 4 != 0: +- over_chunk = field_stream.read(self._chunk_size) +- if not over_chunk: +- break +- over_stripped = b"".join(over_chunk.split()) +- stripped_parts.append(over_stripped) +- stripped_length += len(over_stripped) +- +- stripped_chunk = b"".join(stripped_parts) ++ # multiple of 4, ignoring whitespace. Carry the ++ # trailing 1-3 bytes over to the next chunk ++ # rather than reading ahead, so that memory use ++ # stays bounded by the chunk size. ++ stripped_chunk = base64_remainder + b"".join( ++ chunk.split() ++ ) ++ aligned_length = len(stripped_chunk) // 4 * 4 ++ base64_remainder = stripped_chunk[aligned_length:] ++ if not aligned_length: ++ continue + + try: +- chunk = base64.b64decode(stripped_chunk) ++ chunk = base64.b64decode( ++ stripped_chunk[:aligned_length] ++ ) + except Exception as exc: + # Since this is only a chunk, any error is + # an unfixable error. +@@ -333,6 +333,10 @@ class MultiPartParser: + # the handler is None. + break + ++ if base64_remainder: ++ # Leftover bytes mean the base64 data is truncated. ++ raise MultiPartParserError("Could not decode base64 data.") ++ + except SkipFile: + self._close_files() + # Just use up the rest of this file... +diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py +index 24c703a30934..f7ccc5908336 100644 +--- a/tests/file_uploads/tests.py ++++ b/tests/file_uploads/tests.py +@@ -179,7 +179,7 @@ class FileUploadTests(TestCase): + "wsgi.input": payload, + } + response = self.client.request(**r) +- self.assertEqual(response.json()["file"], "") ++ self.assertEqual(response.status_code, 400) + + def test_unicode_file_name(self): + with sys_tempfile.TemporaryDirectory() as temp_dir: +diff --git a/tests/requests_tests/tests.py b/tests/requests_tests/tests.py +index 6305c8827365..4f4690709272 100644 +--- a/tests/requests_tests/tests.py ++++ b/tests/requests_tests/tests.py +@@ -1,3 +1,4 @@ ++import base64 + import copy + from io import BytesIO + from itertools import chain +@@ -5,6 +6,7 @@ from unittest import mock + from urllib.parse import urlencode + + from django.core.exceptions import DisallowedHost ++from django.core.files.uploadhandler import FileUploadHandler + from django.core.handlers.wsgi import LimitedStream, WSGIRequest + from django.http import ( + HttpHeaders, +@@ -627,25 +629,105 @@ class RequestsTests(SimpleTestCase): + self.assertEqual(len(files), 1) + self.assertEqual(files["file"].read(), b"\x00\x00\x00") + +- # The alignment loop must read in `chunk-sized` units rather than one +- # byte at a time, otherwise each whitespace byte triggers a separate +- # read() call with a costly internal unget() cycle. +- # Parsing this payload should issue exactly 8 LazyStream.read() calls: ++ # The base64 alignment must not issue extra reads, otherwise each ++ # whitespace byte could trigger a separate read() call with a costly ++ # internal unget() cycle. Bytes needed to complete the 4-byte base64 ++ # group that spans the chunk boundary are carried over to the next ++ # chunk instead. Parsing this payload should issue exactly 7 ++ # LazyStream.read() calls: + # 1. main_stream.read(1) -- BoundaryIter.__init__ probe, preamble + # 2. sub_stream.read(1024) -- parse_boundary_stream, preamble headers + # 3. main_stream.read(1) -- BoundaryIter.__init__ probe, file field + # 4. field_stream.read(1024) -- parse_boundary_stream, file headers +- # 5. field_stream.read(65536)-- base64 alignment loop: one chunk-sized +- # read to find the non-whitespace bytes +- # needed to complete the 4-byte base64 +- # group that spans the chunk boundary +- # 6. main_stream.read(1) -- BoundaryIter.__init__ probe, epilogue +- # 7. sub_stream.read(1024) -- parse_boundary_stream, epilogue headers +- # 8. main_stream.read(1) -- BoundaryIter.__init__ probe, exhausted ++ # 5. main_stream.read(1) -- BoundaryIter.__init__ probe, epilogue ++ # 6. sub_stream.read(1024) -- parse_boundary_stream, epilogue headers ++ # 7. main_stream.read(1) -- BoundaryIter.__init__ probe, exhausted + # stream; returns b"" and stops iteration +- # A byte-at-a-time implementation of read() in step 5 would do instead +- # one read(1) per whitespace byte past the chunk boundary (4488 calls). +- self.assertEqual(reads, [1, 1024, 1, 1024, 65536, 1, 1024, 1]) ++ # A byte-at-a-time alignment would instead do one read(1) per ++ # whitespace byte past the chunk boundary (4488 calls). ++ self.assertEqual(reads, [1, 1024, 1, 1024, 1, 1024, 1]) ++ ++ def test_multipart_file_upload_base64_streamed_in_chunks(self): ++ # Decoded data is passed to upload handlers in bounded chunks whatever ++ # the alignment of the base64 data relative to the chunk boundaries. ++ # The filename length shifts that alignment. ++ content = bytes(range(256)) * 1024 ++ encoded = base64.b64encode(content) ++ chunk_size = 2**16 ++ ++ class RecordingUploadHandler(FileUploadHandler): ++ def __init__(self, *args, **kwargs): ++ super().__init__(*args, **kwargs) ++ self.chunks = [] ++ ++ def receive_data_chunk(self, raw_data, start): ++ self.chunks.append(raw_data) ++ ++ def file_complete(self, file_size): ++ return None ++ ++ for filename in ["a", "ab", "abc", "abcd"]: ++ with self.subTest(filename=filename): ++ payload = FakePayload( ++ "\r\n".join( ++ [ ++ f"--{BOUNDARY}", ++ 'Content-Disposition: form-data; name="file"; ' ++ f'filename="{filename}"', ++ "Content-Type: application/octet-stream", ++ "Content-Transfer-Encoding: base64", ++ "", ++ "", ++ ] ++ ) ++ ) ++ payload.write(encoded + b"\r\n") ++ payload.write(f"--{BOUNDARY}--\r\n") ++ request = WSGIRequest( ++ { ++ "REQUEST_METHOD": "POST", ++ "CONTENT_TYPE": MULTIPART_CONTENT, ++ "CONTENT_LENGTH": len(payload), ++ "wsgi.input": payload, ++ } ++ ) ++ handler = RecordingUploadHandler() ++ request.upload_handlers = [handler] ++ request.FILES # evaluate ++ ++ self.assertEqual(b"".join(handler.chunks), content) ++ self.assertGreater(len(handler.chunks), 1) ++ self.assertLessEqual(max(map(len, handler.chunks)), chunk_size) ++ ++ def test_multipart_file_upload_base64_truncated(self): ++ for data in ["A", "AA", "AAA", "AAAAA"]: ++ with self.subTest(data=data): ++ payload = FakePayload( ++ "\r\n".join( ++ [ ++ f"--{BOUNDARY}", ++ 'Content-Disposition: form-data; name="file"; ' ++ 'filename="test.txt"', ++ "Content-Type: application/octet-stream", ++ "Content-Transfer-Encoding: base64", ++ "", ++ data, ++ f"--{BOUNDARY}--", ++ "", ++ ] ++ ) ++ ) ++ request = WSGIRequest( ++ { ++ "REQUEST_METHOD": "POST", ++ "CONTENT_TYPE": MULTIPART_CONTENT, ++ "CONTENT_LENGTH": len(payload), ++ "wsgi.input": payload, ++ } ++ ) ++ msg = "Could not decode base64 data." ++ with self.assertRaisesMessage(MultiPartParserError, msg): ++ request.FILES + + def test_POST_after_body_read_and_stream_read_multipart(self): + """ diff -Nru python-django-4.2.28/debian/patches/0012-CVE-2026-113593.patch python-django-4.2.30/debian/patches/0012-CVE-2026-113593.patch --- python-django-4.2.28/debian/patches/0012-CVE-2026-113593.patch 1970-01-01 00:00:00.000000000 +0000 +++ python-django-4.2.30/debian/patches/0012-CVE-2026-113593.patch 2026-11-05 17:27:41.000000000 +0000 @@ -0,0 +1,71 @@ +From: Andrew James Gonzalez +Date: Wed, 21 Oct 2026 10:00:15 +0200 +Subject: [PATCH] [5.2.x] Fixed CVE-2026-113593 -- Differentiated empty and + missing headers in response cache. + +When learning the cache key for a response, a missing header must be +cached differently to an empty one, as per RFC 9111. + +Thanks to Andrew Gonzalez for the report. + +Co-authored-by: Jake Howard + +Backport of c0b7e5e4e4546e8ddc58262f1945938bb9d9ac2d from main. + +Origin: upstream, https://github.com/django/django/commit/9007fecd3633cfd90b093ebe106af564347c8aee.patch +--- + django/utils/cache.py | 10 ++++++++-- + tests/cache/tests.py | 19 ++++++++++++++++++- + 2 files changed, 26 insertions(+), 3 deletions(-) + +diff --git a/django/utils/cache.py b/django/utils/cache.py +index d9f96d8f7f56..d98b4c696676 100644 +--- a/django/utils/cache.py ++++ b/django/utils/cache.py +@@ -351,8 +351,14 @@ def _generate_cache_key(request, method, headerlist, key_prefix): + ctx = md5(usedforsecurity=False) + for header in headerlist: + value = request.META.get(header) +- if value is not None: +- ctx.update(value.encode()) ++ if value is None: ++ # An absent field must not share a cache key with a field that is ++ # present but empty (RFC 9111, Section 4.1). Emit a marker that ++ # cannot collide with any netstring. ++ ctx.update(b"-,") ++ continue ++ data = value.encode() ++ ctx.update(data) + url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False) + cache_key = "views.decorators.cache.cache_page.%s.%s.%s.%s" % ( + key_prefix, +diff --git a/tests/cache/tests.py b/tests/cache/tests.py +index fcce9579d48c..dfdf1ff48c81 100644 +--- a/tests/cache/tests.py ++++ b/tests/cache/tests.py +@@ -2109,7 +2109,24 @@ class CacheUtils(SimpleTestCase): + self.assertEqual( + get_cache_key(request), + "views.decorators.cache.cache_page.settingsprefix.GET." +- "18a03f9c9649f7d684af5db3524f5c99.d41d8cd98f00b204e9800998ecf8427e", ++ "18a03f9c9649f7d684af5db3524f5c99.4792b9bac48c3f0441b0d9b0d7af8f2c", ++ ) ++ ++ def test_cache_key_blank_header(self): ++ """ ++ An absent field must be distinguished from a present-but-empty field ++ (RFC 9111, Section 4.1). ++ """ ++ request_no_headers = self.factory.head(self.path) ++ request_empty_headers = self.factory.head(self.path, headers={"Pony": ""}) ++ response = HttpResponse() ++ response.headers["Vary"] = "Pony" ++ key_no_headers = learn_cache_key(request_no_headers, response) ++ key_empty_headers = learn_cache_key(request_empty_headers, response) ++ self.assertNotEqual(key_no_headers, key_empty_headers) ++ self.assertNotEqual( ++ get_cache_key(request_no_headers), ++ get_cache_key(request_empty_headers), + ) + + def test_patch_cache_control(self): diff -Nru python-django-4.2.28/debian/patches/0013-Adjust-the-scaling-factor-in-the-test-for-CVE-2025-6.patch python-django-4.2.30/debian/patches/0013-Adjust-the-scaling-factor-in-the-test-for-CVE-2025-6.patch --- python-django-4.2.28/debian/patches/0013-Adjust-the-scaling-factor-in-the-test-for-CVE-2025-6.patch 1970-01-01 00:00:00.000000000 +0000 +++ python-django-4.2.30/debian/patches/0013-Adjust-the-scaling-factor-in-the-test-for-CVE-2025-6.patch 2026-11-05 17:27:41.000000000 +0000 @@ -0,0 +1,22 @@ +From: Chris Lamb +Date: Thu, 5 Nov 2026 09:11:21 -0800 +Subject: Adjust the scaling factor in the test for CVE-2025-64460 as it + causes flakiness on loaded machines. (Closes: #1126323) + +--- + tests/serializers/test_xml.py | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/tests/serializers/test_xml.py b/tests/serializers/test_xml.py +index 03462cfed54a..821d88b7f51b 100644 +--- a/tests/serializers/test_xml.py ++++ b/tests/serializers/test_xml.py +@@ -141,7 +141,7 @@ class XmlSerializerTestCase(SerializersTestBase, TestCase): + [(50, 2000), (100, 4000), (200, 8000), (400, 16000), (800, 32000)], + 2, + ) +- assertFactor("constant depth, varying length", [(100, 1), (100, 1000)], 2) ++ assertFactor("constant depth, varying length", [(100, 1), (100, 1000)], 4) + + + class XmlSerializerTransactionTestCase( diff -Nru python-django-4.2.28/debian/patches/series python-django-4.2.30/debian/patches/series --- python-django-4.2.28/debian/patches/series 2026-05-26 21:35:49.000000000 +0000 +++ python-django-4.2.30/debian/patches/series 2026-11-05 17:27:41.000000000 +0000 @@ -4,3 +4,10 @@ 0004-Set-the-default-shebang-to-new-projects-to-use-Pytho.patch py313-test-help-default-options-with-custom-arguments.patch 0006-Workaround-changes-in-CVE-2025-6069.patch +0007-CVE-2026-15337.patch +0008-CVE-2026-15920.patch +0009-CVE-2026-77050.patch +0010-CVE-2026-84429.patch +0011-CVE-2026-108147.patch +0012-CVE-2026-113593.patch +0013-Adjust-the-scaling-factor-in-the-test-for-CVE-2025-6.patch diff -Nru python-django-4.2.28/django/__init__.py python-django-4.2.30/django/__init__.py --- python-django-4.2.28/django/__init__.py 2026-02-03 13:31:14.000000000 +0000 +++ python-django-4.2.30/django/__init__.py 2026-04-07 11:46:10.000000000 +0000 @@ -1,6 +1,6 @@ from django.utils.version import get_version -VERSION = (4, 2, 28, "final", 0) +VERSION = (4, 2, 30, "final", 0) __version__ = get_version(VERSION) diff -Nru python-django-4.2.28/django/contrib/admin/options.py python-django-4.2.30/django/contrib/admin/options.py --- python-django-4.2.28/django/contrib/admin/options.py 2026-02-03 13:30:55.000000000 +0000 +++ python-django-4.2.30/django/contrib/admin/options.py 2026-04-07 11:42:15.000000000 +0000 @@ -30,6 +30,7 @@ from django.contrib.admin.widgets import AutocompleteSelect, AutocompleteSelectMultiple from django.contrib.auth import get_permission_codename from django.core.exceptions import ( + BadRequest, FieldDoesNotExist, FieldError, PermissionDenied, @@ -2016,6 +2017,8 @@ for form in formset.forms: if form.has_changed(): obj = self.save_form(request, form, change=True) + if obj._state.adding: + raise BadRequest("list_editable does not allow adding.") self.save_model(request, obj, form, change=True) self.save_related(request, form, formsets=[], change=True) change_msg = self.construct_change_message( diff -Nru python-django-4.2.28/django/contrib/contenttypes/admin.py python-django-4.2.30/django/contrib/contenttypes/admin.py --- python-django-4.2.28/django/contrib/contenttypes/admin.py 2026-02-03 13:12:03.000000000 +0000 +++ python-django-4.2.30/django/contrib/contenttypes/admin.py 2026-04-07 11:41:42.000000000 +0000 @@ -127,6 +127,21 @@ **kwargs, } + base_model_form = defaults["form"] + can_change = self.has_change_permission(request, obj) if request else True + can_add = self.has_add_permission(request, obj) if request else True + + class PermissionProtectedModelForm(base_model_form): + def has_changed(self): + # Protect against unauthorized edits. + if not can_change and not self.instance._state.adding: + return False + if not can_add and self.instance._state.adding: + return False + return super().has_changed() + + defaults["form"] = PermissionProtectedModelForm + if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): diff -Nru python-django-4.2.28/django/core/cache/backends/filebased.py python-django-4.2.30/django/core/cache/backends/filebased.py --- python-django-4.2.28/django/core/cache/backends/filebased.py 2026-02-03 13:30:55.000000000 +0000 +++ python-django-4.2.30/django/core/cache/backends/filebased.py 2026-04-07 11:39:39.000000000 +0000 @@ -10,6 +10,7 @@ from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.core.files import locks from django.core.files.move import file_move_safe +from django.utils._os import safe_makedirs from django.utils.crypto import md5 @@ -114,13 +115,10 @@ self._delete(fname) def _createdir(self): - # Set the umask because os.makedirs() doesn't apply the "mode" argument + # Workaround because os.makedirs() doesn't apply the "mode" argument # to intermediate-level directories. - old_umask = os.umask(0o077) - try: - os.makedirs(self._dir, 0o700, exist_ok=True) - finally: - os.umask(old_umask) + # https://github.com/python/cpython/issues/86533 + safe_makedirs(self._dir, mode=0o700, exist_ok=True) def _key_to_file(self, key, version=None): """ diff -Nru python-django-4.2.28/django/core/files/storage/filesystem.py python-django-4.2.30/django/core/files/storage/filesystem.py --- python-django-4.2.28/django/core/files/storage/filesystem.py 2026-02-03 13:30:55.000000000 +0000 +++ python-django-4.2.30/django/core/files/storage/filesystem.py 2026-04-07 11:39:39.000000000 +0000 @@ -6,7 +6,7 @@ from django.core.files import File, locks from django.core.files.move import file_move_safe from django.core.signals import setting_changed -from django.utils._os import safe_join +from django.utils._os import safe_join, safe_makedirs from django.utils.deconstruct import deconstructible from django.utils.encoding import filepath_to_uri from django.utils.functional import cached_property @@ -74,15 +74,10 @@ directory = os.path.dirname(full_path) try: if self.directory_permissions_mode is not None: - # Set the umask because os.makedirs() doesn't apply the "mode" + # Workaround because os.makedirs() doesn't apply the "mode" # argument to intermediate-level directories. - old_umask = os.umask(0o777 & ~self.directory_permissions_mode) - try: - os.makedirs( - directory, self.directory_permissions_mode, exist_ok=True - ) - finally: - os.umask(old_umask) + # https://github.com/python/cpython/issues/86533 + safe_makedirs(directory, self.directory_permissions_mode, exist_ok=True) else: os.makedirs(directory, exist_ok=True) except FileExistsError: diff -Nru python-django-4.2.28/django/core/handlers/asgi.py python-django-4.2.30/django/core/handlers/asgi.py --- python-django-4.2.28/django/core/handlers/asgi.py 2026-02-03 13:30:55.000000000 +0000 +++ python-django-4.2.30/django/core/handlers/asgi.py 2026-04-07 11:41:10.000000000 +0000 @@ -85,6 +85,9 @@ _headers = defaultdict(list) for name, value in self.scope.get("headers", []): name = name.decode("latin1") + # Prevent spoofing via ambiguity between underscores and hyphens. + if "_" in name: + continue if name == "content-length": corrected_name = "CONTENT_LENGTH" elif name == "content-type": diff -Nru python-django-4.2.28/django/forms/fields.py python-django-4.2.30/django/forms/fields.py --- python-django-4.2.28/django/forms/fields.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/django/forms/fields.py 2026-04-07 11:39:39.000000000 +0000 @@ -12,7 +12,6 @@ import uuid from decimal import Decimal, DecimalException from io import BytesIO -from urllib.parse import urlsplit, urlunsplit from django.core import validators from django.core.exceptions import ValidationError @@ -757,33 +756,24 @@ super().__init__(strip=True, **kwargs) def to_python(self, value): - def split_url(url): - """ - Return a list of url parts via urlparse.urlsplit(), or raise - ValidationError for some malformed URLs. - """ - try: - return list(urlsplit(url)) - except ValueError: - # urlparse.urlsplit can raise a ValueError with some - # misformatted URLs. - raise ValidationError(self.error_messages["invalid"], code="invalid") - value = super().to_python(value) if value: - url_fields = split_url(value) - if not url_fields[0]: - # If no URL scheme given, assume http:// - url_fields[0] = "http" - if not url_fields[1]: - # Assume that if no domain is provided, that the path segment - # contains the domain. - url_fields[1] = url_fields[2] - url_fields[2] = "" - # Rebuild the url_fields list, since the domain segment may now - # contain the path too. - url_fields = split_url(urlunsplit(url_fields)) - value = urlunsplit(url_fields) + # Detect scheme via partition to avoid calling urlsplit() on + # potentially large or slow-to-normalize inputs. + scheme, sep, _ = value.partition(":") + if ( + not sep + or not scheme + or not scheme[0].isascii() + or not scheme[0].isalpha() + or "/" in scheme + ): + # No valid scheme found -- prepend the assumed scheme. Handle + # scheme-relative URLs ("//example.com") separately. + if value.startswith("//"): + value = "http:" + value + else: + value = "http://" + value return value diff -Nru python-django-4.2.28/django/http/multipartparser.py python-django-4.2.30/django/http/multipartparser.py --- python-django-4.2.28/django/http/multipartparser.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/django/http/multipartparser.py 2026-04-07 11:42:34.000000000 +0000 @@ -302,15 +302,18 @@ # We should always decode base64 chunks by # multiple of 4, ignoring whitespace. - stripped_chunk = b"".join(chunk.split()) + stripped_parts = [b"".join(chunk.split())] + stripped_length = len(stripped_parts[0]) - remaining = len(stripped_chunk) % 4 - while remaining != 0: - over_chunk = field_stream.read(4 - remaining) + while stripped_length % 4 != 0: + over_chunk = field_stream.read(self._chunk_size) if not over_chunk: break - stripped_chunk += b"".join(over_chunk.split()) - remaining = len(stripped_chunk) % 4 + over_stripped = b"".join(over_chunk.split()) + stripped_parts.append(over_stripped) + stripped_length += len(over_stripped) + + stripped_chunk = b"".join(stripped_parts) try: chunk = base64.b64decode(stripped_chunk) diff -Nru python-django-4.2.28/django/http/request.py python-django-4.2.30/django/http/request.py --- python-django-4.2.28/django/http/request.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/django/http/request.py 2026-04-07 11:43:00.000000000 +0000 @@ -1,5 +1,6 @@ import codecs import copy +import os from io import BytesIO from itertools import chain from urllib.parse import parse_qsl, quote, urlencode, urljoin, urlsplit @@ -328,25 +329,49 @@ "You cannot access body after reading from request's data stream" ) - # Limit the maximum request data size that will be handled in-memory. - if ( - settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None - and int(self.META.get("CONTENT_LENGTH") or 0) - > settings.DATA_UPLOAD_MAX_MEMORY_SIZE - ): - raise RequestDataTooBig( - "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE." - ) + # Limit the maximum request data size that will be handled + # in-memory. Reject early when Content-Length is present and + # already exceeds the limit, avoiding reading the body at all. + self._check_data_too_big(int(self.META.get("CONTENT_LENGTH") or 0)) + + # Content-Length can be absent or understated (e.g. + # `Transfer-Encoding: chunked` on ASGI), so for seekable + # streams (e.g. SpooledTemporaryFile on ASGI), check the actual + # buffered size before reading it all into memory. + if hasattr(self._stream, "seekable") and self._stream.seekable(): + stream_size = self._stream.seek(0, os.SEEK_END) + self._check_data_too_big(stream_size) + self._stream.seek(0) + did_check = True + else: + did_check = False try: - self._body = self.read() + if settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and not did_check: + # Read one byte past the limit to detect an oversize body + # without loading it all into memory first. + self._body = self.read(settings.DATA_UPLOAD_MAX_MEMORY_SIZE + 1) + else: + self._body = self.read() except OSError as e: raise UnreadablePostError(*e.args) from e finally: self._stream.close() self._stream = BytesIO(self._body) + if not did_check: + stream_size = self._stream.seek(0, os.SEEK_END) + self._check_data_too_big(stream_size) + self._stream.seek(0) return self._body + def _check_data_too_big(self, length): + if ( + settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None + and length > settings.DATA_UPLOAD_MAX_MEMORY_SIZE + ): + msg = "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE." + raise RequestDataTooBig(msg) + def _mark_post_parse_error(self): self._post = QueryDict() self._files = MultiValueDict() diff -Nru python-django-4.2.28/django/test/client.py python-django-4.2.30/django/test/client.py --- python-django-4.2.28/django/test/client.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/django/test/client.py 2026-04-07 11:41:10.000000000 +0000 @@ -705,7 +705,10 @@ if headers: extra.update(HttpHeaders.to_asgi_names(headers)) s["headers"] += [ - (key.lower().encode("ascii"), value.encode("latin1")) + # Avoid breaking test clients that just want to supply normalized + # ASGI names, regardless of the fact that ASGIRequest drops headers + # with underscores (CVE-2026-3902). + (key.lower().replace("_", "-").encode("ascii"), value.encode("latin1")) for key, value in extra.items() ] # If QUERY_STRING is absent or empty, we want to extract it from the diff -Nru python-django-4.2.28/django/utils/_os.py python-django-4.2.30/django/utils/_os.py --- python-django-4.2.28/django/utils/_os.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/django/utils/_os.py 2026-04-07 11:39:39.000000000 +0000 @@ -1,11 +1,67 @@ import os import tempfile -from os.path import abspath, dirname, join, normcase, sep +from os.path import abspath, curdir, dirname, join, normcase, sep from pathlib import Path from django.core.exceptions import SuspiciousFileOperation +# Copied verbatim (minus `os.path` fixes) from: +# https://github.com/python/cpython/pull/23901. +# Python versions >= PY315 may include this fix, so periodic checks are needed +# to remove this vendored copy of `makedirs` once solved upstream. +def makedirs(name, mode=0o777, exist_ok=False, *, parent_mode=None): + """makedirs(name [, mode=0o777][, exist_ok=False][, parent_mode=None]) + + Super-mkdir; create a leaf directory and all intermediate ones. Works like + mkdir, except that any intermediate path segment (not just the rightmost) + will be created if it does not exist. If the target directory already + exists, raise an OSError if exist_ok is False. Otherwise no exception is + raised. If parent_mode is not None, it will be used as the mode for any + newly-created, intermediate-level directories. Otherwise, intermediate + directories are created with the default permissions (respecting umask). + This is recursive. + + """ + head, tail = os.path.split(name) + if not tail: + head, tail = os.path.split(head) + if head and tail and not os.path.exists(head): + try: + if parent_mode is not None: + makedirs( + head, mode=parent_mode, exist_ok=exist_ok, parent_mode=parent_mode + ) + else: + makedirs(head, exist_ok=exist_ok) + except FileExistsError: + # Defeats race condition when another thread created the path + pass + cdir = curdir + if isinstance(tail, bytes): + cdir = bytes(curdir, "ASCII") + if tail == cdir: # xxx/newdir/. exists if xxx/newdir exists + return + try: + os.mkdir(name, mode) + # PY315: The call to `chmod()` is not in the CPython proposed code. + # Apply `chmod()` after `mkdir()` to enforce the exact requested + # permissions, since the kernel masks the mode argument with the + # process umask. This guarantees consistent directory permissions + # without mutating global umask state. + os.chmod(name, mode) + except OSError: + # Cannot rely on checking for EEXIST, since the operating system + # could give priority to other errors like EACCES or EROFS + if not exist_ok or not os.path.isdir(name): + raise + + +def safe_makedirs(name, mode=0o777, exist_ok=False): + """Create directories recursively with explicit `mode` on each level.""" + makedirs(name=name, mode=mode, exist_ok=exist_ok, parent_mode=mode) + + def safe_join(base, *paths): """ Join one or more path components to the base path component intelligently. diff -Nru python-django-4.2.28/docs/releases/4.2.29.txt python-django-4.2.30/docs/releases/4.2.29.txt --- python-django-4.2.28/docs/releases/4.2.29.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-django-4.2.30/docs/releases/4.2.29.txt 2026-04-04 14:19:34.000000000 +0000 @@ -0,0 +1,45 @@ +=========================== +Django 4.2.29 release notes +=========================== + +*March 3, 2026* + +Django 4.2.29 fixes a security issue with severity "moderate" and a security +issue with severity "low" in 4.2.28. + +CVE-2026-25673: Potential denial-of-service vulnerability in ``URLField`` via Unicode normalization on Windows +============================================================================================================== + +The :class:`~django.forms.URLField` form field's ``to_python()`` method used +:func:`~urllib.parse.urlsplit` to determine whether to prepend a URL scheme to +the submitted value. On Windows, ``urlsplit()`` performs +:func:`NFKC normalization `, which can be +disproportionately slow for large inputs containing certain characters. + +``URLField.to_python()`` now uses a simplified scheme detection, avoiding +Unicode normalization entirely and deferring URL validation to the appropriate +layers. As a result, while leading and trailing whitespace is still stripped by +default, characters such as newlines, tabs, and other control characters within +the value are no longer handled by ``URLField.to_python()``. When using the +default :class:`~django.core.validators.URLValidator`, these values will +continue to raise :exc:`~django.core.exceptions.ValidationError` during +validation, but if you rely on custom validators, ensure they do not depend on +the previous behavior of ``URLField.to_python()``. + +This issue has severity "moderate" according to the :ref:`Django security +policy `. + +CVE-2026-25674: Potential incorrect permissions on newly created file system objects +==================================================================================== + +Django's file-system storage and file-based cache backends used the process +``umask`` to control permissions when creating directories. In multi-threaded +environments, one thread's temporary umask change can affect other threads' +file and directory creation, resulting in file system objects being created +with unintended permissions. + +Django now applies the requested permissions via :func:`~os.chmod` after +:func:`~os.mkdir`, removing the dependency on the process-wide umask. + +This issue has severity "low" according to the :ref:`Django security policy +`. diff -Nru python-django-4.2.28/docs/releases/4.2.30.txt python-django-4.2.30/docs/releases/4.2.30.txt --- python-django-4.2.28/docs/releases/4.2.30.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-django-4.2.30/docs/releases/4.2.30.txt 2026-04-07 11:43:00.000000000 +0000 @@ -0,0 +1,69 @@ +=========================== +Django 4.2.30 release notes +=========================== + +*April 7, 2026* + +Django 4.2.30 fixes one security issue with severity "moderate" and four +security issues with severity "low" in 4.2.29. + +CVE-2026-3902: ASGI header spoofing via underscore/hyphen conflation +==================================================================== + +``ASGIRequest`` normalizes header names following WSGI conventions, mapping +hyphens to underscores. As a result, even in configurations where reverse +proxies carefully strip security-sensitive headers named with hyphens, such a +header could be spoofed by supplying a header named with underscores. + +Under WSGI, it is the responsibility of the server or proxy to avoid ambiguous +mappings. (Django's :djadmin:`runserver` was patched in :cve:`2015-0219`.) But +under ASGI, there is not the same uniform expectation, even if many proxies +protect against this under default configuration (including ``nginx`` via +``underscores_in_headers off;``). + +Headers containing underscores are now ignored by ``ASGIRequest``, matching the +behavior of :pypi:`Daphne `, the reference server for ASGI. + +This issue has severity "low" according to the :ref:`Django security policy +`. + +CVE-2026-4277: Privilege abuse in ``GenericInlineModelAdmin`` +============================================================= + +Add permissions on inline model instances were not validated on submission of +forged ``POST`` data in +:class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`. + +This issue has severity "low" according to the :ref:`Django security policy +`. + +CVE-2026-4292: Privilege abuse in ``ModelAdmin.list_editable`` +============================================================== + +Admin changelist forms using +:attr:`~django.contrib.admin.ModelAdmin.list_editable` incorrectly allowed new +instances to be created via forged ``POST`` data. + +This issue has severity "low" according to the :ref:`Django security policy +`. + +CVE-2026-33033: Potential denial-of-service vulnerability in ``MultiPartParser`` via base64-encoded file upload +=============================================================================================================== + +When using ``django.http.multipartparser.MultiPartParser``, multipart uploads +with ``Content-Transfer-Encoding: base64`` that include excessive whitespace +may trigger repeated memory copying, potentially degrading performance. + +This issue has severity "moderate" according to the :ref:`Django security +policy `. + +CVE-2026-33034: Potential denial-of-service vulnerability in ASGI requests via memory upload limit bypass +========================================================================================================= + +ASGI requests with a missing or understated ``Content-Length`` header could +bypass the :setting:`DATA_UPLOAD_MAX_MEMORY_SIZE` limit when reading +``HttpRequest.body``, potentially loading an unbounded request body into +memory and causing service degradation. + +This issue has severity "low" according to the :ref:`Django security policy +`. diff -Nru python-django-4.2.28/docs/releases/index.txt python-django-4.2.30/docs/releases/index.txt --- python-django-4.2.28/docs/releases/index.txt 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/docs/releases/index.txt 2026-04-07 11:39:39.000000000 +0000 @@ -26,6 +26,8 @@ .. toctree:: :maxdepth: 1 + 4.2.30 + 4.2.29 4.2.28 4.2.27 4.2.26 diff -Nru python-django-4.2.28/docs/releases/security.txt python-django-4.2.30/docs/releases/security.txt --- python-django-4.2.28/docs/releases/security.txt 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/docs/releases/security.txt 2026-04-07 11:39:39.000000000 +0000 @@ -36,6 +36,97 @@ All security issues have been handled under versions of Django's security process. These are listed below. +March 3, 2026 - :cve:`2026-25673` +--------------------------------- + +Potential denial-of-service vulnerability in ``URLField`` via Unicode +normalization on Windows. +`Full description +`__ + +* Django 6.0 :commit:`(patch) ` +* Django 5.2 :commit:`(patch) <4d3c184686626d224d9a87451410ecf802b41f7c>` +* Django 4.2 :commit:`(patch) ` + +March 3, 2026 - :cve:`2026-25674` +--------------------------------- + +Potential incorrect permissions on newly created file system objects. +`Full description +`__ + +* Django 6.0 :commit:`(patch) <264d5c70ef3281a8869cb2ad45a3a52d5adbe790>` +* Django 5.2 :commit:`(patch) ` +* Django 4.2 :commit:`(patch) <54b50bf7d6dcbf02d4c01f853627cc9299d4934d>` + +February 3, 2026 - :cve:`2025-13473` +------------------------------------ + +Username enumeration through timing difference in mod_wsgi authentication +handler. +`Full description +`__ + +* Django 6.0 :commit:`(patch) ` +* Django 5.2 :commit:`(patch) <184e38ab0a061c365f5775676a074796d8abd02f>` +* Django 4.2 :commit:`(patch) <6dc23508f3395e1254c315084c7334ef81c4c09a>` + +February 3, 2026 - :cve:`2025-14550` +------------------------------------ + +Potential denial-of-service vulnerability via repeated headers when using ASGI. +`Full description +`__ + +* Django 6.0 :commit:`(patch) <972dbdd4f7f69e9c405e6fe12a1b90e4713c1611>` +* Django 5.2 :commit:`(patch) <1ba90069c12836db46981bdf75b0e661db5849ce>` +* Django 4.2 :commit:`(patch) ` + +February 3, 2026 - :cve:`2026-1207` +----------------------------------- + +Potential SQL injection via raster lookups on PostGIS. +`Full description +`__ + +* Django 6.0 :commit:`(patch) <8f77e7301174834573614ae90e1826fdf27f8a24>` +* Django 5.2 :commit:`(patch) <17a1d64a58ef24c0c3b78d66d86f5415075f18f0>` +* Django 4.2 :commit:`(patch) ` + +February 3, 2026 - :cve:`2026-1285` +----------------------------------- + +Potential denial-of-service vulnerability in ``django.utils.text.Truncator`` +HTML methods. +`Full description +`__ + +* Django 6.0 :commit:`(patch) <4b86ba51e486530db982341a23e53c7a1e1e6e71>` +* Django 5.2 :commit:`(patch) <9f2ada875bbee62ac46032e38ddb22755d67ae5a>` +* Django 4.2 :commit:`(patch) ` + +February 3, 2026 - :cve:`2026-1287` +----------------------------------- + +Potential SQL injection in column aliases via control characters. +`Full description +`__ + +* Django 6.0 :commit:`(patch) <0c0f5c2178c01ada5410cd53b4b207bf7858b952>` +* Django 5.2 :commit:`(patch) <3e68ccdc11c127758745ddf0b4954990b14892bc>` +* Django 4.2 :commit:`(patch) ` + +February 3, 2026 - :cve:`2026-1312` +----------------------------------- + +Potential SQL injection via ``QuerySet.order_by`` and ``FilteredRelation``. +`Full description +`__ + +* Django 6.0 :commit:`(patch) <15e70cb83e6f7a9a2a2f651f30b28b5cb20febeb>` +* Django 5.2 :commit:`(patch) ` +* Django 4.2 :commit:`(patch) <90f5b10784ba5bf369caed87640e2b4394ea3314>` + December 2, 2025 - :cve:`2025-13372` ------------------------------------ diff -Nru python-django-4.2.28/tests/admin_views/admin.py python-django-4.2.30/tests/admin_views/admin.py --- python-django-4.2.28/tests/admin_views/admin.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/tests/admin_views/admin.py 2026-04-07 11:42:15.000000000 +0000 @@ -358,6 +358,14 @@ return super().get_queryset(request).order_by("age") +class ParentWithUUIDPKAdmin(admin.ModelAdmin): + list_display = ("id", "title") + list_editable = ("title",) + + def has_add_permission(self, request): + return False + + class FooAccountAdmin(admin.StackedInline): model = FooAccount extra = 1 @@ -1244,7 +1252,7 @@ site.register(InlineReferer, InlineRefererAdmin) site.register(ReferencedByGenRel) site.register(GenRelReference) -site.register(ParentWithUUIDPK) +site.register(ParentWithUUIDPK, ParentWithUUIDPKAdmin) site.register(RelatedPrepopulated, search_fields=["name"]) site.register(RelatedWithUUIDPKModel) site.register(ReadOnlyRelatedField, ReadOnlyRelatedFieldAdmin) diff -Nru python-django-4.2.28/tests/admin_views/tests.py python-django-4.2.30/tests/admin_views/tests.py --- python-django-4.2.28/tests/admin_views/tests.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/tests/admin_views/tests.py 2026-04-07 11:42:15.000000000 +0000 @@ -2,6 +2,7 @@ import os import re import unittest +from http import HTTPStatus from unittest import mock from urllib.parse import parse_qsl, urljoin, urlparse @@ -4100,6 +4101,22 @@ self.assertIs(Person.objects.get(name="John Mauchly").alive, False) + def test_forged_post_submission_when_no_add_permission(self): + before_count = ParentWithUUIDPK.objects.count() + data = { + "form-TOTAL_FORMS": "1", + "form-INITIAL_FORMS": "0", + "form-MAX_NUM_FORMS": "0", + "form-0-title": "The News", + "form-0-id": "", + "_save": "Save", + } + # This model admin allows no add permissions. + changelist_url = reverse("admin:admin_views_parentwithuuidpk_changelist") + response = self.client.post(changelist_url, data) + self.assertEqual(response.status_code, HTTPStatus.BAD_REQUEST) + self.assertEqual(ParentWithUUIDPK.objects.count(), before_count) + def test_non_field_errors(self): """ Non-field errors are displayed for each of the forms in the diff -Nru python-django-4.2.28/tests/asgi/tests.py python-django-4.2.30/tests/asgi/tests.py --- python-django-4.2.28/tests/asgi/tests.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/tests/asgi/tests.py 2026-04-07 11:43:00.000000000 +0000 @@ -1,12 +1,14 @@ import asyncio import sys import threading +from io import BytesIO from pathlib import Path from asgiref.testing import ApplicationCommunicator from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler -from django.core.asgi import get_asgi_application +from django.core.asgi import ASGIHandler, get_asgi_application +from django.core.exceptions import RequestDataTooBig from django.core.handlers.asgi import ASGIRequest from django.core.signals import request_finished, request_started from django.db import close_old_connections @@ -22,6 +24,7 @@ from .urls import sync_waiter, test_filename TEST_STATIC_ROOT = Path(__file__).parent / "project" / "static" +TOO_MUCH_DATA_MSG = "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE." @override_settings(ROOT_URLCONF="asgi.urls") @@ -220,6 +223,17 @@ self.assertEqual(len(request.headers["foo"].split(",")), 200_000) self.assertLessEqual(setitem_count, 100) + async def test_underscores_in_headers_ignored(self): + scope = self.async_request_factory._base_scope(path="/", http_version="2.0") + scope["headers"] = [(b"some_header", b"1")] + request = ASGIRequest(scope, None) + # No form of the header exists anywhere. + self.assertNotIn("Some_Header", request.headers) + self.assertNotIn("Some-Header", request.headers) + self.assertNotIn("SOME_HEADER", request.META) + self.assertNotIn("SOME-HEADER", request.META) + self.assertNotIn("HTTP_SOME_HEADER", request.META) + async def test_untouched_request_body_gets_closed(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(method="POST", path="/post/") @@ -345,3 +359,157 @@ self.assertEqual(len(sync_waiter.active_threads), 2) sync_waiter.active_threads.clear() + + +class DataUploadMaxMemorySizeASGITests(SimpleTestCase): + def make_request( + self, + body, + content_type=b"application/octet-stream", + content_length=None, + stream=None, + ): + scope = AsyncRequestFactory()._base_scope(method="POST", path="/") + scope["headers"] = [(b"content-type", content_type)] + if content_length is not None: + scope["headers"].append((b"content-length", str(content_length).encode())) + return ASGIRequest(scope, stream if stream is not None else BytesIO(body)) + + def test_body_size_not_exceeded_without_content_length(self): + body = b"x" * 5 + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=5): + self.assertEqual(self.make_request(body).body, body) + + def test_body_size_exceeded_without_content_length(self): + request = self.make_request(b"x" * 10) + with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=5): + request.body + + def test_body_size_check_fires_before_read(self): + # The seekable size check rejects oversized bodies before reading + # them into memory (i.e. before calling self.read()). + class TrackingBytesIO(BytesIO): + calls = [] + + def read(self, *args, **kwargs): + self.calls.append((args, kwargs)) + return super().read(*args, **kwargs) + + stream = TrackingBytesIO(b"x" * 10) + request = self.make_request(b"x" * 10, stream=stream) + with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=5): + request.body + + self.assertEqual(stream.calls, []) + + def test_post_size_exceeded_without_content_length(self): + request = self.make_request( + b"a=" + b"x" * 10, + content_type=b"application/x-www-form-urlencoded", + ) + with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=5): + request.POST + + def test_no_limit(self): + body = b"x" * 100 + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None): + self.assertEqual(self.make_request(body).body, body) + + async def test_read_body_no_limit(self): + chunks = [ + {"type": "http.request", "body": b"x" * 100, "more_body": True}, + {"type": "http.request", "body": b"x" * 100, "more_body": False}, + ] + + async def receive(): + return chunks.pop(0) + + handler = ASGIHandler() + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None): + body_file = await handler.read_body(receive) + self.addCleanup(body_file.close) + + body_file.seek(0) + self.assertEqual(body_file.read(), b"x" * 200) + + def test_non_multipart_body_size_enforced(self): + # DATA_UPLOAD_MAX_MEMORY_SIZE is enforced on non-multipart bodies. + request = self.make_request(b"x" * 100) + with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=10): + request.body + + def test_multipart_file_upload_not_limited_by_data_upload_max(self): + # DATA_UPLOAD_MAX_MEMORY_SIZE applies to non-file fields only; a file + # upload whose total body exceeds the limit must still succeed. + boundary = "testboundary" + file_content = b"x" * 100 + body = ( + ( + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="file"; filename="test.txt"\r\n' + f"Content-Type: application/octet-stream\r\n" + f"\r\n" + ).encode() + + file_content + + f"\r\n--{boundary}--\r\n".encode() + ) + request = self.make_request( + body, + content_type=f"multipart/form-data; boundary={boundary}".encode(), + content_length=len(body), + ) + with self.settings( + DATA_UPLOAD_MAX_MEMORY_SIZE=10, FILE_UPLOAD_MAX_MEMORY_SIZE=10 + ): + files = request.FILES + self.assertEqual(len(files), 1) + uploaded = files["file"] + self.addCleanup(uploaded.close) + self.assertEqual(uploaded.read(), file_content) + + async def test_read_body_buffers_all_chunks(self): + # read_body() consumes all chunks regardless of + # DATA_UPLOAD_MAX_MEMORY_SIZE; the limit is enforced later when + # HttpRequest.body is accessed. + chunks = [ + {"type": "http.request", "body": b"x" * 10, "more_body": True}, + {"type": "http.request", "body": b"y" * 10, "more_body": True}, + {"type": "http.request", "body": b"z" * 10, "more_body": False}, + ] + + async def receive(): + return chunks.pop(0) + + handler = ASGIHandler() + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=15): + body_file = await handler.read_body(receive) + self.addCleanup(body_file.close) + + self.assertEqual(len(chunks), 0) # All chunks were consumed. + body_file.seek(0) + self.assertEqual(body_file.read(), b"x" * 10 + b"y" * 10 + b"z" * 10) + + async def test_read_body_multipart_not_limited(self): + # All chunks are consumed regardless of DATA_UPLOAD_MAX_MEMORY_SIZE; + # multipart size enforcement happens inside MultiPartParser, not here. + chunks = [ + {"type": "http.request", "body": b"x" * 10, "more_body": True}, + {"type": "http.request", "body": b"y" * 10, "more_body": True}, + {"type": "http.request", "body": b"z" * 10, "more_body": False}, + ] + + async def receive(): + return chunks.pop(0) + + handler = ASGIHandler() + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=15): + body_file = await handler.read_body(receive) + self.addCleanup(body_file.close) + + self.assertEqual(len(chunks), 0) # All chunks were consumed. + body_file.seek(0) + self.assertEqual(body_file.read(), b"x" * 10 + b"y" * 10 + b"z" * 10) diff -Nru python-django-4.2.28/tests/forms_tests/field_tests/test_urlfield.py python-django-4.2.30/tests/forms_tests/field_tests/test_urlfield.py --- python-django-4.2.28/tests/forms_tests/field_tests/test_urlfield.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/tests/forms_tests/field_tests/test_urlfield.py 2026-04-07 11:39:39.000000000 +0000 @@ -1,4 +1,5 @@ from django.core.exceptions import ValidationError +from django.core.validators import URLValidator from django.forms import URLField from django.test import SimpleTestCase @@ -72,6 +73,16 @@ # IPv6. ("http://[12:34::3a53]/", "http://[12:34::3a53]/"), ("http://[a34:9238::]:8080/", "http://[a34:9238::]:8080/"), + # IPv6 without scheme. + ("[12:34::3a53]/", "http://[12:34::3a53]/"), + # IDN domain without scheme but with port. + ("ñandú.es:8080/", "http://ñandú.es:8080/"), + # Scheme-relative. + ("//example.com", "http://example.com"), + ("//example.com/path", "http://example.com/path"), + # Whitespace stripped. + ("\t\n//example.com \n\t\n", "http://example.com"), + ("\t\nhttp://example.com \n\t\n", "http://example.com"), ] for url, expected in tests: with self.subTest(url=url): @@ -102,10 +113,19 @@ # even on domains that don't fail the domain label length check in # the regex. "http://%s" % ("X" * 200,), - # urlsplit() raises ValueError. + # Scheme prepend yields a structurally invalid URL. "////]@N.AN", - # Empty hostname. + # Scheme prepend yields an empty hostname. "#@A.bO", + # Known problematic unicode chars. + "http://" + "¾" * 200, + # Non-ASCII character before the first colon. + "¾:example.com", + # ASCII digit before the first colon. + "1http://example.com", + # Empty scheme. + "://example.com", + ":example.com", ] msg = "'Enter a valid URL.'" for value in tests: @@ -135,3 +155,63 @@ msg = "__init__() got multiple values for keyword argument 'strip'" with self.assertRaisesMessage(TypeError, msg): URLField(strip=False) + + def test_urlfield_assume_scheme_when_colons(self): + f = URLField() + tests = [ + # Port number. + ("http://example.com:8080/", "http://example.com:8080/"), + ("https://example.com:443/path", "https://example.com:443/path"), + # Userinfo with password. + ("http://user:pass@example.com", "http://user:pass@example.com"), + ( + "http://user:pass@example.com:8080/", + "http://user:pass@example.com:8080/", + ), + # Colon in path segment. + ("http://example.com/path:segment", "http://example.com/path:segment"), + ("http://example.com/a:b/c:d", "http://example.com/a:b/c:d"), + # Colon in query string. + ("http://example.com/?key=val:ue", "http://example.com/?key=val:ue"), + # Colon in fragment. + ("http://example.com/#section:1", "http://example.com/#section:1"), + # IPv6 -- multiple colons in host. + ("http://[::1]/", "http://[::1]/"), + ("http://[2001:db8::1]/", "http://[2001:db8::1]/"), + ("http://[2001:db8::1]:8080/", "http://[2001:db8::1]:8080/"), + # Colons across multiple components. + ( + "http://user:pass@example.com:8080/path:x?q=a:b#id:1", + "http://user:pass@example.com:8080/path:x?q=a:b#id:1", + ), + # FTP with port and userinfo. + ( + "ftp://user:pass@ftp.example.com:21/file", + "ftp://user:pass@ftp.example.com:21/file", + ), + ( + "ftps://user:pass@ftp.example.com:990/", + "ftps://user:pass@ftp.example.com:990/", + ), + # Scheme-relative URLs, starts with "//". + ("//example.com:8080/path", "http://example.com:8080/path"), + ("//user:pass@example.com/", "http://user:pass@example.com/"), + ] + for value, expected in tests: + with self.subTest(value=value): + self.assertEqual(f.clean(value), expected) + + def test_custom_validator_longer_max_length(self): + class CustomLongURLValidator(URLValidator): + max_length = 4096 + + class CustomURLField(URLField): + default_validators = [CustomLongURLValidator()] + + field = CustomURLField() + # A URL with 4096 chars is valid given the custom validator. + prefix = "https://example.com/" + url = prefix + "a" * (4096 - len(prefix)) + self.assertEqual(len(url), 4096) + # No ValidationError is raised. + field.clean(url) diff -Nru python-django-4.2.28/tests/generic_inline_admin/tests.py python-django-4.2.30/tests/generic_inline_admin/tests.py --- python-django-4.2.28/tests/generic_inline_admin/tests.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/tests/generic_inline_admin/tests.py 2026-04-07 11:41:42.000000000 +0000 @@ -1,6 +1,6 @@ from django.contrib import admin from django.contrib.admin.sites import AdminSite -from django.contrib.auth.models import User +from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.admin import GenericTabularInline from django.contrib.contenttypes.models import ContentType from django.forms.formsets import DEFAULT_MAX_NUM @@ -8,9 +8,9 @@ from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings from django.urls import reverse -from .admin import MediaInline, MediaPermanentInline +from .admin import MediaInline, MediaPermanentInline, PhoneNumberInline from .admin import site as admin_site -from .models import Category, Episode, EpisodePermanent, Media, PhoneNumber +from .models import Category, Contact, Episode, EpisodePermanent, Media, PhoneNumber class TestDataMixin: @@ -295,12 +295,102 @@ @override_settings(ROOT_URLCONF="generic_inline_admin.urls") -class NoInlineDeletionTest(SimpleTestCase): - def test_no_deletion(self): - inline = MediaPermanentInline(EpisodePermanent, admin_site) - fake_request = object() - formset = inline.get_formset(fake_request) - self.assertFalse(formset.can_delete) +class GenericInlineAdminPermissionsTest(TestCase): + factory = RequestFactory() + + @classmethod + def setUpTestData(cls): + cls.user = User(username="admin", is_staff=True, is_active=True) + cls.user.set_password("secret") + cls.user.save() + + # User always has all permissions on Contact (parent) model. + # Permissions on the inlines vary per test. + cls.contact_type = ContentType.objects.get_for_model(Contact) + cls.user.user_permissions.add( + *Permission.objects.filter(content_type=cls.contact_type) + ) + + def test_add_inline_without_add_permission(self): + self.client.force_login(self.user) + inline_view_perm = Permission.objects.get(codename="view_phonenumber") + self.user.user_permissions.add(inline_view_perm) + + category_id = Category.objects.create(name="test").pk + prefix = "generic_inline_admin-phonenumber-content_type-object_id" + post_data = { + "name": "Barbara", + # inline data + f"{prefix}-TOTAL_FORMS": "1", + f"{prefix}-INITIAL_FORMS": "0", + f"{prefix}-MIN_NUM_FORMS": "0", + f"{prefix}-MAX_NUM_FORMS": "0", + f"{prefix}-0-id": "", + f"{prefix}-0-phone_number": "555-555-5555", + f"{prefix}-0-category": str(category_id), + } + request = self.factory.get(reverse("admin:generic_inline_admin_contact_add")) + request.user = self.user + inline = PhoneNumberInline(Contact, AdminSite()) + FormSet = inline.get_formset(request) + formset = FormSet( + data=post_data, prefix=prefix, instance=Contact(name="Barbara") + ) + + self.assertIs(formset.is_valid(), True) + self.assertIs(formset.has_changed(), False) + self.assertEqual(formset.save(commit=False), []) + + def test_add_inline_with_change_permission_only(self): + """ + Forged new inline instances are ignored without add permissions, but + but edits still work with edit permissions. + """ + self.client.force_login(self.user) + inline_perms = Permission.objects.filter( + codename__in=("view_phonenumber", "change_phonenumber") + ) + self.user.user_permissions.add(*inline_perms) + + category_id = Category.objects.create(name="test").pk + contact = Contact.objects.create(name="Barbara") + existing_number = PhoneNumber.objects.create( + category_id=category_id, + content_type=self.contact_type, + object_id=contact.pk, + phone_number="555-555-5555", + ) + prefix = "generic_inline_admin-phonenumber-content_type-object_id" + post_data = { + "id": str(contact.pk), + "name": "Barbara", + # inline data + f"{prefix}-TOTAL_FORMS": "2", + f"{prefix}-INITIAL_FORMS": "1", + f"{prefix}-MIN_NUM_FORMS": "0", + f"{prefix}-MAX_NUM_FORMS": "0", + # Attempt to edit the existing phone number value. + f"{prefix}-0-id": str(existing_number.id), + f"{prefix}-0-phone_number": "111-111-1111", + f"{prefix}-0-category": str(category_id), + # Attempt to forge a new phone number. + f"{prefix}-1-id": "", + f"{prefix}-1-phone_number": "666-666-6666", + f"{prefix}-1-category": str(category_id), + "_save": "Save", + } + request = self.factory.get( + reverse("admin:generic_inline_admin_contact_change", args=[contact.pk]) + ) + request.user = self.user + inline = PhoneNumberInline(Contact, AdminSite()) + FormSet = inline.get_formset(request) + formset = FormSet(data=post_data, prefix=prefix, instance=contact) + + self.assertIs(formset.is_valid(), True) + self.assertIs(formset.has_changed(), True) + # The edit succeeds; the add is ignored. + self.assertEqual(formset.save(commit=False), [existing_number]) class MockRequest: @@ -317,6 +407,14 @@ @override_settings(ROOT_URLCONF="generic_inline_admin.urls") +class NoInlineDeletionTest(SimpleTestCase): + def test_no_deletion(self): + inline = MediaPermanentInline(EpisodePermanent, admin_site) + formset = inline.get_formset(request) + self.assertFalse(formset.can_delete) + + +@override_settings(ROOT_URLCONF="generic_inline_admin.urls") class GenericInlineModelAdminTest(SimpleTestCase): def setUp(self): self.site = AdminSite() diff -Nru python-django-4.2.28/tests/requests_tests/tests.py python-django-4.2.30/tests/requests_tests/tests.py --- python-django-4.2.28/tests/requests_tests/tests.py 2026-02-03 13:30:56.000000000 +0000 +++ python-django-4.2.30/tests/requests_tests/tests.py 2026-04-07 11:42:34.000000000 +0000 @@ -1,6 +1,7 @@ import copy from io import BytesIO from itertools import chain +from unittest import mock from urllib.parse import urlencode from django.core.exceptions import DisallowedHost @@ -11,10 +12,10 @@ RawPostDataException, UnreadablePostError, ) -from django.http.multipartparser import MultiPartParserError +from django.http.multipartparser import LazyStream, MultiPartParserError from django.http.request import split_domain_port from django.test import RequestFactory, SimpleTestCase, override_settings -from django.test.client import FakePayload +from django.test.client import BOUNDARY, MULTIPART_CONTENT, FakePayload class RequestsTests(SimpleTestCase): @@ -537,6 +538,115 @@ self.assertEqual(request.read(1), b"n") self.assertEqual(request.POST, {"name": ["value"]}) + def test_multipart_post_field_with_base64(self): + payload = FakePayload( + "\r\n".join( + [ + f"--{BOUNDARY}", + 'Content-Disposition: form-data; name="name"', + "Content-Transfer-Encoding: base64", + "", + "dmFsdWU=", + f"--{BOUNDARY}--", + "", + ] + ) + ) + request = WSGIRequest( + { + "REQUEST_METHOD": "POST", + "CONTENT_TYPE": MULTIPART_CONTENT, + "CONTENT_LENGTH": len(payload), + "wsgi.input": payload, + } + ) + request.body # evaluate + self.assertEqual(request.POST, {"name": ["value"]}) + + def test_multipart_post_field_with_invalid_base64(self): + payload = FakePayload( + "\r\n".join( + [ + f"--{BOUNDARY}", + 'Content-Disposition: form-data; name="name"', + "Content-Transfer-Encoding: base64", + "", + "123", + f"--{BOUNDARY}--", + "", + ] + ) + ) + request = WSGIRequest( + { + "REQUEST_METHOD": "POST", + "CONTENT_TYPE": MULTIPART_CONTENT, + "CONTENT_LENGTH": len(payload), + "wsgi.input": payload, + } + ) + request.body # evaluate + self.assertEqual(request.POST, {"name": ["123"]}) + + def test_multipart_file_upload_base64_whitespace_heavy(self): + # Fake a file upload with base64-encoded content including mostly + # whitespaces across chunk boundaries. + payload = FakePayload( + "\r\n".join( + [ + f"--{BOUNDARY}", + 'Content-Disposition: form-data; name="file"; filename="test.txt"', + "Content-Type: application/octet-stream", + "Content-Transfer-Encoding: base64", + "", + ] + ) + ) + # "AAAA" decodes to b"\x00\x00\x00". Whitespace (70000 bytes) spans the + # default 64KB chunk boundary, hence the alignment loop is exercised. + payload.write(b"\r\n" + b"AAA" + b" " * 70000 + b"A" + b"\r\n") + payload.write("--" + BOUNDARY + "--\r\n") + request = WSGIRequest( + { + "REQUEST_METHOD": "POST", + "CONTENT_TYPE": MULTIPART_CONTENT, + "CONTENT_LENGTH": len(payload), + "wsgi.input": payload, + } + ) + reads = [] + original_read = LazyStream.read + + def counting_read(self_stream, size=None): + reads.append(size) + return original_read(self_stream, size) + + with mock.patch.object(LazyStream, "read", counting_read): + files = request.FILES + + self.assertEqual(len(files), 1) + self.assertEqual(files["file"].read(), b"\x00\x00\x00") + + # The alignment loop must read in `chunk-sized` units rather than one + # byte at a time, otherwise each whitespace byte triggers a separate + # read() call with a costly internal unget() cycle. + # Parsing this payload should issue exactly 8 LazyStream.read() calls: + # 1. main_stream.read(1) -- BoundaryIter.__init__ probe, preamble + # 2. sub_stream.read(1024) -- parse_boundary_stream, preamble headers + # 3. main_stream.read(1) -- BoundaryIter.__init__ probe, file field + # 4. field_stream.read(1024) -- parse_boundary_stream, file headers + # 5. field_stream.read(65536)-- base64 alignment loop: one chunk-sized + # read to find the non-whitespace bytes + # needed to complete the 4-byte base64 + # group that spans the chunk boundary + # 6. main_stream.read(1) -- BoundaryIter.__init__ probe, epilogue + # 7. sub_stream.read(1024) -- parse_boundary_stream, epilogue headers + # 8. main_stream.read(1) -- BoundaryIter.__init__ probe, exhausted + # stream; returns b"" and stops iteration + # A byte-at-a-time implementation of read() in step 5 would do instead + # one read(1) per whitespace byte past the chunk boundary (4488 calls). + self.assertEqual(reads, [1, 1024, 1, 1024, 65536, 1, 1024, 1]) + def test_POST_after_body_read_and_stream_read_multipart(self): """ POST should be populated even if body is read first, and then diff -Nru python-django-4.2.28/tests/utils_tests/test_os_utils.py python-django-4.2.30/tests/utils_tests/test_os_utils.py --- python-django-4.2.28/tests/utils_tests/test_os_utils.py 2026-01-26 15:09:15.000000000 +0000 +++ python-django-4.2.30/tests/utils_tests/test_os_utils.py 2026-04-04 14:19:34.000000000 +0000 @@ -1,9 +1,173 @@ import os +import stat +import sys +import tempfile import unittest from pathlib import Path from django.core.exceptions import SuspiciousFileOperation -from django.utils._os import safe_join, to_path +from django.utils._os import safe_join, safe_makedirs, to_path + + +class SafeMakeDirsTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.base = tmp.name + self.addCleanup(tmp.cleanup) + + def assertDirMode(self, path, expected): + self.assertIs(os.path.isdir(path), True) + if sys.platform == "win32": + # Windows partially supports chmod: dirs always end up with 0o777. + expected = 0o777 + + # These tests assume a typical process umask (0o022 or similar): they + # create directories with modes like 0o755 and 0o700, which don't have + # group/world write bits, so a typical umask doesn't change the final + # permissions. On unexpected failures, check whether umask has changed. + self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), expected) + + def test_creates_directory_hierarchy_with_permissions(self): + path = os.path.join(self.base, "a", "b", "c") + safe_makedirs(path, mode=0o755) + + self.assertDirMode(os.path.join(self.base, "a"), 0o755) + self.assertDirMode(os.path.join(self.base, "a", "b"), 0o755) + self.assertDirMode(path, 0o755) + + def test_existing_directory_exist_ok(self): + path = os.path.join(self.base, "a") + os.mkdir(path, 0o700) + + safe_makedirs(path, mode=0o755, exist_ok=True) + + self.assertDirMode(path, 0o700) + + def test_existing_directory_exist_ok_false_raises(self): + path = os.path.join(self.base, "a") + os.mkdir(path) + + with self.assertRaises(FileExistsError): + safe_makedirs(path, mode=0o755, exist_ok=False) + + def test_existing_file_at_target_raises(self): + path = os.path.join(self.base, "a") + with open(path, "w") as f: + f.write("x") + + with self.assertRaises(FileExistsError): + safe_makedirs(path, mode=0o755, exist_ok=False) + + with self.assertRaises(FileExistsError): + safe_makedirs(path, mode=0o755, exist_ok=True) + + def test_file_in_intermediate_path_raises(self): + file_path = os.path.join(self.base, "a") + with open(file_path, "w") as f: + f.write("x") + + path = os.path.join(file_path, "b") + + expected = FileNotFoundError if sys.platform == "win32" else NotADirectoryError + + with self.assertRaises(expected): + safe_makedirs(path, mode=0o755, exist_ok=False) + + with self.assertRaises(expected): + safe_makedirs(path, mode=0o755, exist_ok=True) + + def test_existing_parent_preserves_permissions(self): + a = os.path.join(self.base, "a") + b = os.path.join(a, "b") + + os.mkdir(a, 0o700) + + safe_makedirs(b, mode=0o755, exist_ok=False) + + self.assertDirMode(a, 0o700) + self.assertDirMode(b, 0o755) + + c = os.path.join(a, "c") + safe_makedirs(c, mode=0o750, exist_ok=True) + + self.assertDirMode(a, 0o700) + self.assertDirMode(c, 0o750) + + def test_path_is_normalized(self): + path = os.path.join(self.base, "a", "b", "..", "c") + safe_makedirs(path, mode=0o755) + + self.assertDirMode(os.path.normpath(path), 0o755) + self.assertIs(os.path.isdir(os.path.join(self.base, "a", "c")), True) + + def test_permissions_unaffected_by_process_umask(self): + path = os.path.join(self.base, "a", "b", "c") + # `umask()` returns the current mask, so it'll be restored on cleanup. + self.addCleanup(os.umask, os.umask(0o077)) + + safe_makedirs(path, mode=0o755) + + self.assertDirMode(os.path.join(self.base, "a"), 0o755) + self.assertDirMode(os.path.join(self.base, "a", "b"), 0o755) + self.assertDirMode(path, 0o755) + + def test_permissions_correct_despite_concurrent_umask_change(self): + path = os.path.join(self.base, "a", "b", "c") + original_mkdir = os.mkdir + # `umask()` returns the current mask, so it'll be restored on cleanup. + self.addCleanup(os.umask, os.umask(0o000)) + + def mkdir_changing_umask(p, mode): + # Simulate a concurrent thread changing the process umask. + os.umask(0o077) + original_mkdir(p, mode) + + with unittest.mock.patch("os.mkdir", side_effect=mkdir_changing_umask): + safe_makedirs(path, mode=0o755) + + self.assertDirMode(os.path.join(self.base, "a"), 0o755) + self.assertDirMode(os.path.join(self.base, "a", "b"), 0o755) + self.assertDirMode(path, 0o755) + + def test_race_condition_exist_ok_false(self): + path = os.path.join(self.base, "a", "b") + + original_mkdir = os.mkdir + call_count = [0] + + # `safe_makedirs()` calls `os.mkdir()` for each level in the path. + # For path "a/b", mkdir is called twice: once for "a", once for "b". + def mkdir_with_race(p, mode): + call_count[0] += 1 + if call_count[0] == 1: + original_mkdir(p, mode) + else: + raise FileExistsError(f"Directory exists: '{p}'") + + with unittest.mock.patch("os.mkdir", side_effect=mkdir_with_race): + with self.assertRaises(FileExistsError): + safe_makedirs(path, mode=0o755, exist_ok=False) + + def test_race_condition_exist_ok_true(self): + path = os.path.join(self.base, "a", "b") + + original_mkdir = os.mkdir + call_count = [0] + + def mkdir_with_race(p, mode): + call_count[0] += 1 + if call_count[0] == 1: + original_mkdir(p, mode) + else: + # Simulate other thread creating the directory during the race. + # The directory needs to exist for `exist_ok=True` to succeed. + original_mkdir(p, mode) + raise FileExistsError(f"Directory exists: '{p}'") + + with unittest.mock.patch("os.mkdir", side_effect=mkdir_with_race): + safe_makedirs(path, mode=0o755, exist_ok=True) + + self.assertIs(os.path.isdir(path), True) class SafeJoinTests(unittest.TestCase):