vcom/internal/archive/index_test.go
vrubelroman af453aa705 feat(archive): index zip/tar/tar.gz and stream members in one pass (5A.1)
BuildIndex reads the zip directory or walks a tar(.gz) once, with progress
and cancellation; no temp directory. Zip-slip names (.., absolute, drive
letters) and members below a symlink or file of the same archive are
rejected in any order; member count and total size are limited. NewSource
feeds members to transfer: directories and links from the index, file
contents in archive order from a single open; Unpack = Prepare + Execute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 04:10:11 +03:00

211 lines
6 KiB
Go

package archive
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"vcom/internal/transfer"
"vcom/internal/vfs/localfs"
"vcom/internal/vfs/vfstest"
)
func TestIndexZip(t *testing.T) {
idx := index(t, Zip,
dir("docs/"),
file("docs/a.txt", "hello"),
file("deep/x/y.bin", "12345678"), // parents implicit
symlink("docs/ln", "a.txt"),
)
if got := fmt.Sprint(paths(idx)); got != "[deep deep/x deep/x/y.bin docs docs/a.txt docs/ln]" {
t.Fatalf("paths %s", got)
}
if idx.TotalBytes != 13 || idx.Format != Zip {
t.Fatalf("total %d", idx.TotalBytes)
}
e, _ := idx.Lookup("/docs/ln")
if !e.IsSymlink() || e.Link != "a.txt" {
t.Fatalf("link %+v", e)
}
d, _ := idx.Lookup("deep")
if !d.IsDir() || !d.Implicit {
t.Fatalf("implicit dir %+v", d)
}
f, _ := idx.Lookup("docs/a.txt")
if f.Size != 5 || !f.ModTime.Equal(mtime) || f.Mode.Perm() != 0o644 {
t.Fatalf("file %+v", f)
}
}
func TestIndexTarGz(t *testing.T) {
var ms []member
for i := range 1000 {
ms = append(ms, file(fmt.Sprintf("d/f%04d", i), "x"))
}
ms = append(ms, symlink("d/ln", "f0000"), member{name: "d/fifo", mode: os.ModeNamedPipe | 0o644})
b := makeArchive(t, TarGz, ms...)
var progress []int
idx, err := BuildIndex(bg, bytes.NewReader(b), int64(len(b)), TarGz, func(n int) { progress = append(progress, n) })
if err != nil {
t.Fatal(err)
}
if len(idx.Entries) != 1003 || idx.TotalBytes != 1000 {
t.Fatalf("%d entries, %d bytes", len(idx.Entries), idx.TotalBytes)
}
if len(progress) < 3 || progress[len(progress)-1] != 1002 {
t.Fatalf("progress %v", progress)
}
if e, _ := idx.Lookup("d/fifo"); e.Mode&os.ModeNamedPipe == 0 {
t.Fatalf("fifo %+v", e)
}
ctx, cancel := context.WithCancel(bg)
_, err = BuildIndex(ctx, bytes.NewReader(b), int64(len(b)), TarGz, func(n int) {
if n >= 256 {
cancel()
}
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancel: %v", err)
}
}
func TestZipSlipRejected(t *testing.T) {
for _, f := range []Format{Zip, Tar} {
idx := index(t, f,
file("../evil", "x"),
file("/abs/path", "x"),
file("a/../../up", "x"),
file(`..\win`, "x"),
file("C:/drive", "x"),
file("ok/./file", "fine"),
symlink("esc", "/etc"),
file("esc/passwd", "through the link"),
file("plainfile", "f"),
file("plainfile/child", "under a file"),
)
if got := fmt.Sprint(paths(idx)); got != "[esc ok ok/file plainfile]" {
t.Errorf("%v: kept %s", f, got)
}
if len(idx.Rejected) != 7 {
t.Errorf("%v: rejected %v", f, idx.Rejected)
}
if idx.TotalBytes != 5 {
t.Errorf("%v: total %d", f, idx.TotalBytes)
}
}
// A member under a link is rejected whatever the order in the archive.
idx := index(t, Tar, file("esc/passwd", "x"), symlink("esc", "/etc"))
if fmt.Sprint(paths(idx)) != "[esc]" {
t.Fatalf("order-dependent: %v", paths(idx))
}
}
func TestMemberLimit(t *testing.T) {
var ms []member
for i := range 11 {
ms = append(ms, file(fmt.Sprintf("f%d", i), "abc"))
}
for _, f := range []Format{Zip, TarGz} {
b := makeArchive(t, f, ms...)
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxMembers: 10}, nil); !errors.Is(err, ErrTooManyMembers) {
t.Errorf("%v members: %v", f, err)
}
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxBytes: 30}, nil); !errors.Is(err, ErrTooLarge) {
t.Errorf("%v bytes: %v", f, err)
}
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxMembers: 11, MaxBytes: 33}, nil); err != nil {
t.Errorf("%v at the limit: %v", f, err)
}
}
}
// opens counts FS opens of one path.
type opens struct {
mu sync.Mutex
n map[string]int
}
func (o *opens) hook(op vfstest.Op, p string) error {
if op == vfstest.OpOpen {
o.mu.Lock()
if o.n == nil {
o.n = map[string]int{}
}
o.n[p]++
o.mu.Unlock()
}
return nil
}
func TestSourceSinglePass(t *testing.T) {
for _, name := range []string{"a.tar.gz", "a.zip", "a.tar"} {
var ms []member
for i := range 50 {
ms = append(ms, file(fmt.Sprintf("top/f%02d", i), strings.Repeat("y", i)))
}
ms = append(ms, symlink("top/ln", "f01"), dir("top/empty/"))
arch := writeArchive(t, name, ms...)
o := &opens{}
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: o.hook}
idx, err := IndexFile(bg, fsys, arch, nil)
if err != nil {
t.Fatal(err)
}
dst := t.TempDir()
rep := Unpack(bg, fsys, arch, idx, nil, localfs.New(), dst, transfer.DefaultOptions(), transfer.Hooks{})
if rep.Err != nil || rep.Done != 51 || rep.Failed != 0 {
t.Fatalf("%s: %+v", name, rep)
}
if o.n[arch] != 2 { // one for the index, one for the unpack
t.Fatalf("%s: archive opened %d times, want 2 (one pass per phase)", name, o.n[arch])
}
b, _ := os.ReadFile(filepath.Join(dst, "top", "f49"))
if len(b) != 49 {
t.Fatalf("%s: f49 has %d bytes", name, len(b))
}
if l, _ := os.Readlink(filepath.Join(dst, "top", "ln")); l != "f01" {
t.Fatalf("%s: link %q", name, l)
}
if fi, err := os.Stat(filepath.Join(dst, "top", "empty")); err != nil || !fi.IsDir() {
t.Fatalf("%s: empty dir missing", name)
}
if fi, _ := os.Stat(filepath.Join(dst, "top", "f10")); !fi.ModTime().Equal(mtime) {
t.Fatalf("%s: mtime %v", name, fi.ModTime())
}
}
}
func TestNameAndDetect(t *testing.T) {
cases := []struct {
src []string
f Format
want string
}{
{[]string{"foo.tar.gz"}, Zip, "foo.zip"},
{[]string{"/x/foo.zip"}, TarGz, "foo.tar.gz"},
{[]string{"report.pdf"}, Tar, "report.tar"},
{[]string{"photos/"}, Zip, "photos.zip"},
{[]string{"/home/u/proj/a", "/home/u/proj/b"}, Zip, "proj.zip"},
{[]string{"a", "b"}, Tar, "archive.tar"},
}
for _, c := range cases {
if got := Name(c.src, c.f); got != c.want {
t.Errorf("Name(%v, %v) = %q, want %q", c.src, c.f, got, c.want)
}
}
for name, want := range map[string]Format{"a.ZIP": Zip, "a.tgz": TarGz, "a.tar.gz": TarGz, "a.tar": Tar} {
if f, ok := DetectFormat(name); !ok || f != want {
t.Errorf("DetectFormat(%s) = %v %v", name, f, ok)
}
}
if _, ok := DetectFormat(".zip"); ok {
t.Error("bare extension detected")
}
}