Python tarfile: stage extraction before promotion
A hypothetical static data bundle contains approved regular files. Build a private staging directory, reject unexpected member types, validate the payload, and return only a promoted directory.
Quick answer
Python tarfile extraction should finish in a private staging directory before its output becomes an accepted bundle. An extraction filter can reject a member after earlier members were written, so failure must leave staging unpromoted. Validate the completed payload against your application’s manifest, then promote it through a clearly owned filesystem operation.
On this page
Python tarfile extraction should finish in a private staging directory before its output becomes an accepted bundle. An extraction filter can reject a member after earlier members were written, so failure must leave staging unpromoted. Validate the completed payload against your application’s manifest, then promote it through a clearly owned filesystem operation. [1][2]
Scenario: a service imports a static reference-data bundle containing a CSV and a schema file. Its current importer extracts directly into the directory readers use. A later archive member is refused, but earlier files remain. The filter did its job; the delivery process still exposed an incomplete bundle. Keep extracted files private until the importer can accept the whole bundle.
The example below is intentionally narrower than a general-purpose archive manager. It accepts a fixed set of regular files with exact relative names. It assumes a maintained Python build with extraction filters, a private application-owned parent directory, a single promoter and same-filesystem staging. It does not claim to sandbox arbitrary hostile archives or replace artifact authentication.
What remains after a rejected archive member?#
Partial extraction can remain after an error. The tarfile documentation states that aborted extraction does not clean up automatically, and the filter design leaves cleanup to the caller. Catching the exception and continuing to serve the destination therefore changes a refused bundle into a partially accepted one. Treat that as an installation failure. [1][2]
First reproduce the delivery symptom with a harmless fixture. Put an approved regular file before a deliberately disallowed member, extract into an isolated temporary directory and inspect what remains when the operation fails. The useful assertion is not only that an exception occurred. It is that no reader-facing success result points to the partial directory.
Do not run an adversarial archive against a shared data directory to demonstrate the risk. The fixture only needs to show that earlier writes can exist when a later member fails. A safe local fixture and a controlled temporary destination are sufficient to investigate the promotion contract without touching live files.
Keep patch maintenance separate from API availability. CPython has required security fixes for extraction-filter bypasses, including the issues tracked by its public security-fix record. Detecting data_filter tells you the interface exists; it does not prove that the interpreter includes all relevant distributor fixes. Record the actual interpreter build used by the importer. [6]
Define the bundle before accepting its paths#
Define allowed names, member types, size limits and required content before opening the archive. For this static-data case, the accepted bundle contains only catalog.csv and schema.json. It needs no symlinks, hard links, devices, directories or executable content. Rejecting those features is an application decision that simplifies both review and testing.
An exact manifest also decides what an unexpected but apparently harmless file means. A hidden metadata file is not automatically acceptable simply because its path stays inside staging. A repeated filename is not automatically harmless simply because the final directory contains only one copy. Explicit rejection avoids a later writer deciding which occurrence should win.
Use a trusted expected manifest supplied by the application or its verified release metadata. A manifest stored inside the same untrusted archive cannot independently establish authenticity. Checksums can establish agreement with trusted expected bytes; parsing and semantic validation establish whether those bytes are usable. Record authenticity, byte agreement and usable content as separate checks.
The extraction filter still matters. PEP 706 provides named filters and a way to build additional policies around them. Our narrow importer delegates the baseline extraction checks to the data filter and adds its own regular-file, name and declared-size restrictions. It does not infer safety merely from a string prefix on a resolved path. [1][2]
Resource bounds need a second boundary outside the Python loop. Declared member sizes are useful admission checks, but they do not independently bound every parser, decompressor, filesystem or CPU cost. Run the importer with your platform’s appropriate process, storage and time limits. The tarfile documentation specifically warns that predefined filters do not prevent denial-of-service attacks. [1]
How does the staging implementation fail closed?#
The implementation returns a promoted directory only after extraction and validation both succeed. Any earlier exception exits the temporary-directory context without returning that path. Python’s temporary-directory facility supplies the staging lifecycle; the application controls when the output becomes accepted. Cleanup failures must remain visible to the caller or operational record. [3]
from pathlib import Path
import os
import tarfile
import tempfile
def stage_bundle(archive, parent, release_name, expected, validate_payload):
"""Single promoter; private POSIX parent on one filesystem.
expected maps exact relative filenames to maximum byte sizes.
validate_payload(root) must raise if content is unacceptable.
This is not a general untrusted-archive sandbox.
"""
if not hasattr(tarfile, "data_filter"):
raise RuntimeError("maintained Python with data_filter required")
if not release_name or release_name in {".", ".."}:
raise ValueError("invalid release name")
if "/" in release_name or "\\" in release_name:
raise ValueError("release name must be one component")
parent = Path(parent)
final = parent / release_name
# The caller guarantees a private parent and a single promoter.
if final.exists() or final.is_symlink():
raise FileExistsError(final)
seen = set()
def accept(member, destination):
if not member.isfile() or member.name not in expected:
raise ValueError("unexpected archive member")
if member.name in seen:
raise ValueError("duplicate archive member")
if member.size < 0 or member.size > expected[member.name]:
raise ValueError("declared member size exceeds policy")
checked = tarfile.data_filter(member, destination)
if checked is None:
raise ValueError("required member was filtered out")
seen.add(member.name)
return checked
with tempfile.TemporaryDirectory(prefix=".staging-", dir=parent) as temp:
payload = Path(temp) / "payload"
payload.mkdir()
with tarfile.open(archive, mode="r:*") as source:
source.extractall(payload, filter=accept)
if seen != set(expected):
raise ValueError("required member missing")
validate_payload(payload)
os.rename(payload, final)
return finalThe parent must be private, and only one process may promote a release into it. The existence check followed by rename is not a portable concurrent “create only if absent” primitive. Another writer must not be able to create, replace or redirect destination entries between those operations. If that ownership cannot be guaranteed, use a deployment mechanism with a suitable no-replace or coordination contract.
The function also expects a local archive whose authenticity and immutability have already been established for this operation. It does not download a remote URL, verify signatures or make a changing source file stable. Keep those steps outside this small filesystem example and record which component owns them.
The validator callback should examine actual content. For the illustrative CSV, verify the required columns, permitted record shapes and application-specific identifiers. For the schema file, parse it and ensure the consuming application recognizes its version. A file existing at the approved name is a necessary condition, not evidence that readers can use it.
If validation reads the whole bundle into memory, its own resource behavior also needs limits. The small fixture used for a tutorial does not justify unbounded production parsing. Stream where appropriate and make the maximum accepted artifact size part of the importer’s operational configuration rather than an assumption hidden in a developer’s laptop test.
What does promotion guarantee, and what does it not?#
A successful same-filesystem POSIX rename provides an atomic namespace transition. That lets the application expose a completed directory name after validation instead of exposing the directory while extraction is in progress. Python documents both the atomic successful operation and filesystem restrictions. The example chooses immutable release directories rather than merging into an existing directory. [4]
That is an atomic visibility boundary, not a complete durability protocol. It does not by itself establish survival of a power loss, coordinated updates across multiple filesystems, or atomic replacement of a non-empty live directory. If those properties matter, the deployment design needs explicit filesystem durability and pointer-switch behavior reviewed for the platform.
Likewise, the returned path is not automatically active. A caller may retain it as an accepted release candidate and switch readers through a separate mechanism. Keep candidate creation and activation as separate states if activation can fail. The function’s success should not be logged as “deployed” before the application’s own activation boundary completes.
An existing release name is a conflict, not permission to delete it and retry. In this example, reject it and reconcile the intended artifact identity. If the operation is retried after a crash, inspect whether the final directory already holds the verified bundle before deciding what to do. Do not turn retry handling into recursive deletion of a directory readers might still use.
Cleanup belongs to the staging owner. Python’s shutil documentation describes platform-dependent resistance to symlink attacks in recursive removal. Keeping staging private reduces exposure to another process rearranging its paths, while checking the platform’s cleanup behavior remains relevant. Do not elevate the importer merely to make cleanup errors disappear. [5]
Which failure cases belong in the acceptance test?#
Test the delivery states, not only the filter exception. The acceptance suite should distinguish an archive rejected before output, an archive rejected after partial staging, a complete bundle rejected by content validation, and a fully accepted candidate. Each failure should leave the final destination absent in this new-release example.
| Fixture | Expected decision | Delivery assertion |
|---|---|---|
| Approved files with valid content | Accept candidate | Returned final directory contains the validated bundle |
| Approved file followed by a link | Reject member type | No promoted directory; staging cleaned or failure recorded |
| Duplicate approved filename | Reject ambiguity | No last-occurrence-wins behavior |
| Missing required file | Reject incomplete bundle | No accepted path returned |
| Oversized declared member | Reject policy violation | No promoted directory |
| Valid names with invalid CSV content | Reject payload | Validation failure remains visible |
| Existing release name | Reconcile conflict | Existing directory stays untouched |
Add traversal names, absolute names, unexpected directories and truncated archives to the isolated fixture set. For each, check both the exception and the filesystem state. Keep sentinel files outside staging to confirm the fixture did not alter them. These local checks support the importer contract; they do not establish protection against every hostile archive or resource-exhaustion technique.
Retain the trusted manifest identity with the accepted candidate. The next process should know which expected bundle was validated, rather than rediscovering its meaning from whichever files happen to be present. A release name supplied by an operator is useful for navigation but need not be the artifact’s integrity identity. Choose and record the identity before extraction starts.
Rehearse the handoff to the reader separately. Create an accepted candidate, leave the currently active candidate untouched, and have the activation mechanism select the new one under its own contract. Then inject an activation failure and verify that readers still have an understood version. The staging function deliberately stops before that step, so its successful return cannot be used as evidence that a service loaded the new data.
A reader may hold an older file open while a newer directory becomes available. Decide whether that is acceptable for reference data or whether consumers need a version-consistent reload protocol. Keep that decision out of the extraction filter: the filter can reject a member, but it cannot coordinate application readers or establish their release identity.
Exercise cleanup failure separately using a controlled fixture on the target platform. Decide what operational record is required if staging remains, and ensure the caller does not interpret cleanup trouble as accepted content. A leftover private directory is a maintenance problem; an accepted partial bundle is a correctness problem. The process should make that distinction visible.
The same ownership questions appear in bounded subprocess execution and build secret handling. A local operation finishing successfully is useful evidence only when the surrounding delivery process defines what becomes visible and who can consume it.
Frequently asked questions#
- Does filter data make extraction transactional?
- Extraction filters inspect or modify members, but aborted extraction can leave earlier output behind. Transactional delivery requires a separate staging and acceptance boundary. Keep that output private until the complete bundle passes the application’s checks. [1][2]
- Is checking for data_filter enough to verify patch level?
- It verifies interface availability, not every security fix in the interpreter or distributor package. Extraction filters have had security fixes. Record the maintained runtime build and review applicable distributor updates instead of treating an attribute check as a patch audit. [6]
- Can I merge staging into the current directory?
- Merging exposes a different delivery contract because readers can observe a mixture of old and new files. The example creates a new immutable release directory after validation. Activation and replacement of an existing release require their own reviewed mechanism. [4]
- Do declared size limits prevent archive denial of service?
- They provide useful admission checks but do not independently bound all decompression, parsing, CPU, memory or filesystem costs. Use appropriate external limits and test the importer under them. The predefined tarfile filters are not a complete denial-of-service defense. [1]