Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+640
View File
@@ -0,0 +1,640 @@
package main
import (
"archive/zip"
"bytes"
"encoding/binary"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// zipBuildOpts describes a stdlib-writer-produced test zip with zero-byte
// Store entries named f000000.txt, f000001.txt, ...
type zipBuildOpts struct {
entries int
comment string
customize func(i int, h *zip.FileHeader)
}
func buildZipFile(t *testing.T, path string, opts zipBuildOpts) string {
t.Helper()
out, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
w := zip.NewWriter(out)
if opts.comment != "" {
if err := w.SetComment(opts.comment); err != nil {
t.Fatal(err)
}
}
for i := 0; i < opts.entries; i++ {
h := zip.FileHeader{Name: fmt.Sprintf("f%06d.txt", i), Method: zip.Store}
if opts.customize != nil {
opts.customize(i, &h)
}
if _, err := w.CreateHeader(&h); err != nil {
t.Fatal(err)
}
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
if err := out.Close(); err != nil {
t.Fatal(err)
}
return path
}
func openTestFile(t *testing.T, path string) (*os.File, int64) {
t.Helper()
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { f.Close() })
st, err := f.Stat()
if err != nil {
t.Fatal(err)
}
return f, st.Size()
}
// locateTailEOCD returns the offset of the 22-byte EOCD of a writer-produced
// (commentless) zip, failing the test if it is not where expected.
func locateTailEOCD(t *testing.T, raw []byte) int {
t.Helper()
eocd := len(raw) - zipCDEOCDLen
if eocd < 0 || binary.LittleEndian.Uint32(raw[eocd:eocd+4]) != zipCDEOCDSignature {
t.Fatal("writer-produced EOCD not at tail")
}
return eocd
}
// Round-trip fidelity: on every valid corpus member the mirrored plan must
// find the same directory the stdlib parses (same entry count), the walk must
// count exactly the stdlib's entries, the preflight must pass, and extraction
// through the real entry point must succeed.
func TestZipPreflightRoundTripOnValidCorpus(t *testing.T) {
dir := t.TempDir()
var sfxExpectedStart int64
// A comment whose tail carries a fake PK\x05\x06: it sits inside the
// final 22 bytes, outside the stdlib's backward scan window, but a naive
// last-occurrence scan of the whole file would trip over it.
fakeSigComment := strings.Repeat("A", 30) + "PK\x05\x06" + strings.Repeat("B", 6)
corpus := []struct {
name string
build func(t *testing.T, dir string) string
verify func(t *testing.T, plan zipCentralDirectoryPlan) // optional extra checks
}{
{"plain", func(t *testing.T, dir string) string {
return buildZipFile(t, filepath.Join(dir, "plain.zip"), zipBuildOpts{entries: 3})
}, nil},
{"archive comment", func(t *testing.T, dir string) string {
return buildZipFile(t, filepath.Join(dir, "comment.zip"), zipBuildOpts{entries: 3, comment: "a comment for the whole archive"})
}, nil},
{"sfx prefix", func(t *testing.T, dir string) string {
base := buildZipFile(t, filepath.Join(dir, "sfx-base.zip"), zipBuildOpts{entries: 3})
raw, err := os.ReadFile(base)
if err != nil {
t.Fatal(err)
}
eocd := locateTailEOCD(t, raw)
dirOffset := int64(binary.LittleEndian.Uint32(raw[eocd+16 : eocd+20]))
const junk = 1000
sfxExpectedStart = junk + dirOffset
p := filepath.Join(dir, "sfx.zip")
if err := os.WriteFile(p, append(bytes.Repeat([]byte{'J'}, junk), raw...), 0o644); err != nil {
t.Fatal(err)
}
return p
}, func(t *testing.T, plan zipCentralDirectoryPlan) {
if plan.Start != sfxExpectedStart {
t.Fatalf("sfx walk start = %d, want %d (junk + raw directory offset)", plan.Start, sfxExpectedStart)
}
}},
{"fake eocd signature in comment", func(t *testing.T, dir string) string {
return buildZipFile(t, filepath.Join(dir, "fake-sig.zip"), zipBuildOpts{entries: 3, comment: fakeSigComment})
}, nil},
{"appended duplicate eocd", func(t *testing.T, dir string) string {
base := buildZipFile(t, filepath.Join(dir, "multi-base.zip"), zipBuildOpts{entries: 3})
raw, err := os.ReadFile(base)
if err != nil {
t.Fatal(err)
}
eocd := locateTailEOCD(t, raw)
p := filepath.Join(dir, "multi-eocd.zip")
if err := os.WriteFile(p, append(append([]byte{}, raw...), raw[eocd:]...), 0o644); err != nil {
t.Fatal(err)
}
return p
}, nil},
{"eocd beyond 1kb window", func(t *testing.T, dir string) string {
// A comment longer than the stdlib's first scan window (1KB)
// pushes the EOCD out of stage 1; only the 65KB stage can find
// it, and the mirror must pick the same record.
return buildZipFile(t, filepath.Join(dir, "far-eocd.zip"), zipBuildOpts{
entries: 3,
comment: strings.Repeat("C", 3000),
})
}, nil},
{"zip64 many entries", func(t *testing.T, dir string) string {
// zip.Writer emits zip64 EOCD records at 65535+ entries; keep the
// entries zero-byte so the artifact stays a few MB.
return buildZipFile(t, filepath.Join(dir, "zip64.zip"), zipBuildOpts{entries: 65540})
}, nil},
{"per-entry comments and long and non-ascii names", func(t *testing.T, dir string) string {
return buildZipFile(t, filepath.Join(dir, "fancy.zip"), zipBuildOpts{entries: 3, customize: func(i int, h *zip.FileHeader) {
h.Comment = fmt.Sprintf("entry comment %d", i)
switch i {
case 1:
h.Name = strings.Repeat("l", 200) + ".txt"
case 2:
h.Name = "héllo wörld 日本語.txt"
}
}})
}, nil},
}
for _, tc := range corpus {
t.Run(tc.name, func(t *testing.T) {
src := tc.build(t, dir)
f, size := openTestFile(t, src)
zr, err := zip.NewReader(f, size)
if err != nil {
t.Fatalf("stdlib must open valid corpus member: %v", err)
}
plan, err := planZipCentralDirectory(f, size)
if err != nil {
t.Fatalf("plan error on valid corpus member: %v", err)
}
if !plan.Found {
t.Fatal("EOCD not found on valid corpus member")
}
if plan.Records != uint64(len(zr.File)) {
t.Fatalf("declared records %d != stdlib entries %d", plan.Records, len(zr.File))
}
if tc.verify != nil {
tc.verify(t, plan)
}
scan, violation := scanZipCentralDirectory(f, plan, size, 1<<20, 1<<30)
if violation != zipCentralDirWithinCaps {
t.Fatalf("unexpected walk violation: %d", violation)
}
if scan.Entries != len(zr.File) {
t.Fatalf("walk counted %d headers, stdlib parsed %d", scan.Entries, len(zr.File))
}
if err := preflightZipCentralDirectory(f, size, 1<<20, 1<<30); err != nil {
t.Fatalf("preflight must pass valid corpus member: %v", err)
}
// Extraction through the real entry point at production caps.
dest := filepath.Join(dir, "dest-"+strings.ReplaceAll(tc.name, " ", "-"))
if err := extractZipSafe(src, dest, int64(maxExtractSize)); err != nil {
t.Fatalf("extraction failed: %v", err)
}
if _, err := os.Stat(filepath.Join(dest, zr.File[0].Name)); err != nil {
t.Fatalf("extracted entry missing: %v", err)
}
})
}
}
// Strategy (b): a small declared record count with many real central-directory
// headers. Only the header walk (not the declared count) catches this, which
// is exactly the allocation vector zip.NewReader's post-parse check misses.
func TestZipPreflightWalkCountsRealHeadersNotDeclaredCount(t *testing.T) {
dir := t.TempDir()
base := buildZipFile(t, filepath.Join(dir, "base.zip"), zipBuildOpts{entries: 50})
raw, err := os.ReadFile(base)
if err != nil {
t.Fatal(err)
}
eocd := locateTailEOCD(t, raw)
binary.LittleEndian.PutUint16(raw[eocd+10:eocd+12], 1) // declare 1 record
p := filepath.Join(dir, "underdeclared.zip")
if err := os.WriteFile(p, raw, 0o644); err != nil {
t.Fatal(err)
}
f, size := openTestFile(t, p)
// The stdlib parses all 50 real headers and only then fails the
// mod-65536 comparison - at million-header scale that parse is the DoS.
if zr, err := zip.NewReader(f, size); err == nil {
t.Fatalf("expected stdlib mod-65536 rejection, got %d entries", len(zr.File))
}
err = preflightZipCentralDirectory(f, size, 10, 1<<20)
want := "too many files in archive: 11 (max 10)"
if err == nil || err.Error() != want {
t.Fatalf("preflight must reject on the walked count, got: %v (want %q)", err, want)
}
}
// Strategy (a): a zip64 EOCD declaring a huge entry count with only a handful
// of real headers. The declared-count fast path rejects before any walk.
func TestZipPreflightRejectsDeclaredHugeZip64Count(t *testing.T) {
dir := t.TempDir()
base := buildZipFile(t, filepath.Join(dir, "base.zip"), zipBuildOpts{entries: 3})
raw, err := os.ReadFile(base)
if err != nil {
t.Fatal(err)
}
eocd := locateTailEOCD(t, raw)
dirSize := binary.LittleEndian.Uint32(raw[eocd+12 : eocd+16])
dirOffset := binary.LittleEndian.Uint32(raw[eocd+16 : eocd+20])
const hugeRecords = uint64(1) << 40
// Layout: [original data without EOCD][zip64 EOCD record][zip64 locator][plain EOCD, records=0xffff]
// bytes.Buffer (not bytes.NewBuffer) so the writes cannot spill into raw's
// backing array and clobber the EOCD that patched below is copied from.
var buf bytes.Buffer
buf.Write(raw[:eocd])
rec := make([]byte, zipCDEOCD64Len)
binary.LittleEndian.PutUint32(rec[0:], zipCDEOCD64Signature)
binary.LittleEndian.PutUint64(rec[4:], zipCDEOCD64Len-12) // record size
binary.LittleEndian.PutUint16(rec[12:], 45) // version made by
binary.LittleEndian.PutUint16(rec[14:], 45) // version needed
binary.LittleEndian.PutUint32(rec[16:], 0) // number of this disk
binary.LittleEndian.PutUint32(rec[20:], 0) // disk with start of central dir
binary.LittleEndian.PutUint64(rec[24:], hugeRecords) // records this disk
binary.LittleEndian.PutUint64(rec[32:], hugeRecords) // total records
binary.LittleEndian.PutUint64(rec[40:], uint64(dirSize))
binary.LittleEndian.PutUint64(rec[48:], uint64(dirOffset))
buf.Write(rec)
loc := make([]byte, zipCDEOCD64LocLen)
binary.LittleEndian.PutUint32(loc[0:], zipCDEOCD64LocSignature)
binary.LittleEndian.PutUint32(loc[4:], 0) // disk with zip64 EOCD
binary.LittleEndian.PutUint64(loc[8:], uint64(eocd)) // offset of the zip64 record
binary.LittleEndian.PutUint32(loc[16:], 1) // total disks
buf.Write(loc)
patched := make([]byte, zipCDEOCDLen)
copy(patched, raw[eocd:])
binary.LittleEndian.PutUint16(patched[10:], 0xffff) // zip64 trigger
buf.Write(patched)
p := filepath.Join(dir, "declared-huge.zip")
if err := os.WriteFile(p, buf.Bytes(), 0o644); err != nil {
t.Fatal(err)
}
f, size := openTestFile(t, p)
plan, err := planZipCentralDirectory(f, size)
if err != nil || !plan.Found {
t.Fatalf("crafted zip64 must resolve: %v", err)
}
if plan.Records != hugeRecords {
t.Fatalf("zip64 records = %d, want %d", plan.Records, hugeRecords)
}
err = preflightZipCentralDirectory(f, size, 10, 1<<20)
want := fmt.Sprintf("too many files in archive: %d (max %d)", uint64(1)<<40, 10)
if err == nil || err.Error() != want {
t.Fatalf("declared-huge fast path must reject, got: %v (want %q)", err, want)
}
}
// Fat headers: a handful of entries with large extra fields must hit the
// central-directory byte cap even though the entry count stays tiny.
func TestZipPreflightByteCapRejectsFatCentralDirectory(t *testing.T) {
dir := t.TempDir()
const extraLen = 60000
src := buildZipFile(t, filepath.Join(dir, "fat.zip"), zipBuildOpts{entries: 3, customize: func(i int, h *zip.FileHeader) {
h.Extra = make([]byte, extraLen)
}})
f, size := openTestFile(t, src)
// Sanity: stdlib opens it, and with a generous byte cap the walk sees all
// 3 headers of 46 + name + 60000 bytes each.
if _, err := zip.NewReader(f, size); err != nil {
t.Fatalf("stdlib must open fat-extra archive: %v", err)
}
plan, err := planZipCentralDirectory(f, size)
if err != nil || !plan.Found {
t.Fatalf("plan: %v", err)
}
const nameLen = 11 // f000000.txt
perHeader := int64(46 + nameLen + extraLen)
scan, violation := scanZipCentralDirectory(f, plan, size, 100, 1<<30)
if violation != zipCentralDirWithinCaps || scan.Entries != 3 || scan.Bytes != 3*perHeader {
t.Fatalf("generous caps: violation=%d entries=%d bytes=%d, want 0/3/%d", violation, scan.Entries, scan.Bytes, 3*perHeader)
}
// Two headers already exceed a 100000-byte cap.
err = preflightZipCentralDirectory(f, size, 100, 100000)
want := fmt.Sprintf("zip central directory too large: %d bytes (max %d)", 2*perHeader, 100000)
if err == nil || err.Error() != want {
t.Fatalf("byte cap must reject, got: %v (want %q)", err, want)
}
}
// End to end at the real caps: a maxExtractFiles+1-entry archive is rejected
// by extractZipSafeFrom with the standard message, and a small archive still
// extracts fully afterwards.
func TestExtractZipSafeRejectsTooManyEntriesEndToEnd(t *testing.T) {
dir := t.TempDir()
big := buildZipFile(t, filepath.Join(dir, "big.zip"), zipBuildOpts{entries: maxExtractFiles + 1})
dest := filepath.Join(dir, "out-big")
err := extractZipSafe(big, dest, int64(maxExtractSize))
want := fmt.Sprintf("too many files in archive: %d (max %d)", maxExtractFiles+1, maxExtractFiles)
if err == nil || err.Error() != want {
t.Fatalf("expected standard too-many-files rejection, got: %v (want %q)", err, want)
}
if entries, _ := os.ReadDir(dest); len(entries) != 0 {
t.Fatalf("destination touched despite preflight rejection: %d entries", len(entries))
}
small := buildZipFile(t, filepath.Join(dir, "small.zip"), zipBuildOpts{entries: 3})
dest2 := filepath.Join(dir, "out-small")
if err := extractZipSafe(small, dest2, int64(maxExtractSize)); err != nil {
t.Fatalf("small archive must still extract: %v", err)
}
for i := 0; i < 3; i++ {
if _, err := os.Stat(filepath.Join(dest2, fmt.Sprintf("f%06d.txt", i))); err != nil {
t.Fatalf("entry missing after extraction: %v", err)
}
}
}
// Unparsable inputs must fail open: the preflight returns nil so zip.NewReader
// produces its authentic error. Those paths never reach a large allocation.
// The caps are deliberately tiny to prove pass-through does not depend on them.
func TestZipPreflightPassesUnparsableThroughToStdlib(t *testing.T) {
dir := t.TempDir()
cases := []struct {
name string
build func(t *testing.T) string
}{
{"empty file", func(t *testing.T) string {
p := filepath.Join(dir, "empty.bin")
if err := os.WriteFile(p, nil, 0o644); err != nil {
t.Fatal(err)
}
return p
}},
{"ten bytes of garbage", func(t *testing.T) string {
p := filepath.Join(dir, "garbage.bin")
if err := os.WriteFile(p, bytes.Repeat([]byte{0xDE}, 10), 0o644); err != nil {
t.Fatal(err)
}
return p
}},
{"no eocd", func(t *testing.T) string {
p := filepath.Join(dir, "no-eocd.bin")
if err := os.WriteFile(p, bytes.Repeat([]byte{'A'}, 4096), 0o644); err != nil {
t.Fatal(err)
}
return p
}},
{"truncated zip", func(t *testing.T) string {
base := buildZipFile(t, filepath.Join(dir, "trunc-base.zip"), zipBuildOpts{entries: 5})
raw, err := os.ReadFile(base)
if err != nil {
t.Fatal(err)
}
p := filepath.Join(dir, "truncated.zip")
if err := os.WriteFile(p, raw[:len(raw)*3/5], 0o644); err != nil {
t.Fatal(err)
}
return p
}},
{"directory size out of range", func(t *testing.T) string {
base := buildZipFile(t, filepath.Join(dir, "size-base.zip"), zipBuildOpts{entries: 3})
raw, err := os.ReadFile(base)
if err != nil {
t.Fatal(err)
}
eocd := locateTailEOCD(t, raw)
binary.LittleEndian.PutUint32(raw[eocd+12:eocd+16], 0xfffffff0) // directorySize
p := filepath.Join(dir, "bad-size.zip")
if err := os.WriteFile(p, raw, 0o644); err != nil {
t.Fatal(err)
}
return p
}},
{"eocd comment length overruns file", func(t *testing.T) string {
base := buildZipFile(t, filepath.Join(dir, "cmt-base.zip"), zipBuildOpts{entries: 3})
raw, err := os.ReadFile(base)
if err != nil {
t.Fatal(err)
}
eocd := locateTailEOCD(t, raw)
binary.LittleEndian.PutUint16(raw[eocd+20:eocd+22], 0xffff) // commentLen
p := filepath.Join(dir, "bad-comment.zip")
if err := os.WriteFile(p, raw, 0o644); err != nil {
t.Fatal(err)
}
return p
}},
{"decoy eocd poisoned by overrunning tail eocd", func(t *testing.T) string {
// A valid decoy EOCD sits before a tail EOCD whose comment length
// overruns EOF. The stdlib's backward scan hits the tail record
// first and abandons the whole stage (truncated-comment abort) in
// BOTH windows - it must not fall through to the decoy. The
// mirror has to reach the same verdict.
base := buildZipFile(t, filepath.Join(dir, "decoy-base.zip"), zipBuildOpts{entries: 3})
raw, err := os.ReadFile(base)
if err != nil {
t.Fatal(err)
}
eocd := locateTailEOCD(t, raw)
decoy := append([]byte{}, raw[eocd:]...)
tail := append([]byte{}, raw[eocd:]...)
binary.LittleEndian.PutUint16(tail[20:22], 0xffff) // commentLen overruns EOF
p := filepath.Join(dir, "decoy-poisoned.zip")
if err := os.WriteFile(p, append(append(raw, decoy...), tail...), 0o644); err != nil {
t.Fatal(err)
}
return p
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f, size := openTestFile(t, tc.build(t))
if err := preflightZipCentralDirectory(f, size, 2, 1024); err != nil {
t.Fatalf("unparsable input must pass through, got: %v", err)
}
if _, err := zip.NewReader(f, size); err == nil {
t.Fatal("expected zip.NewReader to produce its own error")
}
})
}
}
// Count-cap boundary at an injected cap: exactly cap entries passes the
// preflight (and the stdlib agrees), cap+1 rejects with the confirmed count.
func TestZipPreflightCountCapBoundary(t *testing.T) {
dir := t.TempDir()
const injectedCap = 10
exact := buildZipFile(t, filepath.Join(dir, "exact.zip"), zipBuildOpts{entries: injectedCap})
f, size := openTestFile(t, exact)
if err := preflightZipCentralDirectory(f, size, injectedCap, 1<<30); err != nil {
t.Fatalf("exactly cap entries must pass: %v", err)
}
zr, err := zip.NewReader(f, size)
if err != nil || len(zr.File) != injectedCap {
t.Fatalf("stdlib must open exactly-cap archive: %v (%d entries)", err, func() int {
if zr != nil {
return len(zr.File)
}
return -1
}())
}
over := buildZipFile(t, filepath.Join(dir, "over.zip"), zipBuildOpts{entries: injectedCap + 1})
f2, size2 := openTestFile(t, over)
err = preflightZipCentralDirectory(f2, size2, injectedCap, 1<<30)
want := fmt.Sprintf("too many files in archive: %d (max %d)", injectedCap+1, injectedCap)
if err == nil || err.Error() != want {
t.Fatalf("cap+1 entries must reject, got: %v (want %q)", err, want)
}
}
// parseZipCDHeader must share readDirectoryHeader's error semantics so the
// walk stops exactly where init's parse loop would stop.
func TestParseZipCDHeaderMirrorSemantics(t *testing.T) {
mkHeader := func(nameLen, extraLen, commentLen int, compSize, uncompSize, hdrOffset uint32, extra []byte) []byte {
buf := make([]byte, zipCDHeaderLen)
binary.LittleEndian.PutUint32(buf[0:], zipCDHeaderSignature)
binary.LittleEndian.PutUint32(buf[20:], compSize)
binary.LittleEndian.PutUint32(buf[24:], uncompSize)
binary.LittleEndian.PutUint16(buf[28:], uint16(nameLen))
binary.LittleEndian.PutUint16(buf[30:], uint16(extraLen))
binary.LittleEndian.PutUint16(buf[32:], uint16(commentLen))
binary.LittleEndian.PutUint32(buf[42:], hdrOffset)
buf = append(buf, bytes.Repeat([]byte{'n'}, nameLen)...)
buf = append(buf, extra...)
buf = append(buf, bytes.Repeat([]byte{'c'}, commentLen)...)
return buf
}
zip64Extra := func(dataLen int) []byte {
b := make([]byte, 4+dataLen)
binary.LittleEndian.PutUint16(b[0:], zipCDZip64ExtraID)
binary.LittleEndian.PutUint16(b[2:], uint16(dataLen))
return b
}
read := func(t *testing.T, data []byte) (int64, bool) {
t.Helper()
return parseZipCDHeader(bytes.NewReader(data))
}
const maxU32 = ^uint32(0)
size, ok := read(t, mkHeader(11, 0, 3, 5, 5, 0, nil))
if !ok || size != 46+11+0+3 {
t.Fatalf("plain header: ok=%v size=%d, want true %d", ok, size, 46+11+3)
}
bad := mkHeader(11, 0, 0, 5, 5, 0, nil)
bad[0] = 'X'
if _, ok := read(t, bad); ok {
t.Fatal("bad signature must not parse")
}
// Unmet uncompressed size is tolerated (the stdlib's 42.zip note) ...
if _, ok := read(t, mkHeader(1, 0, 0, 5, maxU32, 0, nil)); !ok {
t.Fatal("unmet needUSize must be tolerated")
}
// ... but an unmet compressed size or header offset is ErrFormat.
if _, ok := read(t, mkHeader(1, 0, 0, maxU32, 5, 0, nil)); ok {
t.Fatal("unmet needCSize must not parse")
}
if _, ok := read(t, mkHeader(1, 0, 0, 5, 5, maxU32, nil)); ok {
t.Fatal("unmet needHeaderOffset must not parse")
}
// A zip64 extra satisfying the needed value fixes it ... (the declared
// extraLen must match the appended extra bytes, or the parser never
// sees the field at all)
if _, ok := read(t, mkHeader(1, 4+8, 0, 5, maxU32, 0, zip64Extra(8))); !ok {
t.Fatal("zip64 extra must satisfy needUSize")
}
if _, ok := read(t, mkHeader(1, 4+24, 0, maxU32, maxU32, maxU32, zip64Extra(24))); !ok {
t.Fatal("24-byte zip64 extra must satisfy all three needs")
}
// ... but a too-short zip64 extra for a needed value is ErrFormat.
if _, ok := read(t, mkHeader(1, 4+4, 0, maxU32, 5, 0, zip64Extra(4))); ok {
t.Fatal("short zip64 extra for needCSize must not parse")
}
if _, ok := read(t, mkHeader(1, 4+4, 0, 5, 5, maxU32, zip64Extra(4))); ok {
t.Fatal("short zip64 extra for needHeaderOffset must not parse")
}
// needUSize alone with a short zip64 extra is still ErrFormat.
if _, ok := read(t, mkHeader(1, 4+4, 0, 5, maxU32, 0, zip64Extra(4))); ok {
t.Fatal("short zip64 extra for needUSize must not parse")
}
// A declared tail longer than the reader provides stops the walk.
if _, ok := read(t, mkHeader(100, 0, 0, 5, 5, 0, nil)[:50]); ok {
t.Fatal("truncated tail must not parse")
}
// A malformed extra field length breaks the extras loop without error.
malformed := make([]byte, 5)
binary.LittleEndian.PutUint16(malformed[0:], 0x1234)
binary.LittleEndian.PutUint16(malformed[2:], 0xff) // claims 255 bytes, 1 present
malformed[4] = 0xAA
if _, ok := read(t, mkHeader(1, len(malformed), 0, 5, 5, 0, malformed)); !ok {
t.Fatal("malformed extra field must break the loop, not error")
}
}
// findZipCDEOCDInBlock must replicate the stdlib's backward scan, including
// the first-signature-wins rule and the truncated-comment stage abort.
func TestFindZipCDEOCDInBlockMirrorsStdlib(t *testing.T) {
mkEOCD := func(commentLen int) []byte {
b := make([]byte, zipCDEOCDLen)
binary.LittleEndian.PutUint32(b[0:], zipCDEOCDSignature)
binary.LittleEndian.PutUint16(b[20:], uint16(commentLen))
return b
}
if got := findZipCDEOCDInBlock(nil); got != -1 {
t.Fatalf("empty window: %d, want -1", got)
}
if got := findZipCDEOCDInBlock(make([]byte, zipCDEOCDLen-1)); got != -1 {
t.Fatalf("short window: %d, want -1", got)
}
if got := findZipCDEOCDInBlock(mkEOCD(0)); got != 0 {
t.Fatalf("plain EOCD: %d, want 0", got)
}
// EOCD plus a 40-byte comment hosting a fake signature in scan range: the
// first signature from the end wins when its comment length fits. The fake
// sits at 27, so its own comment-length field at [47:49] must declare an n
// with n+22+27 <= 62; 13 is the largest such n.
withFake := mkEOCD(40)
withFake = append(withFake, bytes.Repeat([]byte{'A'}, 40)...)
copy(withFake[zipCDEOCDLen+5:], "PK\x05\x06") // fake at 27, scan starts at 40
binary.LittleEndian.PutUint16(withFake[47:49], 13)
if got := findZipCDEOCDInBlock(withFake); got != 27 {
t.Fatalf("fake signature in scan range: %d, want 27 (first from the end wins)", got)
}
// Same layout, but the fake's comment length overruns the buffer: the
// whole stage is abandoned (-1) even though a valid EOCD sits at 0.
withTruncatedFake := mkEOCD(40)
withTruncatedFake = append(withTruncatedFake, bytes.Repeat([]byte{'A'}, 40)...)
copy(withTruncatedFake[zipCDEOCDLen+5:], "PK\x05\x06")
binary.LittleEndian.PutUint16(withTruncatedFake[27+20:27+22], 0xffff)
if got := findZipCDEOCDInBlock(withTruncatedFake); got != -1 {
t.Fatalf("truncated comment must abandon the stage: %d, want -1", got)
}
// A real EOCD whose declared comment does not fit is also a stage abort.
truncated := append(mkEOCD(5), []byte{'x', 'y', 'z'}...)
if got := findZipCDEOCDInBlock(truncated); got != -1 {
t.Fatalf("overlong comment: %d, want -1", got)
}
}