← Back to Pull requests

fix: decode MIME-encoded author names in package credits #20622

Closed
r3wretrhy closed this pull request without merging on Oct 05, 2026 14:31 UTC
View on GitHub
r3wretrhy r3wretrhy commented on Sep 29, 2026 23:44 UTC
Author

Package metadata sometimes stores Author / Author-email display names as RFC 2047 encoded-words (for example =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?=). The credits sidebar was rendering those strings literally.

Decode them in format_email and via a small decode_mime_header filter used when the name comes from the plain Author field, so sidebar credits show Unicode names.

Fixes #18930.

Tested:

pytest tests/unit/test_filters.py::test_format_email \
       tests/unit/test_filters.py::test_decode_mime_header \
       -c /dev/null --noconftest

→ 10 passed

Diff: 95 lines (+88 / -7) across 4 files Reviewer: nlhkabu Review duration: 8087m
All Vouch review confidence checks passed
Residual risk 0.12 = Change Risk (0.58) × (1 − Review Confidence (0.80)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.58 · 95 lines diff across 4 files
0.58
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.73 · 5 substantive comment(s)
0.73
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
79%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.273
Sensitive Paths sensitive_paths
0.058
Real PR Conversation Timeline
27 items
nlhkabu nlhkabu commented on Sep 30, 2026 06:34 UTC
Contributor

hi @r3wretrhy thanks for this PR.
As this change affects the UI, would you mind providing a before and after screenshot?

r3wretrhy r3wretrhy commented on Sep 30, 2026 07:28 UTC
Author

Thanks @nlhkabu — happy to provide before/after screenshots.

These show the Credits sidebar for the MIME-encoded author case from #18930 (=?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= → Sebastián Ramírez). Produced via a local static HTML mock that mirrors warehouse/templates/includes/packaging/metadata/credits.html (Author + mailto link) with warehouse-like sidebar classes/colors — not a live PyPI deploy of this PR.

Before (literal encoded-word):

!Credits before — MIME encoded-word shown literally

After (decode_mime_header + format_email):

!Credits after — decoded Unicode author name

Side-by-side:

!Credits before/after combined

nlhkabu nlhkabu commented on Sep 30, 2026 16:28 UTC
Contributor

Thanks @r3wretrhy - looks good on my side. We will need one of the Python devs to approve the changes to .py files.
Please run make reformat and make lint to fix the linting error :)

nlhkabu nlhkabu approved these changes on Sep 30, 2026 16:29 UTC
Approved Reviewer

Looks good on the UI side

r3wretrhy r3wretrhy commented on Sep 30, 2026 16:52 UTC
Author

Thanks @nlhkabu — ran the lint fix.

warehouse/filters.py format_email was tripping Ruff PLW2901 by reassigning the for loop variable name. Renamed the loop target to raw_name and decode into name instead. Local smoke on the MIME Author cases still looks good; awaiting CI on the updated tip.

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:36 UTC
Code Review
tests/unit/test_filters.py:1
@@ -282,6 +282,16 @@ def test_is_recent_none():
         ("not-an-email-address", "", ""),
         ("foo@bar.com", "", "foo@bar.com"),
         ('"Foo Bar" <foo@bar.com>', "Foo Bar", "foo@bar.com"),
+        (
+            "=?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>",
+            "Sebastián Ramírez",
+            "tiangolo@gmail.com",
+        ),
+        (
+            "=?utf-8?b?U2ViYXN0acOhbiBSYW3DrXJleg==?= <tiangolo@gmail.com>",
+            "Sebastián Ramírez",
+            "tiangolo@gmail.com",
+        ),

            "=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?= <jose@example.com>",
            "José Muñoz",
            "jose@example.com",
        ),
        (
            "=?utf-8?b?Sm9zw6kgTXXDsW96?= <jose@example.com>",
            "José Muñoz",
            "jose@example.com",
        ),

lets use a fake user we havent asked for permission here

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:37 UTC
Code Review
tests/unit/test_filters.py:1
@@ -290,6 +300,24 @@ def test_format_email(meta_email, expected_name, expected_email):
     assert email == expected_email
 
 
+@pytest.mark.parametrize(
+    ("inp", "expected"),
+    [
+        (None, None),
+        ("", ""),
+        ("plain name", "plain name"),
+        (
+            "=?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?=",
+            "Sebastián Ramírez",
+        ),
+        # Underscores in Q-encoding are spaces; leave non-encoded text alone.
+        ("already decoded Sebastián", "already decoded Sebastián"),
+    ],
+)

@pytest.mark.parametrize(
    ("inp", "expected"),
    [
        (None, None),
        ("", ""),
        ("plain name", "plain name"),
        (
            "=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?=",
            "José Muñoz",
        ),
        # Underscores in Q-encoding are spaces; leave non-encoded text alone.
        ("already decoded José", "already decoded José"),
    ],
)

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:38 UTC
Code Review
warehouse/filters.py:1
@@ -172,14 +173,31 @@ def parse_isoformat(datestring):
     return datetime.datetime.fromisoformat(datestring)
 
 
+def decode_mime_header(value: str | None) -> str | None:
+    """
+    Decode RFC 2047 encoded-words in metadata header values.
+
+    Package metadata occasionally stores Author / Author-email display names as
+    MIME encoded-words (e.g. ``=?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?=``).
+    Render those as human-readable Unicode in the UI.

    Package metadata occasionally stores Author / Author-email display names as
    MIME encoded-words (e.g. ``=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?=``).
    Render those as human-readable Unicode in the UI.

JacobCoffee JacobCoffee approved these changes on Sep 30, 2026 22:38 UTC
Approved Reviewer

Approved these changes.

woodruffw woodruffw commented on code on Sep 30, 2026 22:48 UTC
Code Review
warehouse/filters.py:1
@@ -172,14 +173,31 @@ def parse_isoformat(datestring):
     return datetime.datetime.fromisoformat(datestring)
 
 
+def decode_mime_header(value: str | None) -> str | None:
+    """
+    Decode RFC 2047 encoded-words in metadata header values.
+
+    Package metadata occasionally stores Author / Author-email display names as
+    MIME encoded-words (e.g. ``=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?=``).
+    Render those as human-readable Unicode in the UI.
+    """
+    if not value or "=?" not in value:
+        return value
+    try:
+        return str(make_header(decode_header(value)))
+    except (LookupError, UnicodeError, ValueError):

I believe this also needs to catch HeaderParseError, e.g.:

make_header(decode_header("=?utf-8?b?A?="))

woodruffw woodruffw commented on code on Sep 30, 2026 22:49 UTC
Code Review
warehouse/filters.py:1
@@ -172,14 +173,31 @@ def parse_isoformat(datestring):
     return datetime.datetime.fromisoformat(datestring)
 
 
+def decode_mime_header(value: str | None) -> str | None:
+    """
+    Decode RFC 2047 encoded-words in metadata header values.
+
+    Package metadata occasionally stores Author / Author-email display names as
+    MIME encoded-words (e.g. ``=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?=``).
+    Render those as human-readable Unicode in the UI.
+    """
+    if not value or "=?" not in value:
+        return value
+    try:
+        return str(make_header(decode_header(value)))

Pretty minor, but FWICT decode_header is quadratic over malformed input, so we should probably limit this to something sane, like encoded forms under 128 (256?) bytes.

woodruffw woodruffw requested changes on Sep 30, 2026 22:50 UTC
Changes Requested Reviewer

Requested changes.

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:50 UTC
Code Review
warehouse/filters.py:1
@@ -172,14 +173,31 @@ def parse_isoformat(datestring):
     return datetime.datetime.fromisoformat(datestring)
 
 
+def decode_mime_header(value: str | None) -> str | None:
+    """
+    Decode RFC 2047 encoded-words in metadata header values.
+
+    Package metadata occasionally stores Author / Author-email display names as
+    MIME encoded-words (e.g. ``=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?=``).
+    Render those as human-readable Unicode in the UI.
+    """
+    if not value or "=?" not in value:
+        return value
+    try:
+        return str(make_header(decode_header(value)))
+    except (LookupError, UnicodeError, ValueError):

        return str(make_header(decode_header(value)))
    except (MessageError, LookupError, UnicodeError, ValueError):

bad names will break uploads

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:50 UTC
Code Review
warehouse/filters.py:1
@@ -9,6 +9,7 @@
 import re
 import urllib.parse
 
+from email.header import decode_header, make_header


from email.errors import MessageError
from email.header import decode_header, make_header

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:54 UTC
Code Review
warehouse/filters.py:1
@@ -172,14 +173,31 @@ def parse_isoformat(datestring):
     return datetime.datetime.fromisoformat(datestring)
 
 
+def decode_mime_header(value: str | None) -> str | None:
+    """
+    Decode RFC 2047 encoded-words in metadata header values.
+
+    Package metadata occasionally stores Author / Author-email display names as
+    MIME encoded-words (e.g. ``=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?=``).
+    Render those as human-readable Unicode in the UI.
+    """
+    if not value or "=?" not in value:
+        return value

    if not value or len(value) > 4096 or "=?" not in value:
        return value

should catch on length here, re: @woodruffw comment too but we can adjust the limit however @woodruffw or others thinks is best

🤖:

Author metadata has no field-length limit, and repeated encoded words make this decoding quadratic. A 416 KB value took approximately 1.6 seconds for one decoding call.

> Skip decoding unusually long values and render the original text instead. The proposed 4,096-character threshold limits decoding work; it does not reject uploads or truncate names

JacobCoffee JacobCoffee requested changes on Sep 30, 2026 22:54 UTC
Changes Requested Reviewer

Requested changes.

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 22:55 UTC
Code Review
warehouse/filters.py:1
@@ -172,14 +173,31 @@ def parse_isoformat(datestring):
     return datetime.datetime.fromisoformat(datestring)
 
 
+def decode_mime_header(value: str | None) -> str | None:
+    """
+    Decode RFC 2047 encoded-words in metadata header values.
+
+    Package metadata occasionally stores Author / Author-email display names as
+    MIME encoded-words (e.g. ``=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?=``).
+    Render those as human-readable Unicode in the UI.
+    """
+    if not value or "=?" not in value:
+        return value
+    try:
+        return str(make_header(decode_header(value)))
+    except (LookupError, UnicodeError, ValueError):

i think its a little broader than @woodruffw's since MessageError also is a parent of CharsetError that might popup but defer to him on if its corret or not

JacobCoffee JacobCoffee commented on code on Sep 30, 2026 23:02 UTC
Code Review
warehouse/filters.py:1

also a possible model scan finding:
- warehouse/filters.py:187 — Decoding the whole value corrupts existing Unicode text.

Ζ =?utf-8?q?x?= becomes the literal text \u0396 x, rather than Ζ x. Decode only encoded-word groups, leaving surrounding text unchanged. Keep adjacent encoded words together so their whitespace and byte-decoding behavior remain intact.

<details>
<summary>Details</summary>

--- a/warehouse/filters.py
+++ b/warehouse/filters.py
@@ -174,6 +174,13 @@
     return datetime.datetime.fromisoformat(datestring)


+_MIME_ENCODED_WORDS = re.compile(
+    r"=\?[^?]+\?[bq]\?.*?\?="
+    r"(?:[ \t\r\n]*=\?[^?]+\?[bq]\?.*?\?=)*",
+    re.IGNORECASE,
+)
+
+
 def decode_mime_header(value: str | None) -> str | None:
     """
     Decode RFC 2047 encoded-words in metadata header values.
@@ -185,7 +192,9 @@
     if not value or len(value) > 4096 or "=?" not in value:
         return value
     try:
-        return str(make_header(decode_header(value)))
+        return _MIME_ENCODED_WORDS.sub(
+            lambda match: str(make_header(decode_header(match.group()))), value
+        )
     except (MessageError, LookupError, UnicodeError, ValueError):
         return value

</details>

JacobCoffee JacobCoffee commented on Sep 30, 2026 23:05 UTC
Contributor

thanks for the PR @r3wretrhy , we'll discuss internally hopefully Friday to decide on next steps. in the event we approve please make sure failing CI is passing and comments addressed

r3wretrhy r3wretrhy commented on Sep 30, 2026 23:51 UTC
Author

Thanks @woodruffw and @JacobCoffee — addressed the CHANGES_REQUESTED feedback in 3d7005a (on top of your tip; no force-push):

1. MessageError catch (covers HeaderParseError for cases like =?utf-8?b?A?=) plus existing LookupError / UnicodeError / ValueError.
2. Length guard — skip decoding when len(value) > 4096 (JacobCoffee’s suggestion; happy to tighten toward woodruffw’s 128–256 if preferred).
3. Decode only encoded-word groups via _MIME_ENCODED_WORDS so surrounding Unicode is not corrupted (Ζ =?utf-8?q?x?= → Ζ x, not \u0396 x).
4. Tests for mixed Unicode, malformed Base64 passthrough, and the overlong skip path.

Local smoke under Python 3.14 + ruff==0.15.22 format/check on the touched files is clean; CI should re-run on the new tip.

woodruffw woodruffw commented on code on Oct 01, 2026 13:44 UTC
Code Review
warehouse/filters.py:1
@@ -172,14 +174,41 @@ def parse_isoformat(datestring):
     return datetime.datetime.fromisoformat(datestring)
 
 
+_MIME_ENCODED_WORDS = re.compile(
+    r"=\?[^?]+\?[bq]\?.*?\?="
+    r"(?:[ \t\r\n]*=\?[^?]+\?[bq]\?.*?\?=)*",
+    re.IGNORECASE,
+)
+
+
+def decode_mime_header(value: str | None) -> str | None:
+    """
+    Decode RFC 2047 encoded-words in metadata header values.
+
+    Package metadata occasionally stores Author / Author-email display names as
+    MIME encoded-words (e.g. ``=?utf-8?q?Jos=C3=A9_Mu=C3=B1oz?=``).
+    Render those as human-readable Unicode in the UI.
+    """
+    if not value or len(value) > 4096 or "=?" not in value:
+        return value
+    try:
+        # Decode only encoded-word groups so surrounding Unicode stays intact.
+        return _MIME_ENCODED_WORDS.sub(
+            lambda match: str(make_header(decode_header(match.group()))), value
+        )

I think this is still pretty brittle: something like decode_mime_header("=?utf-7?q?+2AA-?=") will produce an unpaired surrogate, which will then break WebOb's response preparation.

woodruffw woodruffw requested changes on Oct 01, 2026 13:47 UTC
Changes Requested Reviewer

Requested changes.

r3wretrhy r3wretrhy commented on Oct 01, 2026 13:52 UTC
Author

Thanks @woodruffw — addressed the unpaired-surrogate case in 6035061 (new commit on tip; no force-push).

decode_mime_header("=?utf-7?q?+2AA-?=") was returning "\ud800", which then fails WebOb’s UTF-8 encode. Each encoded-word group is now validated with .encode("utf-8") after make_header(decode_header(...)); on UnicodeError / MessageError / friends we leave that group’s original text intact.

Also parenthesized the except clause so the module imports cleanly on Python 3. Added unit coverage for the utf-7 surrogate input (and the adjacent-group fallback). Local smoke on the decode_mime_header / format_email cases looks good; awaiting CI.

woodruffw woodruffw commented on Oct 01, 2026 14:31 UTC
Contributor

(Just registering a concern: I think this is fundamentally brittle and that Warehouse should probably not merge this until we're confident it won't cause security issues. Fundamentally it's a metadata quality problem with build backends that should arguably be fixed there instead.)

nlhkabu nlhkabu commented on Oct 01, 2026 17:55 UTC
Contributor

Note: if we decide not to merge this - is there a way to simply _hide_ this metadata when it appears in the sidebar?
We could then add some troubleshooting information in the docs to help maintainers understand the limitation?

Something like (generated draft):

------------

Why isn't my author or maintainer name showing on my project page?

PyPI expects the Author, Author-email, Maintainer, and Maintainer-email fields in your project's core metadata to be plain UTF-8 text.

Some build backends encode non-ASCII names using RFC 2047 "encoded-word" syntax instead, which is the format used for email headers, e.g.:

Author-email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <email@example.com>

This is valid for an email header, but it isn't valid plain-text metadata, and PyPI does not decode it. Rather than show you the raw encoded string, PyPI hides that field from the sidebar when it can't be read as plain text.

To fix this: update or configure your build backend so it writes author/maintainer names as plain UTF-8 rather than MIME-encoded strings. This is a setting on the tool that built your package, not something you fix on PyPI after publishing — a new release built with corrected metadata is required.

  • PDM users: recent versions MIME-encode non-ASCII author names by default when writing email-style headers. Check your PDM version's changelog/config for a way to disable encoded-word generation for Author/Author-email, or write plain ASCII-transliterated names if your tool doesn't support disabling it.

  • Other tools (setuptools, Hatchling, Flit, Poetry) do not currently do this encoding, so switching build backends also resolves it.
  • r3wretrhy r3wretrhy commented on Oct 05, 2026 14:31 UTC
    Author

    Thanks for the review and discussion. Given the decode/security concerns raised around the MIME-decode approach, I'm closing this PR unmerged. Appreciate the time and feedback from everyone who looked at it.

    Reviewers
    Assignees
    r3wretrhy r3wretrhy
    Labels
    risk: low confidence: 79.7% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 57.9% (MEDIUM) · Higher = larger blast radius
    57.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 79.7% · Lower = rushed or shallow review
    79.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 11.8% · Safe to merge
    11.8%
    Repository