From 0b8cc23216c9fe75ea662f618f80555b6f3935f7 Mon Sep 17 00:00:00 2001 From: Roger Date: Tue, 27 Oct 2026 14:54:54 +0800 Subject: [PATCH] refactor: introduce internal/snapshot for copy and zip (#653) One copier and one zip transport serve archive, restore, and every profile copy, so locked-file handling has one home. Dropping otiai10/copy takes x/sync out of every binary and testing out of the Windows exe. --- browser/archive.go | 67 +++--- browser/archive_test.go | 89 +++++++- cmd/hack-browser-data/restore.go | 35 ++-- cmd/hack-browser-data/restore_golden_test.go | 9 +- filemanager/copy.go | 35 ---- filemanager/copy_other.go | 12 -- filemanager/copy_windows_test.go | 164 --------------- filemanager/session.go | 44 +--- go.mod | 2 - go.sum | 4 - internal/snapshot/copy.go | 127 +++++++++++ internal/snapshot/copy_other.go | 10 + internal/snapshot/copy_test.go | 74 +++++++ internal/snapshot/copy_windows.go | 17 ++ internal/snapshot/copy_windows_test.go | 62 ++++++ internal/snapshot/snapshot.go | 132 ++++++++++++ internal/snapshot/snapshot_test.go | 171 +++++++++++++++ internal/snapshot/zip.go | 173 +++++++++++++++ internal/snapshot/zip_test.go | 197 ++++++++++++++++++ .../winapi/lockedfile_windows.go | 28 ++- internal/winapi/lockedfile_windows_test.go | 106 ++++++++++ rfcs/012-migration-roadmap.md | 3 +- utils/fileutil/fileutil.go | 102 --------- utils/fileutil/fileutil_zip_test.go | 88 -------- 24 files changed, 1232 insertions(+), 519 deletions(-) delete mode 100644 filemanager/copy.go delete mode 100644 filemanager/copy_other.go delete mode 100644 filemanager/copy_windows_test.go create mode 100644 internal/snapshot/copy.go create mode 100644 internal/snapshot/copy_other.go create mode 100644 internal/snapshot/copy_test.go create mode 100644 internal/snapshot/copy_windows.go create mode 100644 internal/snapshot/copy_windows_test.go create mode 100644 internal/snapshot/snapshot.go create mode 100644 internal/snapshot/snapshot_test.go create mode 100644 internal/snapshot/zip.go create mode 100644 internal/snapshot/zip_test.go rename filemanager/copy_windows.go => internal/winapi/lockedfile_windows.go (86%) create mode 100644 internal/winapi/lockedfile_windows_test.go delete mode 100644 utils/fileutil/fileutil_zip_test.go diff --git a/browser/archive.go b/browser/archive.go index faadee6..807cb5e 100644 --- a/browser/archive.go +++ b/browser/archive.go @@ -1,38 +1,59 @@ package browser import ( + "context" "fmt" - "os" - "path/filepath" "github.com/moond4rk/hackbrowserdata/browser/chromium" - "github.com/moond4rk/hackbrowserdata/filemanager" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) // Archivable is implemented by installations that can enumerate their decryption-relevant files for // cross-host transport (Chromium only). type Archivable interface { BrowserKey() string + UserDataDir() string ArchiveSources(categories []category.Category) []chromium.ArchiveSource } // WriteArchive packs each browser's decryption-relevant files into a zip whose internal layout is -// /, so a restore can re-expand it and decrypt with a keys.json. Files -// are staged through a locked-file session first because Windows holds exclusive SQLite locks. Returns -// the number of source entries staged (a directory source counts once). +// /, so a restore can re-expand it and decrypt with a keys.json. Returns +// the number of source entries captured (a directory source counts once). func WriteArchive(browsers []Browser, categories []category.Category, outPath string) (int, error) { - session, err := filemanager.NewSession() + files := archiveFiles(browsers, categories) + + d, err := snapshot.Temp() if err != nil { return 0, err } - defer session.Cleanup() + defer closeSnapshot(d) - staging := session.TempDir() - seen := make(map[string]bool) + if err := d.Capture(context.Background(), files); err != nil { + return 0, err + } count := 0 + for _, f := range files { + if _, err := d.Snapshot(f.DirID).Path(f.Rel); err != nil { + log.Warnf("archive: acquire %s/%s: %v", f.DirID, f.Rel, err) + continue + } + count++ + } + if count == 0 { + return 0, fmt.Errorf("no decryption-relevant files found to archive") + } + if err := d.Zip(outPath); err != nil { + return 0, fmt.Errorf("write archive %s: %w", outPath, err) + } + return count, nil +} + +// archiveFiles lists each source once; the browser key is its snapshot ID, so the zip's top level stays /. +func archiveFiles(browsers []Browser, categories []category.Category) []snapshot.File { + var files []snapshot.File + seen := make(map[string]bool) for _, b := range browsers { archivable, ok := b.(Archivable) if !ok { @@ -45,24 +66,14 @@ func WriteArchive(browsers []Browser, categories []category.Category, outPath st continue } seen[entry] = true - - dst := filepath.Join(staging, key, filepath.FromSlash(src.LayoutRel)) - if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { - log.Warnf("archive: %s: %v", entry, err) - continue - } - if err := session.Acquire(src.AbsPath, dst, src.IsDir); err != nil { - log.Warnf("archive: acquire %s: %v", entry, err) - continue - } - count++ + files = append(files, snapshot.File{DirID: key, From: archivable.UserDataDir(), Rel: src.LayoutRel, IsDir: src.IsDir}) } } - if count == 0 { - return 0, fmt.Errorf("no decryption-relevant files found to archive") + return files +} + +func closeSnapshot(d *snapshot.Dir) { + if err := d.Close(); err != nil { + log.Warnf("archive: %v", err) } - if err := fileutil.ZipDir(outPath, staging); err != nil { - return 0, fmt.Errorf("write archive %s: %w", outPath, err) - } - return count, nil } diff --git a/browser/archive_test.go b/browser/archive_test.go index f3376cf..fa28152 100644 --- a/browser/archive_test.go +++ b/browser/archive_test.go @@ -1,14 +1,17 @@ package browser import ( + "archive/zip" "os" "path/filepath" + "reflect" + "sort" "testing" "github.com/moond4rk/hackbrowserdata/browser/chromium" "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" "github.com/moond4rk/hackbrowserdata/types" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" ) // TestWriteArchive_RoundTrip exercises the archive path: ArchiveSources -> WriteArchive (stage+zip) @@ -43,10 +46,12 @@ func TestWriteArchive_RoundTrip(t *testing.T) { t.Fatal("WriteArchive captured 0 entries") } - extracted := t.TempDir() - if err := fileutil.Unzip(zipPath, extracted); err != nil { + d, err := snapshot.Unzip(zipPath) + if err != nil { t.Fatalf("Unzip: %v", err) } + defer d.Close() + extracted := d.Path() for _, rel := range []string{ filepath.Join("chrome", "Default", "History"), filepath.Join("chrome", "Default", "Preferences"), @@ -57,3 +62,81 @@ func TestWriteArchive_RoundTrip(t *testing.T) { } } } + +// WriteArchive copies each source from UserDataDir/LayoutRel, so that path must be exactly the source's AbsPath. +func TestArchiveSources_AbsPathIsUserDataDirPlusLayoutRel(t *testing.T) { + nested := t.TempDir() + for _, rel := range []string{ + "Local State", "Default/Preferences", "Default/History", "Default/Login Data", + "Default/Login Data For Account", "Profile 1/Preferences", "Profile 1/Network/Cookies", + } { + writeArchiveFile(t, nested, rel) + } + flat := t.TempDir() + writeArchiveFile(t, flat, "History") + + for _, udd := range []string{nested, flat} { + b, err := chromium.NewBrowser(types.BrowserConfig{Key: "chrome", Name: "chrome", Kind: types.Chromium, UserDataDir: udd}) + if err != nil || b == nil { + t.Fatalf("NewBrowser(%s): b=%v err=%v", udd, b, err) + } + srcs := b.ArchiveSources(category.All()) + if len(srcs) == 0 { + t.Fatalf("%s: no archive sources", udd) + } + for _, src := range srcs { + if want := filepath.Join(b.UserDataDir(), filepath.FromSlash(src.LayoutRel)); src.AbsPath != want { + t.Errorf("AbsPath = %q, want %q", src.AbsPath, want) + } + } + } +} + +func TestWriteArchive_CountsOnlyCapturedSources(t *testing.T) { + origin := t.TempDir() + for _, rel := range []string{"Local State", "Default/Preferences", "Default/History", "Default/Bookmarks"} { + writeArchiveFile(t, origin, rel) + } + b, err := chromium.NewBrowser(types.BrowserConfig{Key: "chrome", Name: "chrome", Kind: types.Chromium, UserDataDir: origin}) + if err != nil || b == nil { + t.Fatalf("NewBrowser: b=%v err=%v", b, err) + } + if err := os.Remove(filepath.Join(origin, "Default", "History")); err != nil { + t.Fatal(err) + } + + zipPath := filepath.Join(t.TempDir(), "data.zip") + n, err := WriteArchive([]Browser{b}, []category.Category{category.History, category.Bookmark}, zipPath) + if err != nil { + t.Fatalf("WriteArchive: %v", err) + } + if n != 3 { + t.Errorf("WriteArchive counted %d entries, want 3: the vanished History must not count", n) + } + + r, err := zip.OpenReader(zipPath) + if err != nil { + t.Fatal(err) + } + defer r.Close() + var got []string + for _, f := range r.File { + got = append(got, f.Name) + } + sort.Strings(got) + want := []string{"chrome/Default/Bookmarks", "chrome/Default/Preferences", "chrome/Local State"} + if !reflect.DeepEqual(got, want) { + t.Errorf("archive entries = %q, want %q", got, want) + } +} + +func writeArchiveFile(t *testing.T, root, rel string) { + t.Helper() + path := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(rel), 0o600); err != nil { + t.Fatal(err) + } +} diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index 402b496..e789e7c 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -10,7 +10,7 @@ import ( "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) func restoreCmd() *cobra.Command { @@ -33,13 +33,13 @@ func restoreCmd() *cobra.Command { hack-browser-data restore --keys keys.json --data-dir ./chrome-userdata -b chrome ssh origin "hack-browser-data dumpkeys" | hack-browser-data restore --keys - --data-zip data.zip`, RunE: func(cmd *cobra.Command, args []string) error { - resolvedDir, cleanup, err := resolveDataDir(dataDir, dataZip) + data, err := openRestoreData(dataDir, dataZip) if err != nil { return err } - defer cleanup() + defer closeRestoreData(data) - browsers, err := loadRestoreBrowsers(keysPath, resolvedDir, browserName) + browsers, err := loadRestoreBrowsers(keysPath, data.Path(), browserName) if err != nil { return err } @@ -92,29 +92,24 @@ func loadRestoreBrowsers(keysPath, dataDir, browserName string) ([]browser.Brows return browser.BuildFromDump(dump, dataDir, browserName) } -// resolveDataDir returns the directory restore reads from: --data-dir as-is, or --data-zip extracted -// into a temp dir (removed by the returned cleanup). Exactly one of the two must be set. -func resolveDataDir(dataDir, dataZip string) (string, func(), error) { - noop := func() {} +// openRestoreData returns the snapshot directory restore reads from: --data-dir in place, or --data-zip extracted +// into a temporary one. Exactly one of the two must be set. +func openRestoreData(dataDir, dataZip string) (*snapshot.Dir, error) { if (dataDir == "") == (dataZip == "") { - return "", noop, fmt.Errorf("exactly one of --data-dir or --data-zip is required") + return nil, fmt.Errorf("exactly one of --data-dir or --data-zip is required") } if dataDir != "" { - return dataDir, noop, nil + return snapshot.Open(dataDir), nil } - tmp, err := os.MkdirTemp("", "hbd-restore-*") + d, err := snapshot.Unzip(dataZip) if err != nil { - return "", noop, fmt.Errorf("create temp dir: %w", err) + return nil, fmt.Errorf("extract %s: %w", dataZip, err) } - if err := fileutil.Unzip(dataZip, tmp); err != nil { - removeTempDir(tmp) - return "", noop, fmt.Errorf("extract %s: %w", dataZip, err) - } - return tmp, func() { removeTempDir(tmp) }, nil + return d, nil } -func removeTempDir(dir string) { - if err := os.RemoveAll(dir); err != nil { - log.Warnf("restore: remove temp dir %s: %v", dir, err) +func closeRestoreData(d *snapshot.Dir) { + if err := d.Close(); err != nil { + log.Warnf("restore: %v", err) } } diff --git a/cmd/hack-browser-data/restore_golden_test.go b/cmd/hack-browser-data/restore_golden_test.go index 916ab71..8b9f722 100644 --- a/cmd/hack-browser-data/restore_golden_test.go +++ b/cmd/hack-browser-data/restore_golden_test.go @@ -15,7 +15,7 @@ import ( "github.com/moond4rk/hackbrowserdata/browser" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/utils/fileutil" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) func TestRestoreGolden(t *testing.T) { @@ -41,9 +41,10 @@ func TestRestoreGolden(t *testing.T) { archive := filepath.Join(out, "results.zip") assertGolden(t, "restore-zip.golden", zipListing(t, archive)) - unzipped := t.TempDir() - require.NoError(t, fileutil.Unzip(archive, unzipped)) - assert.Equal(t, want, readDirFiles(t, unzipped)) + unzipped, err := snapshot.Unzip(archive) + require.NoError(t, err) + defer unzipped.Close() + assert.Equal(t, want, readDirFiles(t, unzipped.Path())) }) t.Run("data-zip", func(t *testing.T) { diff --git a/filemanager/copy.go b/filemanager/copy.go deleted file mode 100644 index cbf2bd0..0000000 --- a/filemanager/copy.go +++ /dev/null @@ -1,35 +0,0 @@ -package filemanager - -import ( - "os" - "strings" - - cp "github.com/otiai10/copy" -) - -// copyFile copies a single file from src to dst. -func copyFile(src, dst string) error { - data, err := os.ReadFile(src) - if err != nil { - return err - } - return os.WriteFile(dst, data, 0o600) -} - -// copyDir copies a directory from src to dst, skipping files -// whose path ends with the skip suffix (e.g. "lock"). -func copyDir(src, dst, skip string) error { - opts := cp.Options{Skip: func(info os.FileInfo, src, _ string) (bool, error) { - return strings.HasSuffix(strings.ToLower(src), skip), nil - }} - return cp.Copy(src, dst, opts) -} - -// isFileExists checks if a file (not directory) exists at the given path. -func isFileExists(path string) bool { - info, err := os.Stat(path) - if err != nil { - return false - } - return !info.IsDir() -} diff --git a/filemanager/copy_other.go b/filemanager/copy_other.go deleted file mode 100644 index ad7eae9..0000000 --- a/filemanager/copy_other.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !windows - -package filemanager - -import "fmt" - -// copyLocked is not supported on non-Windows platforms and always returns an error. -// File locking is primarily a Windows issue where Chrome holds exclusive -// locks on Cookie files via PRAGMA locking_mode=EXCLUSIVE. -func copyLocked(_, _ string) error { - return fmt.Errorf("locked file copy not supported on this platform") -} diff --git a/filemanager/copy_windows_test.go b/filemanager/copy_windows_test.go deleted file mode 100644 index 6502e4f..0000000 --- a/filemanager/copy_windows_test.go +++ /dev/null @@ -1,164 +0,0 @@ -//go:build windows - -package filemanager - -import ( - "bytes" - "os" - "path/filepath" - "syscall" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestCopyLocked_ExclusiveLock(t *testing.T) { - dir := t.TempDir() - src := filepath.Join(dir, "locked.db") - testData := []byte("this is locked file content") - - require.NoError(t, os.WriteFile(src, testData, 0o644)) - - handle := openExclusive(t, src) - defer syscall.CloseHandle(handle) - - // Normal copy should fail - err := copyFile(src, filepath.Join(dir, "normal_copy.db")) - require.Error(t, err, "normal copy should fail on exclusively locked file") - - // copyLocked should succeed via DuplicateHandle + FileMapping - lockedDst := filepath.Join(dir, "locked_copy.db") - err = copyLocked(src, lockedDst) - require.NoError(t, err, "copyLocked should bypass exclusive lock") - - copied, err := os.ReadFile(lockedDst) - require.NoError(t, err) - assert.Equal(t, testData, copied, "copied content should match original") -} - -func TestCopyLocked_WriteThenRead(t *testing.T) { - dir := t.TempDir() - src := filepath.Join(dir, "modified.db") - - // Write initial data - require.NoError(t, os.WriteFile(src, []byte("initial"), 0o644)) - - // Open exclusively and write more data through the handle - handle := openExclusive(t, src) - defer syscall.CloseHandle(handle) - - // Seek to end and write additional data - _, seekErr := syscall.Seek(handle, 0, 2) // SEEK_END - require.NoError(t, seekErr) - additional := []byte(" + appended data") - var written uint32 - writeErr := syscall.WriteFile(handle, additional, &written, nil) - require.NoError(t, writeErr) - require.Equal(t, uint32(len(additional)), written) - flushErr := syscall.FlushFileBuffers(handle) - require.NoError(t, flushErr) - - // copyLocked should read the full content including appended data - lockedDst := filepath.Join(dir, "modified_copy.db") - copyErr := copyLocked(src, lockedDst) - require.NoError(t, copyErr) - - copied, err := os.ReadFile(lockedDst) - require.NoError(t, err) - assert.Equal(t, "initial + appended data", string(copied), - "should read complete content including data written after lock") -} - -func TestCopyLocked_LargeFile(t *testing.T) { - dir := t.TempDir() - src := filepath.Join(dir, "large.db") - - // Create a file similar in size to a real Cookies database (~64KB) - data := make([]byte, 65536) - for i := range data { - data[i] = byte(i % 256) - } - require.NoError(t, os.WriteFile(src, data, 0o644)) - - handle := openExclusive(t, src) - defer syscall.CloseHandle(handle) - - lockedDst := filepath.Join(dir, "large_copy.db") - err := copyLocked(src, lockedDst) - require.NoError(t, err) - - copied, err := os.ReadFile(lockedDst) - require.NoError(t, err) - assert.Len(t, copied, len(data), "file sizes should match") - assert.True(t, bytes.Equal(data, copied), "file content should match byte-for-byte") -} - -func TestCopyLocked_FileNotFound(t *testing.T) { - err := copyLocked("/nonexistent/file.db", filepath.Join(t.TempDir(), "dst.db")) - require.Error(t, err) -} - -func TestAcquire_FallbackToLocked(t *testing.T) { - dir := t.TempDir() - src := filepath.Join(dir, "cookies.db") - testData := []byte("cookie data") - - require.NoError(t, os.WriteFile(src, testData, 0o644)) - - handle := openExclusive(t, src) - defer syscall.CloseHandle(handle) - - session, err := NewSession() - require.NoError(t, err) - defer session.Cleanup() - - dst := filepath.Join(session.TempDir(), "cookies.db") - err = session.Acquire(src, dst, false) - require.NoError(t, err, "Acquire should succeed via locked fallback") - - copied, err := os.ReadFile(dst) - require.NoError(t, err) - assert.Equal(t, testData, copied) -} - -func TestAcquire_NormalCopyWhenNotLocked(t *testing.T) { - dir := t.TempDir() - src := filepath.Join(dir, "unlocked.db") - testData := []byte("unlocked data") - - require.NoError(t, os.WriteFile(src, testData, 0o644)) - - // No exclusive lock — normal copy should work without needing copyLocked - session, err := NewSession() - require.NoError(t, err) - defer session.Cleanup() - - dst := filepath.Join(session.TempDir(), "unlocked.db") - err = session.Acquire(src, dst, false) - require.NoError(t, err) - - copied, err := os.ReadFile(dst) - require.NoError(t, err) - assert.Equal(t, testData, copied) -} - -// openExclusive opens a file with exclusive lock (dwShareMode=0), -// simulating Chrome's PRAGMA locking_mode=EXCLUSIVE behavior. -func openExclusive(t *testing.T, path string) syscall.Handle { - t.Helper() - srcPtr, err := syscall.UTF16PtrFromString(path) - require.NoError(t, err) - - handle, err := syscall.CreateFile( - srcPtr, - syscall.GENERIC_READ|syscall.GENERIC_WRITE, - 0, // exclusive: no sharing - nil, - syscall.OPEN_EXISTING, - syscall.FILE_ATTRIBUTE_NORMAL, - 0, - ) - require.NoError(t, err) - return handle -} diff --git a/filemanager/session.go b/filemanager/session.go index e21e3c0..a9ed1b4 100644 --- a/filemanager/session.go +++ b/filemanager/session.go @@ -1,10 +1,10 @@ package filemanager import ( - "errors" "fmt" "os" - "runtime" + + "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) // Session manages temporary files for a single browser extraction run. @@ -28,45 +28,9 @@ func (s *Session) TempDir() string { return s.tempDir } -// Acquire copies a browser file (or directory) from src to dst. -// For regular files, it also copies SQLite WAL and SHM companion files -// if they exist. For directories (e.g. LevelDB), it copies the entire -// directory while skipping lock files. -// -// On Windows, if the normal copy fails (e.g. file locked by Chrome), -// it falls back to DuplicateHandle + FileMapping to bypass exclusive locks. +// Acquire copies a browser file (or directory) from src to dst with the snapshot copier. func (s *Session) Acquire(src, dst string, isDir bool) error { - if isDir { - return copyDir(src, dst, "lock") - } - - // Try normal copy first - err := copyFile(src, dst) - if err != nil { - // Only attempt locked-file fallback on Windows where Chrome holds exclusive locks. - // On other platforms, return the original error directly. - if runtime.GOOS != "windows" { - return fmt.Errorf("copy: %w", err) - } - if err2 := copyLocked(src, dst); err2 != nil { - return errors.Join( - fmt.Errorf("copy: %w", err), - fmt.Errorf("locked copy: %w", err2), - ) - } - } - - // Copy SQLite WAL/SHM companion files if present - var walErrs []error - for _, suffix := range []string{"-wal", "-shm"} { - walSrc := src + suffix - if isFileExists(walSrc) { - if err := copyFile(walSrc, dst+suffix); err != nil { - walErrs = append(walErrs, fmt.Errorf("copy %s: %w", suffix, err)) - } - } - } - return errors.Join(walErrs...) + return snapshot.Copy(src, dst, isDir) } // Cleanup removes the session's temporary directory and all its contents. diff --git a/go.mod b/go.mod index 4fdb067..8c5ea32 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,6 @@ require ( github.com/moond4rk/binarycookies v1.0.3 github.com/moond4rk/keychainbreaker v0.2.6 github.com/moond4rk/plist v1.2.2 - github.com/otiai10/copy v1.14.1 github.com/ppacher/go-dbus-keyring v1.0.1 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 @@ -27,7 +26,6 @@ require ( github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect - github.com/otiai10/mint v1.6.3 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.0 // indirect diff --git a/go.sum b/go.sum index e587949..2c2b5c6 100644 --- a/go.sum +++ b/go.sum @@ -32,10 +32,6 @@ github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/otiai10/copy v1.14.1 h1:5/7E6qsUMBaH5AnQ0sSLzzTg1oTECmcCmT6lvF45Na8= -github.com/otiai10/copy v1.14.1/go.mod h1:oQwrEDDOci3IM8dJF0d8+jnbfPDllW6vUjNc3DoZm9I= -github.com/otiai10/mint v1.6.3 h1:87qsV/aw1F5as1eH1zS/yqHY85ANKVMgkDrf9rcxbQs= -github.com/otiai10/mint v1.6.3/go.mod h1:MJm72SBthJjz8qhefc4z1PYEieWmy8Bku7CjcAqyUSM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/ppacher/go-dbus-keyring v1.0.1 h1:dM4dMfP5w9MxY+foFHCQiN7izEGpFdKr3tZeMGmvqD0= github.com/ppacher/go-dbus-keyring v1.0.1/go.mod h1:JEmkRwBVPBFkOHedAsoZALWmhNJxR/R/ykkFpbEHtGE= diff --git a/internal/snapshot/copy.go b/internal/snapshot/copy.go new file mode 100644 index 0000000..37ecb39 --- /dev/null +++ b/internal/snapshot/copy.go @@ -0,0 +1,127 @@ +package snapshot + +import ( + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "runtime" + "strings" +) + +// Copy copies a file together with its SQLite -wal and -shm sidecars, or a directory minus every entry named *lock. +func Copy(src, dst string, isDir bool) error { + if isDir { + return copyDir(src, dst) + } + if err := copyFile(src, dst); err != nil { + // Chromium on Windows holds Cookies under an exclusive lock that a plain read cannot pass. + if runtime.GOOS != "windows" { + return fmt.Errorf("copy: %w", err) + } + if lockedErr := copyLocked(src, dst); lockedErr != nil { + return errors.Join(fmt.Errorf("copy: %w", err), fmt.Errorf("locked copy: %w", lockedErr)) + } + } + + var sidecarErrs []error + for _, suffix := range []string{"-wal", "-shm"} { + if !isFile(src + suffix) { + continue + } + if err := copyFile(src+suffix, dst+suffix); err != nil { + sidecarErrs = append(sidecarErrs, fmt.Errorf("copy %s: %w", suffix, err)) + } + } + return errors.Join(sidecarErrs...) +} + +func copyFile(src, dst string) error { + data, err := os.ReadFile(src) + if err != nil { + return err + } + return os.WriteFile(dst, data, 0o600) +} + +func copyDir(src, dst string) error { + info, err := os.Lstat(src) + if err != nil { + return err + } + return copyEntry(src, dst, info) +} + +func copyEntry(src, dst string, info fs.FileInfo) error { + switch { + case info.Mode()&fs.ModeSymlink != 0: + target, err := os.Readlink(src) + if err != nil { + return err + } + return os.Symlink(target, dst) + case info.IsDir(): + return copyChildren(src, dst) + case info.Mode().IsRegular(): + return copyRegular(src, dst) + default: + return nil + } +} + +func copyChildren(src, dst string) error { + if err := os.MkdirAll(dst, 0o700); err != nil { + return err + } + entries, err := os.ReadDir(src) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + for _, e := range entries { + child := filepath.Join(src, e.Name()) + // LevelDB's LOCK is held by the running browser and means nothing in a copy; any name ending in lock is skipped. + if strings.HasSuffix(strings.ToLower(child), "lock") { + continue + } + info, err := e.Info() + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + return err + } + if err := copyEntry(child, filepath.Join(dst, e.Name()), info); err != nil { + return err + } + } + return nil +} + +// copyRegular skips a file that vanished after its directory was listed: a live LevelDB compacts while it is copied. +func copyRegular(src, dst string) error { + in, err := os.Open(src) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + defer in.Close() + + out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) + if err != nil { + return err + } + _, err = io.Copy(out, in) + return errors.Join(err, out.Close()) +} + +func isFile(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} diff --git a/internal/snapshot/copy_other.go b/internal/snapshot/copy_other.go new file mode 100644 index 0000000..ad195a3 --- /dev/null +++ b/internal/snapshot/copy_other.go @@ -0,0 +1,10 @@ +//go:build !windows + +package snapshot + +import "errors" + +// copyLocked exists for the build only: file locks outside Windows are advisory and never block a reader. +func copyLocked(_, _ string) error { + return errors.New("locked file copy not supported on this platform") +} diff --git a/internal/snapshot/copy_test.go b/internal/snapshot/copy_test.go new file mode 100644 index 0000000..69dd9aa --- /dev/null +++ b/internal/snapshot/copy_test.go @@ -0,0 +1,74 @@ +package snapshot + +import ( + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCopy_SkipsEveryEntryEndingInLock(t *testing.T) { + src := t.TempDir() + for _, name := range []string{"LOCK", "db.lock", "Block", "LOCKED", "000003.log"} { + writeFile(t, filepath.Join(src, name), []byte(name)) + } + writeFile(t, filepath.Join(src, "unlock", "inner"), []byte("inner")) + + dst := filepath.Join(t.TempDir(), "leveldb") + require.NoError(t, Copy(src, dst, true)) + + for _, skipped := range []string{"LOCK", "db.lock", "Block"} { + assert.NoFileExists(t, filepath.Join(dst, skipped)) + } + assert.NoDirExists(t, filepath.Join(dst, "unlock"), "a directory whose name ends in lock is skipped whole") + assert.FileExists(t, filepath.Join(dst, "LOCKED")) + assert.FileExists(t, filepath.Join(dst, "000003.log")) +} + +func TestCopy_MissingSourceFails(t *testing.T) { + dir := t.TempDir() + require.Error(t, Copy(filepath.Join(dir, "missing"), filepath.Join(dir, "file"), false)) + require.Error(t, Copy(filepath.Join(dir, "missing"), filepath.Join(dir, "dir"), true)) +} + +func TestCopy_FileWithoutSidecarsCopiesOnlyTheFile(t *testing.T) { + src := filepath.Join(t.TempDir(), "History") + writeFile(t, src, []byte("history")) + + dst := filepath.Join(t.TempDir(), "History") + require.NoError(t, Copy(src, dst, false)) + + got, err := os.ReadFile(dst) + require.NoError(t, err) + assert.Equal(t, "history", string(got)) + assert.NoFileExists(t, dst+"-wal") + assert.NoFileExists(t, dst+"-shm") +} + +func TestCopy_SymlinkInADirectoryStaysALink(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("creating symlinks needs extra privileges on Windows") + } + src := t.TempDir() + writeFile(t, filepath.Join(src, "target"), []byte("target")) + require.NoError(t, os.Symlink("target", filepath.Join(src, "link"))) + + dst := filepath.Join(t.TempDir(), "copy") + require.NoError(t, Copy(src, dst, true)) + + got, err := os.Readlink(filepath.Join(dst, "link")) + require.NoError(t, err) + assert.Equal(t, "target", got) +} + +// A directory removed between its parent's listing and its own copy is copied as empty instead of failing the tree. +func TestCopyChildren_VanishedDirectoryCopiesAsEmpty(t *testing.T) { + dst := filepath.Join(t.TempDir(), "Origins") + require.NoError(t, copyChildren(filepath.Join(t.TempDir(), "gone"), dst)) + entries, err := os.ReadDir(dst) + require.NoError(t, err) + assert.Empty(t, entries) +} diff --git a/internal/snapshot/copy_windows.go b/internal/snapshot/copy_windows.go new file mode 100644 index 0000000..d22b2fb --- /dev/null +++ b/internal/snapshot/copy_windows.go @@ -0,0 +1,17 @@ +//go:build windows + +package snapshot + +import ( + "os" + + "github.com/moond4rk/hackbrowserdata/internal/winapi" +) + +func copyLocked(src, dst string) error { + data, err := winapi.ReadLockedFile(src) + if err != nil { + return err + } + return os.WriteFile(dst, data, 0o600) +} diff --git a/internal/snapshot/copy_windows_test.go b/internal/snapshot/copy_windows_test.go new file mode 100644 index 0000000..e8917ea --- /dev/null +++ b/internal/snapshot/copy_windows_test.go @@ -0,0 +1,62 @@ +//go:build windows + +package snapshot + +import ( + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCopy_FallsBackToTheLockedRead(t *testing.T) { + src := filepath.Join(t.TempDir(), "cookies.db") + testData := []byte("cookie data") + require.NoError(t, os.WriteFile(src, testData, 0o644)) + + handle := openExclusive(t, src) + defer syscall.CloseHandle(handle) + + dst := filepath.Join(t.TempDir(), "cookies.db") + require.NoError(t, Copy(src, dst, false), "Copy should succeed via the locked-file fallback") + + copied, err := os.ReadFile(dst) + require.NoError(t, err) + assert.Equal(t, testData, copied) +} + +func TestCopy_PlainWhenNotLocked(t *testing.T) { + src := filepath.Join(t.TempDir(), "unlocked.db") + testData := []byte("unlocked data") + require.NoError(t, os.WriteFile(src, testData, 0o644)) + + dst := filepath.Join(t.TempDir(), "unlocked.db") + require.NoError(t, Copy(src, dst, false)) + + copied, err := os.ReadFile(dst) + require.NoError(t, err) + assert.Equal(t, testData, copied) +} + +// openExclusive opens a file with exclusive lock (dwShareMode=0), +// simulating Chrome's PRAGMA locking_mode=EXCLUSIVE behavior. +func openExclusive(t *testing.T, path string) syscall.Handle { + t.Helper() + srcPtr, err := syscall.UTF16PtrFromString(path) + require.NoError(t, err) + + handle, err := syscall.CreateFile( + srcPtr, + syscall.GENERIC_READ|syscall.GENERIC_WRITE, + 0, // exclusive: no sharing + nil, + syscall.OPEN_EXISTING, + syscall.FILE_ATTRIBUTE_NORMAL, + 0, + ) + require.NoError(t, err) + return handle +} diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go new file mode 100644 index 0000000..090fdf9 --- /dev/null +++ b/internal/snapshot/snapshot.go @@ -0,0 +1,132 @@ +// Package snapshot holds the point-in-time copies of browser files that extractors read instead of a live profile. +package snapshot + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +type File struct { + DirID string // the user data dir's ID; also the snapshot it lands in + From string // absolute path of the user data dir it is copied from + Rel string // slash-separated path relative to From, and to the snapshot + IsDir bool +} + +// Dir is a snapshot directory, laid out as //: one Snapshot per user data dir. +type Dir struct { + path string + temp bool + failed map[string]error // keyed by the cleaned / path, so any spelling of a file finds its failure +} + +// Temp creates a private temporary snapshot directory, which Close removes. +func Temp() (*Dir, error) { + path, err := os.MkdirTemp("", "hbd-snapshot-*") + if err != nil { + return nil, fmt.Errorf("create snapshot dir: %w", err) + } + return &Dir{path: path, temp: true, failed: make(map[string]error)}, nil +} + +// Open uses an existing snapshot directory in place; Close leaves it there. +func Open(path string) *Dir { + return &Dir{path: path, failed: make(map[string]error)} +} + +// Unzip extracts an archive into a temporary snapshot directory, rejecting entries that would land outside it. +func Unzip(src string) (*Dir, error) { + d, err := Temp() + if err != nil { + return nil, err + } + if err := unzip(src, d.path); err != nil { + return nil, errors.Join(err, d.Close()) + } + return d, nil +} + +func (d *Dir) Path() string { + return d.path +} + +// Capture keeps a file's own failure for Snapshot.Path instead of stopping the rest of the capture. +func (d *Dir) Capture(ctx context.Context, files []File) error { + if err := os.MkdirAll(d.path, 0o700); err != nil { + return fmt.Errorf("snapshot dir: %w", err) + } + for _, f := range files { + if err := ctx.Err(); err != nil { + return fmt.Errorf("capture: %w", err) + } + local, err := localPath(f.DirID, f.Rel) + if err != nil { + continue // Snapshot.Path reports the same error for this file + } + if err := d.capture(local, f); err != nil { + d.failed[local] = err + } else { + delete(d.failed, local) + } + } + return nil +} + +func (d *Dir) capture(local string, f File) error { + dst := filepath.Join(d.path, local) + if err := os.MkdirAll(filepath.Dir(dst), 0o700); err != nil { + return fmt.Errorf("create %s: %w", filepath.Dir(dst), err) + } + return Copy(filepath.Join(f.From, filepath.FromSlash(f.Rel)), dst, f.IsDir) +} + +func (d *Dir) Snapshot(dirID string) Snapshot { + return Snapshot{dirID: dirID, root: d.path, failed: d.failed} +} + +// Close removes a temporary snapshot directory and leaves an opened one in place. +func (d *Dir) Close() error { + if !d.temp { + return nil + } + if err := os.RemoveAll(d.path); err != nil { + return fmt.Errorf("remove snapshot dir %s: %w", d.path, err) + } + return nil +} + +type Snapshot struct { + dirID string + root string + failed map[string]error +} + +// Path returns rel's location in the snapshot, or why it is not there: fs.ErrNotExist when it was never captured +// or had vanished before Capture reached it, else the copy's error. +func (s Snapshot) Path(rel string) (string, error) { + local, err := localPath(s.dirID, rel) + if err != nil { + return "", err + } + if err, ok := s.failed[local]; ok { + return "", err + } + p := filepath.Join(s.root, local) + if _, err := os.Lstat(p); err != nil { + return "", err + } + return p, nil +} + +// localPath keeps rel inside its own user data dir's snapshot, not merely inside the snapshot directory. +func localPath(dirID, rel string) (string, error) { + r := filepath.FromSlash(rel) + if !filepath.IsLocal(dirID) || dirID == "." || strings.ContainsAny(dirID, `/\`) || (r != "" && !filepath.IsLocal(r)) { + return "", fmt.Errorf("%q in %q is outside the snapshot directory", rel, dirID) + } + return filepath.Join(dirID, r), nil +} diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go new file mode 100644 index 0000000..90c96fe --- /dev/null +++ b/internal/snapshot/snapshot_test.go @@ -0,0 +1,171 @@ +package snapshot + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// userDataDir builds a Chromium-shaped source tree with a WAL database and a LevelDB directory. +func userDataDir(t *testing.T) string { + t.Helper() + root := t.TempDir() + for rel, data := range map[string]string{ + "Local State": "{}", + "Default/Network/Cookies": "db", + "Default/Network/Cookies-wal": "wal", + "Default/Network/Cookies-shm": "shm", + "Default/Local Storage/leveldb/CURRENT": "MANIFEST-000001", + "Default/Local Storage/leveldb/LOCK": "", + "Default/Local Storage/leveldb/000003.log": "log", + } { + writeFile(t, filepath.Join(root, filepath.FromSlash(rel)), []byte(data)) + } + return root +} + +func TestTemp_IsPrivateAndCloseRemovesIt(t *testing.T) { + d, err := Temp() + require.NoError(t, err) + info, err := os.Stat(d.Path()) + require.NoError(t, err) + if runtime.GOOS != "windows" { + assert.Equal(t, fs.FileMode(0o700), info.Mode().Perm()) + } + + require.NoError(t, d.Close()) + assert.NoDirExists(t, d.Path()) +} + +func TestOpen_ReadsInPlaceAndCloseLeavesIt(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "chrome", "Local State"), []byte("{}")) + + d := Open(dir) + p, err := d.Snapshot("chrome").Path("Local State") + require.NoError(t, err) + assert.Equal(t, filepath.Join(dir, "chrome", "Local State"), p) + + require.NoError(t, d.Close()) + assert.FileExists(t, p) +} + +func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) { + from := userDataDir(t) + d, err := Temp() + require.NoError(t, err) + defer d.Close() + + require.NoError(t, d.Capture(context.Background(), []File{ + {DirID: "chrome", From: from, Rel: "Local State"}, + {DirID: "chrome", From: from, Rel: "Default/Network/Cookies"}, + {DirID: "chrome", From: from, Rel: "Default/Local Storage/leveldb", IsDir: true}, + })) + + s := d.Snapshot("chrome") + cookies, err := s.Path("Default/Network/Cookies") + require.NoError(t, err) + assert.Equal(t, filepath.Join(d.Path(), "chrome", "Default", "Network", "Cookies"), cookies) + for suffix, want := range map[string]string{"-wal": "wal", "-shm": "shm"} { + got, err := os.ReadFile(cookies + suffix) + require.NoError(t, err) + assert.Equal(t, want, string(got)) + } + + leveldb, err := s.Path("Default/Local Storage/leveldb") + require.NoError(t, err) + assert.FileExists(t, filepath.Join(leveldb, "CURRENT")) + assert.FileExists(t, filepath.Join(leveldb, "000003.log")) + assert.NoFileExists(t, filepath.Join(leveldb, "LOCK")) +} + +func TestCapture_KeepsGoingPastFailedFiles(t *testing.T) { + from := userDataDir(t) + d, err := Temp() + require.NoError(t, err) + defer d.Close() + + require.NoError(t, d.Capture(context.Background(), []File{ + {DirID: "chrome", From: from, Rel: "Default/History"}, // vanished before Capture reached it + {DirID: "chrome", From: from, Rel: "Default/Network"}, // a directory read as a file, so the copy fails + {DirID: "chrome", From: from, Rel: "Local State"}, + })) + + s := d.Snapshot("chrome") + _, err = s.Path("Default/History") + require.ErrorIs(t, err, fs.ErrNotExist) + + _, err = s.Path("Default/Network") + require.Error(t, err) + require.NotErrorIs(t, err, fs.ErrNotExist, "a failed copy reads back as its own error") + + _, err = s.Path("Local State") + require.NoError(t, err, "one file's failure does not stop the rest") +} + +func TestCapture_StopsWhenCancelled(t *testing.T) { + from := userDataDir(t) + d, err := Temp() + require.NoError(t, err) + defer d.Close() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + err = d.Capture(ctx, []File{{DirID: "chrome", From: from, Rel: "Local State"}}) + require.ErrorIs(t, err, context.Canceled) + + _, err = d.Snapshot("chrome").Path("Local State") + require.ErrorIs(t, err, fs.ErrNotExist) +} + +func TestCapture_StaysInsideItsOwnSnapshot(t *testing.T) { + from := userDataDir(t) + d, err := Temp() + require.NoError(t, err) + defer d.Close() + + require.NoError(t, d.Capture(context.Background(), []File{ + {DirID: "chrome", From: from, Rel: "../edge/Local State"}, + {DirID: "../chrome", From: from, Rel: "Local State"}, + {DirID: "chrome/sub", From: from, Rel: "Local State"}, + {DirID: ".", From: from, Rel: "Local State"}, + {DirID: "", From: from, Rel: "Local State"}, + })) + + _, err = d.Snapshot("chrome").Path("../edge/Local State") + require.Error(t, err) + entries, err := os.ReadDir(d.Path()) + require.NoError(t, err) + assert.Empty(t, entries, "nothing may be written outside a file's own snapshot") +} + +func TestSnapshot_UncapturedFileIsNotExist(t *testing.T) { + d, err := Temp() + require.NoError(t, err) + defer d.Close() + + _, err = d.Snapshot("chrome").Path("Default/Login Data") + require.ErrorIs(t, err, fs.ErrNotExist) +} + +func TestCapture_ALaterCaptureReplacesAnEarlierFailure(t *testing.T) { + from := t.TempDir() + d, err := Temp() + require.NoError(t, err) + defer d.Close() + + require.NoError(t, d.Capture(context.Background(), []File{{DirID: "chrome", From: from, Rel: "Default/History"}})) + _, err = d.Snapshot("chrome").Path("Default/./History") + require.ErrorIs(t, err, fs.ErrNotExist, "a failure is found under any spelling of the path") + + writeFile(t, filepath.Join(from, "Default", "History"), []byte("history")) + require.NoError(t, d.Capture(context.Background(), []File{{DirID: "chrome", From: from, Rel: "Default/./History"}})) + _, err = d.Snapshot("chrome").Path("Default/History") + require.NoError(t, err) +} diff --git a/internal/snapshot/zip.go b/internal/snapshot/zip.go new file mode 100644 index 0000000..4a263e6 --- /dev/null +++ b/internal/snapshot/zip.go @@ -0,0 +1,173 @@ +package snapshot + +import ( + "archive/zip" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" +) + +// Zip writes the snapshot directory to dst through a temp file beside it, so a failed archive leaves no partial file. +func (d *Dir) Zip(dst string) (err error) { + target, existing, err := zipTarget(dst) + if err != nil { + return err + } + tmp, err := createBeside(target) + if err != nil { + return err + } + defer func() { + if err != nil { + os.Remove(tmp.Name()) + } + }() + + if err := writeZip(tmp, d.path); err != nil { + return errors.Join(err, tmp.Close()) + } + if existing != nil { + if err := tmp.Chmod(existing.Mode().Perm()); err != nil { + return errors.Join(fmt.Errorf("keep the mode of %s: %w", dst, err), tmp.Close()) + } + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("close zip %s: %w", tmp.Name(), err) + } + if err := os.Rename(tmp.Name(), target); err != nil { + return fmt.Errorf("move zip into place: %w", err) + } + return nil +} + +// zipTarget follows a symlinked dst and reports an archive already there, so replacing it keeps the link and the +// mode that writing through os.Create would have kept. +func zipTarget(dst string) (string, fs.FileInfo, error) { + target := dst + if resolved, err := filepath.EvalSymlinks(dst); err == nil { + target = resolved + } + info, err := os.Stat(target) + if errors.Is(err, fs.ErrNotExist) { + return target, nil, nil + } + if err != nil { + return "", nil, fmt.Errorf("create %s: %w", dst, err) + } + if info.IsDir() { + return "", nil, fmt.Errorf("create %s: is a directory", dst) + } + return target, info, nil +} + +// createBeside keeps os.Create's umask-governed mode for a new archive, which os.CreateTemp would force to 0600. +func createBeside(dst string) (*os.File, error) { + dir, base := filepath.Split(dst) + for i := 0; i < 100; i++ { + name := filepath.Join(dir, fmt.Sprintf("%s.%d-%d.tmp", base, os.Getpid(), i)) + f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o666) + if errors.Is(err, fs.ErrExist) { + continue + } + if err != nil { + return nil, fmt.Errorf("create %s: %w", dst, err) + } + return f, nil + } + return nil, fmt.Errorf("create %s: no free temp name beside it", dst) +} + +func writeZip(w io.Writer, root string) error { + zw := zip.NewWriter(w) + walkErr := filepath.WalkDir(root, func(p string, e fs.DirEntry, err error) error { + if err != nil { + return err + } + if e.IsDir() { + return nil + } + rel, err := filepath.Rel(root, p) + if err != nil { + return err + } + return addZipEntry(zw, p, filepath.ToSlash(rel)) + }) + if walkErr != nil { + return errors.Join(fmt.Errorf("zip %s: %w", root, walkErr), zw.Close()) + } + if err := zw.Close(); err != nil { + return fmt.Errorf("close zip: %w", err) + } + return nil +} + +func addZipEntry(zw *zip.Writer, path, name string) error { + w, err := zw.Create(name) + if err != nil { + return err + } + src, err := os.Open(path) + if err != nil { + return err + } + defer src.Close() + _, err = io.Copy(w, src) + return err +} + +func unzip(src, destDir string) error { + r, err := zip.OpenReader(src) + if err != nil { + return fmt.Errorf("open zip %s: %w", src, err) + } + defer r.Close() + + root := filepath.Clean(destDir) + for _, f := range r.File { + target := filepath.Join(root, filepath.FromSlash(f.Name)) + if target != root && !strings.HasPrefix(target, root+string(os.PathSeparator)) { + return fmt.Errorf("zip entry %q escapes destination", f.Name) + } + if f.FileInfo().IsDir() { + if err := os.MkdirAll(target, 0o700); err != nil { + return err + } + continue + } + if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { + return err + } + if err := writeZipEntry(f, target); err != nil { + return err + } + } + return nil +} + +func writeZipEntry(f *zip.File, target string) (err error) { + rc, err := f.Open() + if err != nil { + return err + } + defer rc.Close() + + out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + if err != nil { + return err + } + defer func() { err = errors.Join(err, out.Close()) }() + + for { + _, err := io.CopyN(out, rc, 1<<20) + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + } +} diff --git a/internal/snapshot/zip_test.go b/internal/snapshot/zip_test.go new file mode 100644 index 0000000..e87d344 --- /dev/null +++ b/internal/snapshot/zip_test.go @@ -0,0 +1,197 @@ +package snapshot + +import ( + "archive/zip" + "bytes" + "io/fs" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestZipUnzip_RoundTrip(t *testing.T) { + files := map[string][]byte{ + "empty.txt": {}, + "small.txt": []byte("hello"), + "chrome/Default/Network/Cookies": []byte("cookie-bytes"), + "sub/big.bin": bytes.Repeat([]byte("A"), 3<<20), // exercises the chunked copy loop + } + src := t.TempDir() + for rel, data := range files { + writeFile(t, filepath.Join(src, filepath.FromSlash(rel)), data) + } + + archive := filepath.Join(t.TempDir(), "out.zip") + require.NoError(t, Open(src).Zip(archive)) + + zr, err := zip.OpenReader(archive) + require.NoError(t, err) + for _, f := range zr.File { + assert.NotContains(t, f.Name, `\`, "zip entry names are forward-slash") + } + require.NoError(t, zr.Close()) + + d, err := Unzip(archive) + require.NoError(t, err) + for rel, want := range files { + got, err := os.ReadFile(filepath.Join(d.Path(), filepath.FromSlash(rel))) + require.NoError(t, err, rel) + assert.True(t, bytes.Equal(want, got), "%s: got %d bytes, want %d", rel, len(got), len(want)) + } + require.NoError(t, d.Close()) + assert.NoDirExists(t, d.Path()) +} + +func TestUnzip_RejectsZipSlipAndCleansUp(t *testing.T) { + tmp := privateTempRoot(t) + archive := zipWith(t, "../escape.txt") + + _, err := Unzip(archive) + require.Error(t, err) + entries, err := os.ReadDir(tmp) + require.NoError(t, err) + assert.Empty(t, entries, "a rejected archive leaves neither the escaped file nor the snapshot directory behind") +} + +func TestUnzip_RejectsASiblingSharingTheRootPrefix(t *testing.T) { + parent := t.TempDir() + root := filepath.Join(parent, "snap") + + require.Error(t, unzip(zipWith(t, "../snapx/evil.txt"), root)) + assert.NoFileExists(t, filepath.Join(parent, "snapx", "evil.txt")) +} + +func TestZip_FailureLeavesNoFile(t *testing.T) { + out := t.TempDir() + err := Open(filepath.Join(t.TempDir(), "missing")).Zip(filepath.Join(out, "browser-data.zip")) + require.Error(t, err) + entries, err := os.ReadDir(out) + require.NoError(t, err) + assert.Empty(t, entries, "neither the archive nor its temp file may survive a failed zip") +} + +func TestZip_FailureKeepsAnExistingArchive(t *testing.T) { + out := t.TempDir() + archive := filepath.Join(out, "browser-data.zip") + writeFile(t, archive, []byte("precious")) + + require.Error(t, Open(filepath.Join(t.TempDir(), "missing")).Zip(archive)) + got, err := os.ReadFile(archive) + require.NoError(t, err) + assert.Equal(t, "precious", string(got)) + entries, err := os.ReadDir(out) + require.NoError(t, err) + assert.Len(t, entries, 1, "no temp file may survive a failed zip") +} + +func TestZip_IntoADirectoryFailsBeforeWriting(t *testing.T) { + out := t.TempDir() + require.Error(t, Open(snapshotSource(t)).Zip(out)) + entries, err := os.ReadDir(out) + require.NoError(t, err) + assert.Empty(t, entries) +} + +func TestZip_ModeMatchesOSCreateAndSurvivesReplacement(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX permission bits") + } + src := snapshotSource(t) + out := t.TempDir() + probe, err := os.Create(filepath.Join(out, "probe")) + require.NoError(t, err) + require.NoError(t, probe.Close()) + want, err := os.Stat(probe.Name()) + require.NoError(t, err) + + fresh := filepath.Join(out, "fresh.zip") + require.NoError(t, Open(src).Zip(fresh)) + got, err := os.Stat(fresh) + require.NoError(t, err) + assert.Equal(t, want.Mode().Perm(), got.Mode().Perm(), "a new archive gets the mode os.Create gives a file") + + private := filepath.Join(out, "private.zip") + writeFile(t, private, []byte("old")) + require.NoError(t, os.Chmod(private, 0o600)) + require.NoError(t, Open(src).Zip(private)) + got, err = os.Stat(private) + require.NoError(t, err) + assert.Equal(t, fs.FileMode(0o600), got.Mode().Perm(), "a replaced archive keeps its mode") +} + +func TestZip_WritesThroughASymlinkedArchive(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("creating symlinks needs extra privileges on Windows") + } + out := t.TempDir() + target := filepath.Join(out, "real.zip") + writeFile(t, target, []byte("old")) + link := filepath.Join(out, "link.zip") + require.NoError(t, os.Symlink("real.zip", link)) + + require.NoError(t, Open(snapshotSource(t)).Zip(link)) + info, err := os.Lstat(link) + require.NoError(t, err) + assert.NotZero(t, info.Mode()&fs.ModeSymlink, "the link stays a link") + zr, err := zip.OpenReader(target) + require.NoError(t, err) + defer zr.Close() + assert.Len(t, zr.File, 1, "the archive lands in the link's target") +} + +// snapshotSource is a snapshot directory holding one captured file. +func snapshotSource(t *testing.T) string { + t.Helper() + src := t.TempDir() + writeFile(t, filepath.Join(src, "chrome", "Local State"), []byte("{}")) + return src +} + +func zipWith(t *testing.T, names ...string) string { + t.Helper() + archive := filepath.Join(t.TempDir(), "test.zip") + f, err := os.Create(archive) + require.NoError(t, err) + zw := zip.NewWriter(f) + for _, name := range names { + w, err := zw.Create(name) + require.NoError(t, err) + _, err = w.Write([]byte(name)) + require.NoError(t, err) + } + require.NoError(t, zw.Close()) + require.NoError(t, f.Close()) + return archive +} + +func TestZip_ReplacesAnExistingArchive(t *testing.T) { + archive := filepath.Join(t.TempDir(), "browser-data.zip") + writeFile(t, archive, []byte("stale")) + + require.NoError(t, Open(snapshotSource(t)).Zip(archive)) + zr, err := zip.OpenReader(archive) + require.NoError(t, err) + defer zr.Close() + require.Len(t, zr.File, 1) + assert.Equal(t, "chrome/Local State", zr.File[0].Name) +} + +// privateTempRoot points os.TempDir at a fresh directory, so a test can see everything Temp leaves behind. +func privateTempRoot(t *testing.T) string { + t.Helper() + dir := t.TempDir() + for _, env := range []string{"TMPDIR", "TMP", "TEMP"} { + t.Setenv(env, dir) + } + return dir +} + +func writeFile(t *testing.T, path string, data []byte) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, data, 0o600)) +} diff --git a/filemanager/copy_windows.go b/internal/winapi/lockedfile_windows.go similarity index 86% rename from filemanager/copy_windows.go rename to internal/winapi/lockedfile_windows.go index 31b31bf..9942a29 100644 --- a/filemanager/copy_windows.go +++ b/internal/winapi/lockedfile_windows.go @@ -1,6 +1,6 @@ //go:build windows -package filemanager +package winapi import ( "fmt" @@ -8,11 +8,9 @@ import ( "strings" "golang.org/x/sys/windows" - - "github.com/moond4rk/hackbrowserdata/internal/winapi" ) -// copyLocked copies a file that is locked by another process (e.g., Chrome's +// ReadLockedFile reads a file that is locked by another process (e.g., Chrome's // Cookies database with PRAGMA locking_mode=EXCLUSIVE). // // Approach: DuplicateHandle + FileMapping @@ -20,22 +18,20 @@ import ( // 2. Find the handle matching the target file path // 3. Duplicate that handle into our process via DuplicateHandle // 4. Read file content through memory-mapped I/O (CreateFileMapping + MapViewOfFile) -// 5. Write content to destination // // This requires only normal user privileges (no admin needed). -func copyLocked(src, dst string) error { - handle, err := findFileHandle(src) +func ReadLockedFile(path string) ([]byte, error) { + handle, err := findFileHandle(path) if err != nil { - return fmt.Errorf("find file handle for %s: %w", src, err) + return nil, fmt.Errorf("find file handle for %s: %w", path, err) } defer windows.CloseHandle(handle) data, err := readFileContent(handle) if err != nil { - return fmt.Errorf("read via file mapping: %w", err) + return nil, fmt.Errorf("read via file mapping: %w", err) } - - return os.WriteFile(dst, data, 0o600) + return data, nil } // findFileHandle enumerates all system handles, finds the one matching the @@ -49,7 +45,7 @@ func findFileHandle(targetPath string) (windows.Handle, error) { targetSuffix := extractStableSuffix(targetPath) currentProcess := windows.CurrentProcess() - handles, err := winapi.QuerySystemHandles() + handles, err := QuerySystemHandles() if err != nil { return 0, err } @@ -82,13 +78,13 @@ func findFileHandle(targetPath string) (windows.Handle, error) { } // Verify it's a disk file (not a pipe, device, etc.) - if winapi.GetFileType(dupHandle) != winapi.FileTypeDisk { + if GetFileType(dupHandle) != FileTypeDisk { _ = windows.CloseHandle(dupHandle) continue } // Get the file path and check if it matches our target - name, err := winapi.GetFinalPathName(dupHandle) + name, err := GetFinalPathName(dupHandle) if err != nil { _ = windows.CloseHandle(dupHandle) continue @@ -109,7 +105,7 @@ func findFileHandle(targetPath string) (windows.Handle, error) { // written but not yet checkpointed to the main file. Falls back to ReadFile // if FileMapping fails. func readFileContent(handle windows.Handle) ([]byte, error) { - fileSize, err := winapi.GetFileSizeEx(handle) + fileSize, err := GetFileSizeEx(handle) if err != nil { return nil, err } @@ -120,7 +116,7 @@ func readFileContent(handle windows.Handle) ([]byte, error) { size := int(fileSize) // Try FileMapping first — reads from kernel file cache, includes WAL data - if data, err := winapi.MapFile(handle, size); err == nil { + if data, err := MapFile(handle, size); err == nil { return data, nil } diff --git a/internal/winapi/lockedfile_windows_test.go b/internal/winapi/lockedfile_windows_test.go new file mode 100644 index 0000000..7c3359b --- /dev/null +++ b/internal/winapi/lockedfile_windows_test.go @@ -0,0 +1,106 @@ +//go:build windows + +package winapi + +import ( + "bytes" + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestReadLockedFile_ExclusiveLock(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "locked.db") + testData := []byte("this is locked file content") + + require.NoError(t, os.WriteFile(src, testData, 0o644)) + + handle := openExclusive(t, src) + defer syscall.CloseHandle(handle) + + _, err := os.ReadFile(src) + require.Error(t, err, "a plain read should fail on an exclusively locked file") + + data, err := ReadLockedFile(src) + require.NoError(t, err, "ReadLockedFile should bypass the exclusive lock") + assert.Equal(t, testData, data, "read content should match original") +} + +func TestReadLockedFile_WriteThenRead(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "modified.db") + + // Write initial data + require.NoError(t, os.WriteFile(src, []byte("initial"), 0o644)) + + // Open exclusively and write more data through the handle + handle := openExclusive(t, src) + defer syscall.CloseHandle(handle) + + // Seek to end and write additional data + _, seekErr := syscall.Seek(handle, 0, 2) // SEEK_END + require.NoError(t, seekErr) + additional := []byte(" + appended data") + var written uint32 + writeErr := syscall.WriteFile(handle, additional, &written, nil) + require.NoError(t, writeErr) + require.Equal(t, uint32(len(additional)), written) + flushErr := syscall.FlushFileBuffers(handle) + require.NoError(t, flushErr) + + // ReadLockedFile should read the full content including appended data + data, err := ReadLockedFile(src) + require.NoError(t, err) + assert.Equal(t, "initial + appended data", string(data), + "should read complete content including data written after lock") +} + +func TestReadLockedFile_LargeFile(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "large.db") + + // Create a file similar in size to a real Cookies database (~64KB) + want := make([]byte, 65536) + for i := range want { + want[i] = byte(i % 256) + } + require.NoError(t, os.WriteFile(src, want, 0o644)) + + handle := openExclusive(t, src) + defer syscall.CloseHandle(handle) + + data, err := ReadLockedFile(src) + require.NoError(t, err) + assert.Len(t, data, len(want), "file sizes should match") + assert.True(t, bytes.Equal(want, data), "file content should match byte-for-byte") +} + +func TestReadLockedFile_FileNotFound(t *testing.T) { + _, err := ReadLockedFile("/nonexistent/file.db") + require.Error(t, err) +} + +// openExclusive opens a file with exclusive lock (dwShareMode=0), +// simulating Chrome's PRAGMA locking_mode=EXCLUSIVE behavior. +func openExclusive(t *testing.T, path string) syscall.Handle { + t.Helper() + srcPtr, err := syscall.UTF16PtrFromString(path) + require.NoError(t, err) + + handle, err := syscall.CreateFile( + srcPtr, + syscall.GENERIC_READ|syscall.GENERIC_WRITE, + 0, // exclusive: no sharing + nil, + syscall.OPEN_EXISTING, + syscall.FILE_ATTRIBUTE_NORMAL, + 0, + ) + require.NoError(t, err) + return handle +} diff --git a/rfcs/012-migration-roadmap.md b/rfcs/012-migration-roadmap.md index 25e3609..b9b553c 100644 --- a/rfcs/012-migration-roadmap.md +++ b/rfcs/012-migration-roadmap.md @@ -41,7 +41,7 @@ Leaves first, bottom-up along the dependency arrows ([RFC-002](002-package-layou ### Phase 4 — `snapshot` -- Build `internal/snapshot` ([RFC-007](007-snapshot-and-acquisition.md)): `Dir` (`Temp`, `Open`, `Unzip`, `Capture`, `Snapshot`, `Zip`, `Close`) and `Snapshot.Path` with the per-file error contract, the copier with the Windows locked-file fallback and SQLite sidecars, user-data-dir IDs in the layout, `manifest.json`, and `0700` temp snapshot directories removed on every exit path. +- Build `internal/snapshot` ([RFC-007](007-snapshot-and-acquisition.md)): `Dir` (`Temp`, `Open`, `Unzip`, `Capture`, `Snapshot`, `Zip`, `Close`) and `Snapshot.Path` with the per-file error contract, the copier with the Windows locked-file fallback and SQLite sidecars, user-data-dir IDs in the layout, and `0700` temp snapshot directories removed on every exit path. - Replace `otiai10/copy` with the snapshot copier ([RFC-010](010-dependencies.md)). - `archive` and `restore` move onto the snapshot; the archive-layout and `keys.json` compatibility tests guard both directions. @@ -58,6 +58,7 @@ Leaves first, bottom-up along the dependency arrows ([RFC-002](002-package-layou ### Phase 7 — Switch over - `dump`, `dumpkeys`, `archive`, `restore`, and `list` run on the pipeline. +- `archive` writes the snapshot `manifest.json` and `restore` reads it as its `Discovery` ([RFC-007](007-snapshot-and-acquisition.md)): writer and reader land together, so the round trip is tested end to end, and every earlier archive stays byte-identical to today's. - Validate-first ordering, `--keychain-pw-stdin` with the new precedence, the `-p` fixes, the safe `--zip` order, and the `restore` stamp fix ([RFC-009](009-cli-surface.md)). ### Phase 8 — Delete & document diff --git a/utils/fileutil/fileutil.go b/utils/fileutil/fileutil.go index 533dceb..8d6c072 100644 --- a/utils/fileutil/fileutil.go +++ b/utils/fileutil/fileutil.go @@ -3,12 +3,9 @@ package fileutil import ( "archive/zip" "bytes" - "errors" "fmt" - "io" "os" "path/filepath" - "strings" ) // FileExists checks if the file exists in the provided path. @@ -90,102 +87,3 @@ func writeFile(buffer *bytes.Buffer, filename string) error { return nil } - -// ZipDir writes every file under srcDir into a new zip at zipPath, preserving the relative directory -// layout with forward-slash entry names. Unlike CompressDir it neither flattens names nor deletes the -// source — it is the producer side of cross-host archive transport. -func ZipDir(zipPath, srcDir string) error { - out, err := os.Create(zipPath) - if err != nil { - return fmt.Errorf("create %s: %w", zipPath, err) - } - defer func() { _ = out.Close() }() - - zw := zip.NewWriter(out) - walkErr := filepath.WalkDir(srcDir, func(p string, d os.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if d.IsDir() { - return nil - } - rel, err := filepath.Rel(srcDir, p) - if err != nil { - return err - } - w, err := zw.Create(filepath.ToSlash(rel)) - if err != nil { - return err - } - src, err := os.Open(p) //nolint:gosec // G122: staging tree is created and populated by us - if err != nil { - return err - } - defer func() { _ = src.Close() }() - _, err = io.Copy(w, src) - return err - }) - if walkErr != nil { - _ = zw.Close() - return fmt.Errorf("zip %s: %w", srcDir, walkErr) - } - if err := zw.Close(); err != nil { - return fmt.Errorf("close zip %s: %w", zipPath, err) - } - return nil -} - -// Unzip extracts zipPath into destDir, rejecting any entry whose path would escape destDir (Zip-Slip) -// since a transported archive is not fully trusted. -func Unzip(zipPath, destDir string) error { - r, err := zip.OpenReader(zipPath) - if err != nil { - return fmt.Errorf("open zip %s: %w", zipPath, err) - } - defer func() { _ = r.Close() }() - - root := filepath.Clean(destDir) - for _, f := range r.File { - target := filepath.Join(root, filepath.FromSlash(f.Name)) - if target != root && !strings.HasPrefix(target, root+string(os.PathSeparator)) { - return fmt.Errorf("zip entry %q escapes destination", f.Name) - } - if f.FileInfo().IsDir() { - if err := os.MkdirAll(target, 0o755); err != nil { - return err - } - continue - } - if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { - return err - } - if err := writeZipEntry(f, target); err != nil { - return err - } - } - return nil -} - -func writeZipEntry(f *zip.File, target string) error { - rc, err := f.Open() - if err != nil { - return err - } - defer func() { _ = rc.Close() }() - - out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) - if err != nil { - return err - } - defer func() { _ = out.Close() }() - - for { - _, err := io.CopyN(out, rc, 1<<20) - if errors.Is(err, io.EOF) { - return nil - } - if err != nil { - return err - } - } -} diff --git a/utils/fileutil/fileutil_zip_test.go b/utils/fileutil/fileutil_zip_test.go deleted file mode 100644 index 9d144af..0000000 --- a/utils/fileutil/fileutil_zip_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package fileutil - -import ( - "archive/zip" - "bytes" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestZipDirUnzip_RoundTrip(t *testing.T) { - src := t.TempDir() - files := map[string][]byte{ - "empty.txt": {}, - "small.txt": []byte("hello"), - "Default/Network/Cookies": []byte("cookie-bytes"), - "sub/big.bin": bytes.Repeat([]byte("A"), 3<<20), // 3 MiB: exercises the chunked copy loop - } - for rel, data := range files { - p := filepath.Join(src, filepath.FromSlash(rel)) - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(p, data, 0o600); err != nil { - t.Fatal(err) - } - } - - zipPath := filepath.Join(t.TempDir(), "out.zip") - if err := ZipDir(zipPath, src); err != nil { - t.Fatalf("ZipDir: %v", err) - } - - zr, err := zip.OpenReader(zipPath) - if err != nil { - t.Fatalf("open zip: %v", err) - } - for _, f := range zr.File { - if strings.Contains(f.Name, `\`) { - t.Errorf("zip entry name must be forward-slash, got %q", f.Name) - } - } - if err := zr.Close(); err != nil { - t.Fatal(err) - } - - dst := t.TempDir() - if err := Unzip(zipPath, dst); err != nil { - t.Fatalf("Unzip: %v", err) - } - for rel, want := range files { - got, err := os.ReadFile(filepath.Join(dst, filepath.FromSlash(rel))) - if err != nil { - t.Errorf("missing %s after Unzip: %v", rel, err) - continue - } - if !bytes.Equal(got, want) { - t.Errorf("%s: content mismatch (got %d bytes, want %d)", rel, len(got), len(want)) - } - } -} - -func TestUnzip_RejectsZipSlip(t *testing.T) { - zipPath := filepath.Join(t.TempDir(), "evil.zip") - f, err := os.Create(zipPath) - if err != nil { - t.Fatal(err) - } - zw := zip.NewWriter(f) - w, err := zw.Create("../escape.txt") - if err != nil { - t.Fatal(err) - } - if _, err := w.Write([]byte("pwned")); err != nil { - t.Fatal(err) - } - if err := zw.Close(); err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - - if err := Unzip(zipPath, t.TempDir()); err == nil { - t.Fatal("Unzip must reject an entry that escapes the destination") - } -}