python / python/cpython

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

Open
#154,667 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read the zipfile module and compare timestamp handling in ZipInfo.init(), ZipInfo.from_file(), ZipInfo._for_archive(), and ZipFile.write(). Check the existing strict_timestamps behavior and DOS timestamp precision first. Done means consistent validation or clamping across these entry points, descriptive errors for strict mode, and round-trip-safe upper-bound timestamps.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.