| 1 | package testlib |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bytes" |
| 6 | "embed" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | ) |
| 13 | |
| 14 | //go:embed test-data-master.zip |
| 15 | var zipFile embed.FS |
| 16 | |
| 17 | func ExtractTestRepository(dir string) (string, error) { |
| 18 | data, err := zipFile.ReadFile("test-data-master.zip") |
| 19 | if err != nil { |
| 20 | return "", fmt.Errorf("could not extract test data: %w", err) |
| 21 | } |
| 22 | |
| 23 | r, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) |
| 24 | if err != nil { |
| 25 | return "", fmt.Errorf("could not read test data: %w", err) |
| 26 | } |
| 27 | |
| 28 | for _, f := range r.File { |
| 29 | if err := extractFile(dir, f); err != nil { |
| 30 | return "", fmt.Errorf("could not extract test data: %w", err) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | return filepath.Join(dir, "test-data"), nil |
| 35 | } |
| 36 | |
| 37 | func extractFile(dst string, f *zip.File) error { |
| 38 | rc, err := f.Open() |
| 39 | if err != nil { |
| 40 | return err |
| 41 | } |
| 42 | defer rc.Close() |
| 43 | |
| 44 | path := filepath.Join(dst, f.Name) |
| 45 | |
| 46 | // Check for ZipSlip (Directory traversal) |
| 47 | if !strings.HasPrefix(path, filepath.Clean(dst)+string(os.PathSeparator)) { |
| 48 | return fmt.Errorf("illegal file path: %s", path) |
| 49 | } |
| 50 | |
| 51 | if f.FileInfo().IsDir() { |
| 52 | return os.MkdirAll(path, f.Mode()) |
| 53 | } |
| 54 | |
| 55 | err = os.MkdirAll(filepath.Dir(path), f.Mode()) |
| 56 | if err != nil { |
| 57 | return err |
| 58 | } |
| 59 | |
| 60 | file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | defer file.Close() |
| 65 | |
| 66 | _, err = io.Copy(file, rc) |
| 67 | if err != nil { |
| 68 | return err |
| 69 | } |
| 70 | |
| 71 | return nil |
| 72 | } |