Set a ZIP Decompression Budget Before Opening DOCX and EPUB

DOCX is essentially a set of ZIP entries, and EPUB also uses a ZIP container. Receiving a very small compressed file does not mean it will remain small after de

Setting ZIP decompression budgets is a sound way to handle DOCX and EPUB uploads. A file that arrives small can expand into something much larger, so you need to know what it will become before you open it. This guide explains which limits to set, how to reject files without confusing users, and how to tell a damaged container apart from a translation problem.

Most of the advice applies to any system that accepts ZIP-based formats. The example uses Python's zipfile module to show the rejection path, but the principles are the same whatever language you use.

Read on if you want a practical checklist you can apply at the point where files enter your system.

How do you set a ZIP decompression budget before opening DOCX and EPUB? The short answer

Set limits on compressed size, entry count, single-file size and total expanded size where the file enters your system, and check the directory table before you extract anything.

Your situationWhat to doWhy
You accept DOCX or EPUB uploadsSet limits at the entry point for compressed size, entry count, single-file size and total expanded sizeA small compressed file can grow large after decompression
You rely on the ZIP directory tableUse it to reject entries early, and also enforce runtime limitsThe directory table cannot replace runtime constraints
You read bytes during extractionAccumulate the bytes read and set time and memory budgetsDeclared sizes do not guarantee the real expanded size
A file is rejectedTell the user the reason and keep a separate internal recordUsers can fix the file, and your team can trace the cause
Large documents are validProvide a separate queue or a manual processing pathRaising a quota should not allow unlimited decompression

Test with copies and verify the results before you rely on them

Before you apply anything to real files, read this note:

This paper uses synthetic samples to demonstrate the processing method. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria specified in the text.

In practice, that means:

  • Keep the original copies of important files.
  • Check results against the boundaries and acceptance criteria you set for your own system.
  • Treat the sample files as synthetic demonstrations, not as a guarantee for your own documents.

Why the compressed size is not the full story

DOCX is essentially a set of ZIP entries, and EPUB also uses a ZIP container. Each file inside the archive is stored in compressed form. The compressed size tells you how much data arrived, but not how much data will come out. A tiny upload can unpack into a large set of XML parts, images or other entries.

For this reason, limit four things at the entry point:

  • Compressed size of the file as received
  • Number of entries in the container
  • Size of each individual file after decompression
  • Total expanded size across all entries

Set these limits when the file arrives. Waiting until memory is exhausted to discover that a file is abnormal is too late.

Use the directory table, but do not trust it alone

Start with the directory table. The ZipInfo objects give you the declared size and the compressed size of each entry, which makes them useful for preliminary filtering.

The declared sizes are a starting point. During actual decompression:

  • Accumulate the bytes you actually read, rather than relying on the declared value.
  • Set time and memory budgets for the extraction.
  • Reject early where possible, using the directory table.
CheckStrengthLimitation
Directory table (ZipInfo)Good for early, preliminary filteringDeclared sizes may not match what is actually decompressed
Runtime byte accumulationMeasures the data as it is readNeeds time and memory budgets set alongside it

A pre-check example

from io import BytesIO
from pathlib import PurePosixPath
from zipfile import ZipFile, ZIP_DEFLATED

def inspect(raw, max_entries=10, max_total=4096):
    if len(raw) > 4096:
        raise ValueError("compressed input budget")
    with ZipFile(BytesIO(raw)) as z:
        items = z.infolist()
        if len(items) > max_entries:
            raise ValueError("entry count budget")
        total, seen = 0, set()
        for item in items:
            name = item.filename
            path = PurePosixPath(name)
            if (path.is_absolute() or ".." in path.parts or
                    "\\" in name or ":" in name or name in seen):
                raise ValueError("unsafe or duplicate name")
            seen.add(name)
            total += item.file_size
            if total > max_total:
                raise ValueError("expanded budget")
        return len(items), total

def sample(name, data):
    out = BytesIO()
    with ZipFile(out, "w", ZIP_DEFLATED) as z:
        z.writestr(name, data)
    return out.getvalue()
assert inspect(sample("word/document.xml", b"<doc/>")) == (1, 6)
for raw in [sample("../escape", b"x"), sample("large", b"x" * 5000)]:
    try:
        inspect(raw)
    except ValueError:
        pass
    else:
        raise AssertionError("unsafe archive accepted")

The budgets in this example are deliberately small. They exist to demonstrate the rejection path, so do not copy them directly into production.

This example does not:

  • Call extractall.
  • Write ZIP entries to disk.
  • Act as a complete secure decompressor.

Other concerns need separate policies, including:

  • Encrypted entries
  • Symbolic links
  • Nested archives
  • The resource use of the parser itself

What to tell users when a file is rejected

Each rejection should give the user a clear reason and give your team enough detail to investigate. Keep these two audiences separate.

Trigger conditionExplains to the userInternal record
Total expansion exceeds the budgetFile becomes excessively large after expansionConstraint name and observed value
Duplicate entry nameContainer structure is unclearEntry index, without recording the full text
Out-of-bounds pathFile structure is not supportedSecurity Incident Correlation ID
Container damagedPlease re-export the fileParsing exception type

Notice that the internal record for a duplicate entry stores the entry index, not the full entry name. Apply the same care to any other detail you log.

Do not switch off limits to fix compatibility problems

Some valid documents will be large enough to exceed your budget. Instead of removing the limits, give those files a route through your system:

  • Create an independent queue for large files.
  • Offer a manual processing entry point.

Raising a tenant's business quota does not mean allowing every task to decompress without limit. Enforce the limits together with execution isolation. Showing them as a note next to the upload button is not enough.

Find out where a translation failure happens

When you prepare a document to send to OmniDoc (product entry point), separate container corruption from translation failures. A DOCX file that cannot be parsed as XML points to a problem in input preparation, not in translation.

A clear pre-check report helps the user decide what to do next:

  • Re-export the file.
  • Compress the images.
  • Contact the translation service for troubleshooting.

Reference: Python zipfile

📊 At a glance

ApproachWhat it coversWhat it does not cover
Directory table check (ZipInfo)Early rejection based on declared sizesActual expanded size during extraction
Runtime byte accumulation with time and memory budgetsReal data read during extractionEncryption, symbolic links, nested archives
Pre-check report for usersGuides the user towards re-exporting, compressing images or contacting supportDoes not repair a damaged file by itself

🎯 Which approach fits you?

If you accept DOCX or EPUB uploads from users

Set limits on compressed size, entry count, single-file size and total expanded size before any extraction starts.

If you process large but valid documents

Give them an independent queue or a manual processing route, and keep execution isolation in place.

If you send documents to a translation service

Run a pre-check so you can tell container corruption apart from a translation failure.

❓ FAQ

1. Is a small ZIP file safe to open?

Not necessarily. A very small compressed file can expand into a much larger set of entries, so you need limits on the expanded size as well.

2. Can I rely on the directory table alone?

No. Use the directory table for early rejection, then accumulate the bytes actually read during extraction and set time and memory budgets.

3. Should I raise the limits when a valid file is rejected?

Not across the board. Provide a separate queue or a manual processing route for large files, and keep execution isolation in place.

4. What should I tell a user whose file is rejected?

Give a reason they can act on, such as "Please re-export the file" for a damaged container, and keep the detailed cause in an internal record.

5. Can I copy the example limits into production?

No. The example budgets are deliberately small and show the rejection path as a demonstration.

📝 Summary

Set your ZIP budgets at the point where a file enters your system, before memory is at risk. Combine the directory table check with runtime limits, and give users clear reasons when a file is rejected.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29