id: zip-csv-preflight-gate
namespace: company.team
description: Inspect ZIP entries and verify their CRCs within expansion budgets
before extracting and converting CSV files to ION.
inputs:
- id: archive_url
type: STRING
defaults: https://github.com/mwaskom/seaborn-data/archive/71e2436a092d714350de0fc409ca8a8714e7e78f.zip
description: Trusted HTTP(S) source of a ZIP containing UTF-8, comma-separated
CSV files with headers.
- id: csv_glob
type: STRING
defaults: "*/iris.csv"
description: Case-sensitive fnmatch pattern against full member paths; use
'*.csv' for all lowercase CSV filenames. All entries are still inspected.
- id: expected_sha256
type: STRING
required: false
description: Optional 64-character SHA-256 obtained through a trusted channel.
Empty disables the provenance check.
- id: max_archive_bytes
type: INT
defaults: 33554432
min: 1
description: Compressed-size limit checked after HTTP download, in bytes (32 MiB
by default).
- id: max_entries
type: INT
defaults: 256
min: 1
max: 10000
description: Maximum number of ZIP entries, including directories and non-CSV files.
- id: max_file_bytes
type: INT
defaults: 16777216
min: 1
description: Maximum expanded bytes per file (16 MiB by default).
- id: max_total_bytes
type: INT
defaults: 67108864
min: 1
description: Maximum expanded bytes across all files (64 MiB by default).
- id: max_compression_ratio
type: INT
defaults: 100
min: 1
description: Reject a file if its declared expanded size exceeds this multiple
of its compressed size.
tasks:
- id: download
type: io.kestra.plugin.core.http.Download
uri: "{{ inputs.archive_url }}"
timeout: PT2M
retry:
type: constant
interval: PT5S
maxAttempts: 3
- id: inspect
type: io.kestra.plugin.scripts.python.Script
description: Check every entry before extraction, then stream bounded reads to
verify actual lengths and CRCs.
taskRunner:
type: io.kestra.plugin.core.runner.Process
timeout: PT2M
inputFiles:
archive.zip: "{{ outputs.download.uri }}"
policy.json: "{{ inputs | toJson }}"
outputFiles:
- report.json
script: |
import fnmatch
import hashlib
import json
import re
import stat
import struct
import unicodedata
import zipfile
import zlib
from pathlib import Path
class Rejected(ValueError):
pass
def require(condition, reason):
if not condition:
raise Rejected(reason)
def check_extra(extra):
while extra:
require(len(extra) >= 4, "Truncated ZIP extra field")
kind, size = struct.unpack("<HH", extra[:4])
require(len(extra) >= 4 + size, "Truncated ZIP extra field")
# Different ZIP readers can otherwise disagree about the path or size.
require(kind not in (0x7075, 0x0001),
"Unicode path overrides and ZIP64 are unsupported")
extra = extra[4 + size:]
def expanded_chunks(source, entry):
require(source.tell() == entry.header_offset,
"Unindexed, reordered, or prefixed ZIP data is unsupported")
header = source.read(30)
require(len(header) == 30, "Truncated ZIP local header")
signature, version, flags, method, _, _, crc, packed, size, names, extra = struct.unpack(
"<4s5H3I2H", header)
require(signature == b"PK\x03\x04" and flags == entry.flag_bits and
method == entry.compress_type, "Inconsistent ZIP local header")
expected = (entry.CRC, entry.compress_size, entry.file_size)
require(all(a == b or (flags & 8 and a == 0)
for a, b in zip((crc, packed, size), expected)),
"Inconsistent ZIP local sizes or CRC")
source.read(names) # ZipFile.open separately verifies the local name.
extra_data = source.read(extra)
require(len(extra_data) == extra, "Truncated local extra field")
check_extra(extra_data)
remaining = entry.compress_size
inflater = zlib.decompressobj(-15) if method == zipfile.ZIP_DEFLATED else None
while remaining:
data = source.read(min(65536, remaining))
require(data, "Truncated compressed ZIP data")
remaining -= len(data)
if inflater is None:
yield data
else:
while data:
chunk = inflater.decompress(data, 65536)
require(not inflater.unused_data, "Trailing DEFLATE data")
data = inflater.unconsumed_tail
if chunk:
yield chunk
require(inflater is None or inflater.eof, "Incomplete DEFLATE data")
if flags & 8:
descriptor = source.read(4)
if descriptor == b"PK\x07\x08":
descriptor = source.read(4)
descriptor += source.read(8)
require(len(descriptor) == 12 and struct.unpack("<III", descriptor) == expected,
"Inconsistent ZIP data descriptor")
def inspect_archive(path, policy):
report = {"accepted": False, "sha256": None, "csv_files": [],
"entries": [], "verified_bytes": 0}
try:
require(path.stat().st_size <= policy["max_archive_bytes"],
"Compressed archive exceeds max_archive_bytes")
with path.open("rb") as source:
report["sha256"] = hashlib.file_digest(source, "sha256").hexdigest()
expected = (policy.get("expected_sha256") or "").strip().lower()
require(not expected or re.fullmatch(r"[0-9a-f]{64}", expected),
"expected_sha256 must be empty or 64 hexadecimal characters")
require(not expected or expected == report["sha256"], "SHA-256 mismatch")
with zipfile.ZipFile(path) as archive:
entries = archive.infolist()
require(0 < len(entries) <= policy["max_entries"],
"ZIP is empty or exceeds max_entries")
paths, declared_total, csv_files = {}, 0, []
for entry in entries:
check_extra(entry.extra)
name = entry.filename
require(name == entry.orig_filename and len(name) <= 240,
"Truncated or overlong ZIP member name")
require(not any(ord(c) < 32 or ord(c) == 127 for c in name),
"Control character in ZIP member name")
require(not any(c in name for c in '\\:*?"<>|'),
"Non-portable ZIP member path")
parts = name.rstrip("/").split("/")
require(all(p not in ("", ".", "..") and
not p.endswith((".", " ")) for p in parts),
"Absolute, traversing, or ambiguous ZIP member path")
require(not any(re.fullmatch(r"(?i)(con|prn|aux|nul|com[1-9]|lpt[1-9])",
p.split(".")[0]) for p in parts),
"Reserved device name in ZIP member path")
# ArchiveDecompress replaces spaces with underscores. Reject
# aliases, including case/Unicode aliases on other platforms.
key = unicodedata.normalize("NFC", "/".join(parts).replace(" ", "_")).casefold()
require(key not in paths, "Duplicate or colliding ZIP member path")
paths[key] = entry.is_dir()
mode = stat.S_IFMT(entry.external_attr >> 16)
require(mode in (0, stat.S_IFREG, stat.S_IFDIR),
"Symlink or special file in ZIP")
require(not (mode == stat.S_IFDIR and not entry.is_dir()) and
not (mode == stat.S_IFREG and entry.is_dir()),
"Inconsistent ZIP directory metadata")
require(not entry.flag_bits & 1, "Encrypted ZIP entry is unsupported")
require(entry.compress_type in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED),
"Only stored and DEFLATE ZIP entries are supported")
require(entry.file_size <= policy["max_file_bytes"],
"ZIP member exceeds max_file_bytes")
require(entry.file_size <= max(entry.compress_size, 1) * policy["max_compression_ratio"],
"ZIP member exceeds max_compression_ratio")
require(not entry.is_dir() or entry.file_size == 0,
"Directory entry contains data")
declared_total += entry.file_size
require(declared_total <= policy["max_total_bytes"],
"ZIP exceeds max_total_bytes")
if (not entry.is_dir() and name.lower().endswith(".csv") and
fnmatch.fnmatchcase(name, policy["csv_glob"])):
csv_files.append(name)
report["entries"].append({"name": name, "bytes": entry.file_size,
"compressed_bytes": entry.compress_size})
for key in paths:
components = key.split("/")
require(all(paths.get("/".join(components[:i]), True)
for i in range(1, len(components))),
"A ZIP file is also used as a parent directory")
require(csv_files, "ZIP contains no CSV files matching csv_glob")
# ZipExtFile truncates reads to declared sizes. Count raw bounded
# inflation instead, and reject local records absent from the index.
with path.open("rb") as source:
for entry in entries:
with archive.open(entry):
pass # Verify local name agreement and overlapping entries.
actual, crc = 0, 0
for chunk in expanded_chunks(source, entry):
actual += len(chunk)
report["verified_bytes"] += len(chunk)
crc = zlib.crc32(chunk, crc)
require(actual <= policy["max_file_bytes"] and
report["verified_bytes"] <= policy["max_total_bytes"],
"Actual expanded data exceeds byte budgets")
require(actual == entry.file_size, "ZIP member length mismatch")
require(crc == entry.CRC, "ZIP member CRC mismatch")
require(source.tell() == archive.start_dir,
"Unindexed local ZIP data is unsupported")
report.update(accepted=True, csv_files=csv_files,
reason="All archive checks passed")
except (Rejected, zipfile.BadZipFile, RuntimeError, NotImplementedError,
OSError, EOFError, UnicodeError, zlib.error, struct.error) as error:
report["reason"] = f"{type(error).__name__}: {error}"
return report
if __name__ == "__main__":
policy = json.loads(Path("policy.json").read_text(encoding="utf-8"))
report = inspect_archive(Path("archive.zip"), policy)
Path("report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print("::" + json.dumps({"outputs": {
"accepted": report["accepted"], "csv_files": report["csv_files"],
"sha256": report["sha256"], "reason": report["reason"]}}) + "::")
- id: accept_archive
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.inspect.vars.accepted }}"
then:
- id: extract
type: io.kestra.plugin.compress.ArchiveDecompress
algorithm: ZIP
from: "{{ outputs.download.uri }}"
- id: convert_csv_files
type: io.kestra.plugin.core.flow.Loop
values: "{{ outputs.inspect.vars.csv_files }}"
concurrencyLimit: 2
fetchType: FETCH
outputs:
- id: filename
type: STRING
value: "{{ item.value }}"
- id: uri
type: FILE
value: "{{ outputs.csv_to_ion.uri }}"
- id: rows
type: INT
value: "{{ outputs.csv_to_ion.size }}"
tasks:
- id: csv_to_ion
type: io.kestra.plugin.serdes.csv.CsvToIon
from: "{{ outputs.extract.files[item.value] }}"
header: true
charset: UTF-8
errorOnDifferentFieldCount: true
- id: manifest
type: io.kestra.plugin.core.storage.Write
extension: .json
content: |
{
"sha256": {{ outputs.inspect.vars.sha256 | toJson }},
"report": {{ outputs.inspect.outputFiles['report.json'] | toJson }},
"csv_files": {{ outputs.inspect.vars.csv_files | toJson }},
"converted": {{ outputs.convert_csv_files.outputs | toJson }}
}
else:
- id: reject_archive
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Archive rejected: {{ outputs.inspect.vars.reason }}. See inspect
> outputFiles > report.json."
triggers:
- id: daily
type: io.kestra.plugin.core.trigger.Schedule
cron: "0 6 * * *"
timezone: UTC
disabled: true