python / python/cpython

`zipfile`: Inconsistent and insufficient date_time validation and handling across `ZipInfo` methods

Aperta
#154,667 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

stdlib type-bug
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug report

Bug description:

The zipfile module exhibits architectural inconsistencies in how it handles DOS timestamps (valid range: 1980–2107) across different entry points. The module currently mixes data container responsibilities, input validation, and clamping, leading to uncaught struct.error exceptions, unexpected behavior during archive creation, or precision loss upon reloading.

Problem analysis
1. Inconsistent strict_timestamps support across entry points

ZipInfo.from_file() supports a strict_timestamps parameter, clamping out-of-range dates when set to False. However, when strict_timestamps is True (the default), out-of-range dates are still passed through and only raise a struct.error during later packing (e.g., in ZipInfo.FileHeader() or ZipFile._write_end_record()). Although usually called by ZipFile.write(), ZipInfo.from_file() is a public API and may be called independently, which may make the error obscure. Practically, the option behaves more like no_clamp_timestamps.

ZipInfo.__init__() and ZipInfo._for_archive(), on the other hand, do not expose strict_timestamps at all.

2. ZipInfo.__init__(): asymmetric bounds check

ZipInfo.__init__() hardcodes a check raising ValueError if date_time[0] < 1980. However, it lacks an upper-bound check (year > 2107), resulting an inconsistent behavior:

# Raises ValueError immediately
zinfo = zipfile.ZipInfo(date_time=(1970, 1, 1, 0, 0, 0))

# Silently succeeds during initialization!
zinfo = zipfile.ZipInfo(date_time=(2200, 1, 1, 0, 0, 0))
# Raises struct.error: 'H' format requires 0 <= number <= 65535 when writing with this instance

Additionally, ZipInfo.date_time is a plain instance attribute without a property/descriptor guard, meaning post-instantiation assignments like zinfo.date_time = (2200, 12, 31, 23, 59, 59) will still bypass validation entirely.

3. ZipInfo._for_archive(): unchecked overflow of environment variable and system clock

If SOURCE_DATE_EPOCH is set to a timestamp outside the 1980–2107 range, or if the system clock is configured to a far-future/ancient date, _for_archive() silently constructs the ZipInfo tuple without validation, leading to downstream packing failures (struct.error) when generating headers.

os.environ['SOURCE_DATE_EPOCH'] = str(1 << 33)
with ZipFile(io.BytesIO(), 'w') as zh:
    zh.writestr('foo',  b'')
# If the system time is congured to a far-future
with mock.patch('time.time', return_value=1 << 33), \
     ZipFile(io.BytesIO(), 'w') as zh:
    zh.writestr('foo',  b'')
4. ZipInfo.from_file(): precision truncation at upper bound

When clamping upper-bound timestamps, using 59 seconds (2107-12-31 23:59:59) causes a round-trip inequality. Because the DOS date/time format stores seconds with a 2-second resolution (seconds // 2), encoding 59 seconds truncates to 58 seconds when the file header is re-read from the archive, yielding (2107, 12, 31, 23, 59, 58). This may cause related assertions to fail unexpectedly during testing.

import io, os, tempfile, zipfile
from unittest import mock

with tempfile.TemporaryDirectory() as tmpdir:
    fn = os.path.join(tmpdir, 'foo.txt')
    with open(fn, 'wb') as fh:
        fh.write(b'foo')

    fh = io.BytesIO()
    with mock.patch('os.stat_result.st_mtime', 1 << 33):
        with zipfile.ZipFile(fh, 'w') as zh:
            zinfo = zipfile.ZipInfo.from_file(fn, strict_timestamps=False)
            zh.writestr(zinfo, b'foo')
            print(zinfo.date_time)  # (2107, 12, 31, 23, 59, 59)
        with zipfile.ZipFile(fh) as zh:
            zinfo = zh.infolist()[-1]
            print(zinfo.date_time)  # (2107, 12, 31, 23, 59, 58)
5. Nonworking strict_timestamps=False for extreme timestamps

ZipFile.write() and ZipInfo.from_file() accept strict_timestamps=False, which is intended to clamp out-of-range timestamps to valid DOS bounds. However, this clamping mechanism completely fails when given extreme timestamps that cause the underlying C function (time.localtime) to overflow or raise an error before clamping can take place.

For example, passing an extreme st_mtime value raises an unhandled OverflowError or OSError instead of being smoothly clamped to (2107, 12, 31, 23, 59, 58):

import io, os, tempfile, zipfile
from unittest import mock

with mock.patch('os.stat_result.st_mtime', 1 << 48), \
     tempfile.TemporaryDirectory() as tmpdir:
    fn = os.path.join(tmpdir, 'foo.txt')
    with open(fn, 'wb') as fh:
        fh.write(b'foo')
    
    # Expected: Clamps timestamp to valid DOS range (2107)
    # Actual: Crashes with OverflowError/OSError in time.localtime()
    with zipfile.ZipFile(io.BytesIO(), 'w', strict_timestamps=False) as zh:
        zh.write(fn)
Suggestions
1. Implement unified validate-or-clamp sanitization

Implement a central helper, zipfile._sanitize_date_time(), and apply it across all entry points (ZipInfo.__init__(), ZipInfo.from_file(), and ZipInfo._for_archive()).

  • When strict_timestamps=True: Raise a descriptive ValueError (e.g., ZIP timestamp underflow/overflow) rather than letting it fail later with struct.error.
  • When strict_timestamps=False: Clamp underflow to (1980, 1, 1, 0, 0, 0) and overflow to (2107, 12, 31, 23, 59, 58) to maintain round-trip consistency.
2. Harmonize ZipInfo.__init__() behavior

Align ZipInfo.__init__() with the strict validation logic. While post-instantiation attribute modifications remain unvalidated, this is consistent with other ZipInfo attributes like filename, compress_type, and extra are currently handled. Practically we can keep the "validate-on-init-only" behavior for now. In the future, we could consider reworking ZipInfo.date_time (and maybe other attributes) as a getter/setter property that applies the same sanitization upon assignment.

3. ZipInfo._for_archive(): apply same validate-or-clamp logic for overflowing date_time or timestamp

Besides checking for 1980–2107 for the resulting date_time tuple, timestamp conversion exceptions should also be caught and normalized using the same Validate-or-Clamp logic via the shared sanitizer. For example:

def _sanitize_date_time(date_time, strict_timestamps=True):
    overflow = 0

    if isinstance(date_time, tuple):
        # native zipfile date_time tuple
        if len(date_time) < 6:
            raise ValueError('date_time tuple must have at least 6 elements')
    elif isinstance(date_time, (int, float)):
        # local timestamp
        try:
            date_time = time.localtime(date_time)[:6]
        except (OSError, OverflowError, ValueError):
            overflow = -1 if date_time < 0 else 1
    elif isinstance(date_time, str):
        # envvar SOURCE_DATE_EPOCH

        # raise ValueError natively if invalid
        ts = int(date_time)

        try:
            date_time = time.gmtime(ts)[:6]
        except (OSError, OverflowError, ValueError):
            overflow = -1 if ts < 0 else 1
    else:
        raise TypeError(f'Unsupported type for date_time: {type(date_time).__name__}')

    if overflow == 0:
        if date_time[0] < 1980:
            overflow = -1
        elif date_time[0] > 2107:
            overflow = 1

    if strict_timestamps:
        if overflow == -1:
            raise ValueError('ZIP does not support timestamps before 1980')
        elif overflow == 1:
            raise ValueError('ZIP does not support timestamps after 2107')
    else:
        if overflow == -1:
            return (1980, 1, 1, 0, 0, 0)
        elif overflow == 1:
            return (2107, 12, 31, 23, 59, 58)  # 58s avoids 2-sec rounding discrepancy

    return date_time
CPython versions tested on:

3.14

Operating systems tested on:

No response

Linked PRs
  • gh-154740

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Leggi il modulo zipfile e confronta la gestione dei timestamp in ZipInfo.init(), ZipInfo.from_file(), ZipInfo._for_archive() e ZipFile.write(). Controlla prima il comportamento esistente di strict_timestamps e la precisione dei timestamp DOS. Il lavoro è completato quando la convalida o il troncamento sono coerenti tra questi punti di ingresso, vengono restituiti errori descrittivi per lo strict mode e i timestamp al limite superiore sono sicuri per il round trip.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
backend
Tipo di issue
Bug
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.