81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package platform
|
|
|
|
import (
|
|
"archive/tar"
|
|
"archive/zip"
|
|
"compress/gzip"
|
|
"context"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func makeTarGz(t *testing.T, entries map[string]string) string {
|
|
t.Helper()
|
|
p := filepath.Join(t.TempDir(), "a.tar.gz")
|
|
f, err := os.Create(p)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
gz := gzip.NewWriter(f)
|
|
tw := tar.NewWriter(gz)
|
|
for name, body := range entries {
|
|
tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(len(body))})
|
|
tw.Write([]byte(body))
|
|
}
|
|
tw.Close()
|
|
gz.Close()
|
|
f.Close()
|
|
return p
|
|
}
|
|
|
|
func makeZip(t *testing.T, entries map[string]string) string {
|
|
t.Helper()
|
|
p := filepath.Join(t.TempDir(), "a.zip")
|
|
f, _ := os.Create(p)
|
|
zw := zip.NewWriter(f)
|
|
for name, body := range entries {
|
|
w, _ := zw.Create(name)
|
|
w.Write([]byte(body))
|
|
}
|
|
zw.Close()
|
|
f.Close()
|
|
return p
|
|
}
|
|
|
|
func TestExtractTarGz(t *testing.T) {
|
|
src := makeTarGz(t, map[string]string{"hello.txt": "world", "sub/x.txt": "y"})
|
|
dest := t.TempDir()
|
|
if err := ExtractTarGz(context.Background(), src, dest); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, _ := os.ReadFile(filepath.Join(dest, "hello.txt"))
|
|
if string(got) != "world" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
got, _ = os.ReadFile(filepath.Join(dest, "sub", "x.txt"))
|
|
if string(got) != "y" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestExtractZip(t *testing.T) {
|
|
src := makeZip(t, map[string]string{"a.txt": "A"})
|
|
dest := t.TempDir()
|
|
if err := ExtractZip(context.Background(), src, dest); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, _ := os.ReadFile(filepath.Join(dest, "a.txt"))
|
|
if string(got) != "A" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestExtractRejectsPathTraversal(t *testing.T) {
|
|
src := makeTarGz(t, map[string]string{"../evil.txt": "x"})
|
|
dest := t.TempDir()
|
|
if err := ExtractTarGz(context.Background(), src, dest); err == nil {
|
|
t.Fatal("want error on path traversal")
|
|
}
|
|
}
|