python / python/cpython

`mailbox.MH.__setitem__()` can destroy a message when replacement fails

Abierto
#156,312 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib topic-email type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug description:
Summary

`When mailbox.MH replaces an existing message with an invalid str, it correctly raises ValueError, but the original message file may already have been truncated to empty. In other words, the replacement fails while also destroying the existing message content, resulting in data loss.

Affected public API: mailbox.MH.__setitem__().

Minimal reproducer

Run this against CPython before the fix:

import mailbox
import tempfile

with tempfile.TemporaryDirectory() as path:
    box = mailbox.MH(path)
    key = box.add(b"Subject: original\n\noriginal body\n")
    original = box.get_bytes(key)

    try:
        box[key] = "Subject: caf\u00e9\n\nreplacement body\n"
    except ValueError as exc:
        print(type(exc).__name__, exc)

    print("in-memory:", box.get_bytes(key))
    box.close()

    reopened = mailbox.MH(path)
    print("reopened:", reopened.get_bytes(key))
    assert reopened.get_bytes(key) == original

Actual result before the fix:

ValueError String input must be ASCII-only; use bytes or a Message instead
in-memory: b''
reopened: b''
AssertionError

Expected result:

ValueError String input must be ASCII-only; use bytes or a Message instead
in-memory: b'Subject: original\n\noriginal body\n'
reopened: b'Subject: original\n\noriginal body\n'

The same problem occurs if a file-like message object raises while it is being read: the old message is replaced with the bytes written before the exception.

Root cause

MH.__setitem__() performed these operations in this order:

open existing message
-> open the same path with O_TRUNC
-> serialize the replacement with _dump_message()
-> propagate a serialization error

O_TRUNC changes the existing message file before _dump_message() validates or fully reads the replacement. For a non-ASCII str, _dump_message() calls _string_to_bytes() and raises ValueError immediately, leaving the already truncated file in place. There is no rollback path.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-156313

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con mailbox.MH.setitem() y _dump_message(), y luego ejecuta el reproductor mínimo del issue en las pruebas de mailbox de CPython. Se considera terminado cuando el reemplazo fallido de una cadena no ASCII o de un mensaje similar a un archivo que genera una excepción deja sin cambios tanto el mensaje original en memoria como el que se vuelve a abrir.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
backend
Tipo de issue
Error
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.