diff --git a/cmd/hack-browser-data/archive.go b/cmd/hack-browser-data/archive.go index 7b9c82a..3313640 100644 --- a/cmd/hack-browser-data/archive.go +++ b/cmd/hack-browser-data/archive.go @@ -9,7 +9,7 @@ import ( func newArchiveCommand() *cobra.Command { var ( - flags app.Flags + flags app.ArchiveFlags outputPath string ) @@ -23,12 +23,11 @@ func newArchiveCommand() *cobra.Command { if err != nil { return err } - discovery := app.Discover(options) - if len(discovery.Dirs) == 0 { - log.Warnf("no browsers found") + discovery := app.Discover(options.Target) + if foundNothing(command.ErrOrStderr(), discovery, "no browsers found") { return nil } - fileCount, err := app.Archive(command.Context(), discovery, options, outputPath) + fileCount, err := app.Archive(command.Context(), discovery, options.Categories, outputPath) if err != nil { return err } diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index 70164f6..d39f4a9 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -3,15 +3,18 @@ package main import ( "context" "io" + "os" "github.com/spf13/cobra" "github.com/moond4rk/hackbrowserdata/internal/app" - "github.com/moond4rk/hackbrowserdata/internal/log" ) func newDumpCommand() *cobra.Command { - var flags app.Flags + var ( + flags app.DumpFlags + keychain keychainFlags + ) command := &cobra.Command{ Use: "dump", @@ -22,7 +25,7 @@ func newDumpCommand() *cobra.Command { hack-browser-data dump -f cookie-editor hack-browser-data dump --zip`, RunE: func(command *cobra.Command, args []string) error { - return runDump(command.Context(), command.ErrOrStderr(), flags) + return runDump(command.Context(), command.ErrOrStderr(), flags, keychain) }, } @@ -31,33 +34,23 @@ func newDumpCommand() *cobra.Command { command.Flags().StringVarP(&flags.Format, "format", "f", "json", "output format: csv|json|cookie-editor") command.Flags().StringVarP(&flags.OutputDir, "dir", "d", "results", "output directory") command.Flags().StringVarP(&flags.ProfilePath, "profile-path", "p", "", "custom profile dir path, get with chrome://version") - addKeychainPasswordFlags(command, &flags) + addKeychainPasswordFlags(command, &keychain) command.Flags().BoolVar(&flags.Zip, "zip", false, "compress output to zip") return command } -func addKeychainPasswordFlags(command *cobra.Command, flags *app.Flags) { - command.Flags().StringVar(&flags.KeychainPassword, "keychain-pw", "", "macOS keychain password (visible in ps and shell history)") - command.Flags().BoolVar(&flags.KeychainPasswordStdin, "keychain-pw-stdin", false, - "read the macOS keychain password from the first line of stdin") - command.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin") -} - -func runDump(ctx context.Context, stderr io.Writer, flags app.Flags) error { - options, err := app.ValidateDump(flags) +func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychain keychainFlags) error { + options, err := app.ValidateDump(flags, keychainPasswordFunc(keychain, os.Stdin)) if err != nil { return err } - discovery := app.Discover(options) - if len(discovery.Dirs) == 0 { - if len(discovery.Errors) > 0 { - report(stderr, app.Summary{Results: discovery.Errors}) - } - log.Warnf("no browsers found") + discovery := app.Discover(options.Target) + if foundNothing(stderr, discovery, "no browsers found") { return nil } - summary, err := app.Execute(ctx, app.NewPlan(discovery, options), options) + summary, err := app.Execute(ctx, discovery, options.Categories, options.Output, options.Keychain) + announceExport(stderr, summary.Exported) if ctx.Err() == nil { report(stderr, summary) } diff --git a/cmd/hack-browser-data/dumpkeys.go b/cmd/hack-browser-data/dumpkeys.go index 7e004e1..ad9718f 100644 --- a/cmd/hack-browser-data/dumpkeys.go +++ b/cmd/hack-browser-data/dumpkeys.go @@ -1,6 +1,8 @@ package main import ( + "os" + "github.com/spf13/cobra" "github.com/moond4rk/hackbrowserdata/internal/app" @@ -9,7 +11,8 @@ import ( func newDumpKeysCommand() *cobra.Command { var ( - flags app.Flags + flags app.DumpKeysFlags + keychain keychainFlags outputPath string ) @@ -19,11 +22,12 @@ func newDumpKeysCommand() *cobra.Command { Example: ` hack-browser-data dumpkeys -o keys.json hack-browser-data dumpkeys -b chrome`, RunE: func(command *cobra.Command, args []string) error { - options, err := app.ValidateDumpKeys(flags) + options, err := app.ValidateDumpKeys(flags, keychainPasswordFunc(keychain, os.Stdin)) if err != nil { return err } - vaultCount, err := app.DumpKeys(command.Context(), app.Discover(options), options, outputPath) + discovery := app.Discover(options.Target) + vaultCount, err := app.DumpKeys(command.Context(), discovery, options.Keychain, command.OutOrStdout(), outputPath) if err != nil { return err } @@ -34,7 +38,7 @@ func newDumpKeysCommand() *cobra.Command { command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames()) command.Flags().StringVarP(&outputPath, "output", "o", "", "output file (default: stdout)") - addKeychainPasswordFlags(command, &flags) + addKeychainPasswordFlags(command, &keychain) return command } diff --git a/cmd/hack-browser-data/list.go b/cmd/hack-browser-data/list.go index 6dc8fdc..8ce430b 100644 --- a/cmd/hack-browser-data/list.go +++ b/cmd/hack-browser-data/list.go @@ -26,9 +26,9 @@ func newListCommand() *cobra.Command { if err != nil { return err } - discovery := app.Discover(options) - for _, result := range discovery.Errors { - log.Warnf("%s: %v", result.UserDataDirID, result.Err) + discovery := app.Discover(options.Target) + for _, failure := range discovery.DirFailures { + log.Warnf("%s: %v", failure.UserDataDirID, failure.Err) } if len(discovery.Dirs) == 0 { command.Println("No browsers found.") @@ -37,7 +37,7 @@ func newListCommand() *cobra.Command { if !detail { return printProfiles(command.OutOrStdout(), discovery) } - summary, err := app.CountRecords(command.Context(), app.NewPlan(discovery, options), options) + summary, err := app.CountRecords(command.Context(), discovery, options.Categories, options.Keychain) if err != nil { return err } diff --git a/cmd/hack-browser-data/main.go b/cmd/hack-browser-data/main.go index 11607e5..b7303f4 100644 --- a/cmd/hack-browser-data/main.go +++ b/cmd/hack-browser-data/main.go @@ -3,6 +3,7 @@ package main import ( "context" "errors" + "fmt" "io" "os" "os/signal" @@ -12,6 +13,7 @@ import ( "github.com/spf13/pflag" "github.com/moond4rk/hackbrowserdata/internal/app" + "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/log" ) @@ -78,6 +80,33 @@ func report(writer io.Writer, summary app.Summary) { } } +// foundNothing reports discovery's failures, the likely reason it found no browser data, then says so. +func foundNothing(stderr io.Writer, discovery app.Discovery, message string) bool { + if len(discovery.Dirs) > 0 { + return false + } + if len(discovery.DirFailures) > 0 { + report(stderr, app.Summary{DirFailures: discovery.DirFailures}) + } + log.Warnf("%s", message) + return true +} + +// announceExport lists the files a run wrote, even when it stopped early, so the user finds what it left. +func announceExport(stderr io.Writer, exported export.Output) { + if len(exported.Files) == 0 { + return + } + fmt.Fprintln(stderr) + log.Infof("Exported to %s/", exported.Dir) + for _, file := range exported.Files { + log.Infof(" %-24s %d entries", file.Name, file.Count) + } + if exported.ZipName != "" { + log.Infof("Compressed: %s/%s", exported.Dir, exported.ZipName) + } +} + // stopSignals end the process by default; each first cancels the run, so its temporary copies are removed. var stopSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP} diff --git a/internal/app/password.go b/cmd/hack-browser-data/password.go similarity index 71% rename from internal/app/password.go rename to cmd/hack-browser-data/password.go index fdf1d23..66ea51f 100644 --- a/internal/app/password.go +++ b/cmd/hack-browser-data/password.go @@ -1,4 +1,4 @@ -package app +package main import ( "bufio" @@ -9,27 +9,39 @@ import ( "os" "strings" + "github.com/spf13/cobra" "golang.org/x/term" ) +// keychainFlags say where the macOS login keychain password comes from; both empty means a prompt, or none. +type keychainFlags struct { + password string + passwordStdin bool +} + +func addKeychainPasswordFlags(command *cobra.Command, flags *keychainFlags) { + command.Flags().StringVar(&flags.password, "keychain-pw", "", "macOS keychain password (visible in ps and shell history)") + command.Flags().BoolVar(&flags.passwordStdin, "keychain-pw-stdin", false, + "read the macOS keychain password from the first line of stdin") + command.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin") +} + var errNoPassword = errors.New("macOS login password not given and stdin is not a terminal") // keychainPasswordFunc is read lazily: a flag, else a no-echo prompt on a terminal, else none (metadata only). -func keychainPasswordFunc(flags Flags, stdin *os.File) (func(context.Context) (string, error), error) { +func keychainPasswordFunc(flags keychainFlags, stdin *os.File) func(context.Context) (string, error) { switch { - case flags.KeychainPassword != "" && flags.KeychainPasswordStdin: - return nil, errors.New("--keychain-pw and --keychain-pw-stdin cannot be used together") - case flags.KeychainPassword != "": - password := flags.KeychainPassword - return func(context.Context) (string, error) { return password, nil }, nil - case flags.KeychainPasswordStdin: + case flags.password != "": + password := flags.password + return func(context.Context) (string, error) { return password, nil } + case flags.passwordStdin: return func(ctx context.Context) (string, error) { return untilDone(ctx, func() (string, error) { return firstLine(stdin) }) - }, nil + } case term.IsTerminal(int(stdin.Fd())): - return func(ctx context.Context) (string, error) { return promptPassword(ctx, stdin) }, nil + return func(ctx context.Context) (string, error) { return promptPassword(ctx, stdin) } default: - return func(context.Context) (string, error) { return "", errNoPassword }, nil + return func(context.Context) (string, error) { return "", errNoPassword } } } diff --git a/cmd/hack-browser-data/password_test.go b/cmd/hack-browser-data/password_test.go new file mode 100644 index 0000000..a9a89ff --- /dev/null +++ b/cmd/hack-browser-data/password_test.go @@ -0,0 +1,58 @@ +package main + +import ( + "context" + "errors" + "io" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestKeychainPasswordFunc(t *testing.T) { + tests := []struct { + name string + flags keychainFlags + stdin string + want string + err error + }{ + {name: "flag", flags: keychainFlags{password: "from-flag"}, stdin: "from-stdin\n", want: "from-flag"}, + {name: "stdin", flags: keychainFlags{passwordStdin: true}, stdin: "from-stdin\r\nnext\n", want: "from-stdin"}, + {name: "stdin without newline", flags: keychainFlags{passwordStdin: true}, stdin: "from-stdin", want: "from-stdin"}, + {name: "none off a terminal", stdin: "from-stdin\n", err: errNoPassword}, + } + for _, testCase := range tests { + testCase := testCase + t.Run(testCase.name, func(t *testing.T) { + pipeReader, pipeWriter, err := os.Pipe() + require.NoError(t, err) + defer pipeReader.Close() + _, err = pipeWriter.WriteString(testCase.stdin) + require.NoError(t, errors.Join(err, pipeWriter.Close())) + + got, err := keychainPasswordFunc(testCase.flags, pipeReader)(context.Background()) + require.ErrorIs(t, err, testCase.err) + assert.Equal(t, testCase.want, got) + }) + } +} + +// TestKeychainPasswordFlagsAreExclusive covers the root command too, which runs dump with dump's flags. +func TestKeychainPasswordFlagsAreExclusive(t *testing.T) { + setHome(t, t.TempDir()) + out := t.TempDir() + for _, args := range [][]string{ + {"-d", out, "--keychain-pw", "pw", "--keychain-pw-stdin"}, + {"dump", "-d", out, "--keychain-pw", "pw", "--keychain-pw-stdin"}, + {"dumpkeys", "--keychain-pw", "pw", "--keychain-pw-stdin"}, + } { + root := newRootCommand() + root.SetOut(io.Discard) + root.SetErr(io.Discard) + root.SetArgs(args) + assert.ErrorContains(t, root.Execute(), "keychain-pw", args) + } +} diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index bb046c1..5a1bdf3 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -43,7 +43,7 @@ func newRestoreCommand() *cobra.Command { } func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) error { - options, dump, err := app.ValidateRestore(flags) + options, keyFile, err := app.ValidateRestore(flags) if err != nil { return err } @@ -53,16 +53,15 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e } defer closeRestoreData(data) - discovery, keys, err := app.DiscoverRestore(data.Path(), dump, options) + discovery, keys, err := app.DiscoverRestore(data.Path(), keyFile, options.Target.BrowserName) if err != nil { return err } - if len(discovery.Dirs) == 0 { - log.Warnf("no browsers to restore from the supplied keys and data") + if foundNothing(stderr, discovery, "no browsers to restore from the supplied keys and data") { return nil } - options.ImportedKeys = keys - summary, err := app.Execute(ctx, app.NewPlan(discovery, options), options) + summary, err := app.ExecuteWithKeys(ctx, discovery, options.Categories, options.Output, keys) + announceExport(stderr, summary.Exported) if ctx.Err() == nil { report(stderr, summary) } diff --git a/internal/app/app.go b/internal/app/app.go deleted file mode 100644 index aa8814b..0000000 --- a/internal/app/app.go +++ /dev/null @@ -1,226 +0,0 @@ -// Package app runs the pipeline: the Validate functions, Discover, NewPlan, Execute, and Report. -package app - -import ( - "context" - "errors" - "fmt" - "io/fs" - "os" - "path/filepath" - "strings" - - "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/export" - "github.com/moond4rk/hackbrowserdata/internal/log" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" -) - -type Flags struct { - Browser string - Categories string - Format string - OutputDir string - Zip bool - ProfilePath string - KeychainPassword string - KeychainPasswordStdin bool -} - -type Options struct { - BrowserName string // "all" or one Browser.Name - Categories []category.Category - Format export.Format - OutputDir string - Zip bool - ProfilePath string - HomeDir string - - // KeychainPassword runs when the keychain first opens; "" leaves it locked, and nil, as list has it, silently. - KeychainPassword func(ctx context.Context) (string, error) - // ImportedKeys are a key file's keys by user data dir; nil retrieves every dir's keys from this machine. - ImportedKeys map[browser.UserDataDirID]masterkey.Set -} - -// ValidateDump checks every flag before any browser or secret is touched, so a bad flag fails fast. -func ValidateDump(flags Flags) (Options, error) { - return validateDump(flags, os.Stdin) -} - -func validateDump(flags Flags, stdin *os.File) (Options, error) { - browserName, err := parseBrowser(flags.Browser) - if err != nil { - return Options{}, err - } - categories, err := parseCategories(flags.Categories) - if err != nil { - return Options{}, err - } - format, err := export.ParseFormat(flags.Format) - if err != nil { - return Options{}, err - } - if err := checkOutputDir(flags.OutputDir); err != nil { - return Options{}, err - } - profilePath, err := checkProfilePath(browserName, flags.ProfilePath) - if err != nil { - return Options{}, err - } - password, err := keychainPasswordFunc(flags, stdin) - if err != nil { - return Options{}, err - } - home, err := homeDir() - if err != nil { - return Options{}, err - } - return Options{ - BrowserName: browserName, - Categories: categories, - Format: format, - OutputDir: flags.OutputDir, - Zip: flags.Zip, - ProfilePath: profilePath, - HomeDir: home, - KeychainPassword: password, - }, nil -} - -func ValidateDumpKeys(flags Flags) (Options, error) { - browserName, err := parseBrowser(flags.Browser) - if err != nil { - return Options{}, err - } - password, err := keychainPasswordFunc(flags, os.Stdin) - if err != nil { - return Options{}, err - } - home, err := homeDir() - if err != nil { - return Options{}, err - } - return Options{BrowserName: browserName, HomeDir: home, KeychainPassword: password}, nil -} - -// ValidateArchive takes no keychain password: an archive copies files and reads no secret. -func ValidateArchive(flags Flags) (Options, error) { - browserName, err := parseBrowser(flags.Browser) - if err != nil { - return Options{}, err - } - categories, err := parseCategories(flags.Categories) - if err != nil { - return Options{}, err - } - home, err := homeDir() - if err != nil { - return Options{}, err - } - return Options{BrowserName: browserName, Categories: categories, HomeDir: home}, nil -} - -// ListOptions is what list reads: every browser and category, with the keychain left locked, so counting never prompts. -func ListOptions() (Options, error) { - home, err := homeDir() - if err != nil { - return Options{}, err - } - return Options{BrowserName: allBrowsers, Categories: category.All(), HomeDir: home}, nil -} - -func homeDir() (string, error) { - home, err := os.UserHomeDir() - if err != nil { - return "", fmt.Errorf("home directory: %w", err) - } - return home, nil -} - -const allBrowsers = "all" - -// parseBrowser accepts all or one of this OS's browser names; a name from another OS's table has nothing to find here. -func parseBrowser(value string) (string, error) { - name := strings.ToLower(strings.TrimSpace(value)) - if name == "" || name == allBrowsers { - return allBrowsers, nil - } - for _, supportedBrowser := range browser.Supported() { - if supportedBrowser.Name == name { - return name, nil - } - } - return "", fmt.Errorf("unknown browser %q, available: %s|%s", value, allBrowsers, strings.Join(browser.Names(), "|")) -} - -// checkOutputDir creates nothing: -d, or its nearest existing ancestor, must be a directory we can create in. -func checkOutputDir(dir string) error { - path := filepath.Clean(dir) - for { - info, err := os.Stat(path) - switch { - case err == nil && info.IsDir(): - if err := canCreateIn(path); err != nil { - return fmt.Errorf("output dir %s: %w", dir, err) - } - return nil - case err == nil: - return fmt.Errorf("output dir %s: %s is not a directory", dir, path) - case !errors.Is(err, fs.ErrNotExist): - return fmt.Errorf("output dir %s: %w", dir, err) - } - parent := filepath.Dir(path) - if parent == path { - return fmt.Errorf("output dir %s: no existing parent directory", dir) - } - path = parent - } -} - -// checkProfilePath keeps -p only when one browser is named; with -b all it is ignored, as it always was, but now said. -func checkProfilePath(browserName, path string) (string, error) { - if path == "" { - return "", nil - } - if browserName == allBrowsers { - log.Warnf("-p needs a specific -b; ignoring %s", path) - return "", nil - } - info, err := os.Stat(path) - if err != nil { - return "", fmt.Errorf("profile path: %w", err) - } - if !info.IsDir() { - return "", fmt.Errorf("profile path %s: not a directory", path) - } - return path, nil -} - -// parseCategories keeps a repeated category once, or its records would be exported twice. -func parseCategories(value string) ([]category.Category, error) { - value = strings.TrimSpace(value) - if strings.EqualFold(value, "all") { - return category.All(), nil - } - var categories []category.Category - seen := make(map[category.Category]bool) - for _, name := range strings.Split(value, ",") { - name = strings.TrimSpace(strings.ToLower(name)) - if name == "" { - continue - } - dataCategory, err := category.Parse(name) - if err != nil { - return nil, fmt.Errorf("%w, available: all|%s", err, strings.Join(category.Names(), ",")) - } - if !seen[dataCategory] { - seen[dataCategory] = true - categories = append(categories, dataCategory) - } - } - if len(categories) == 0 { - return nil, fmt.Errorf("no categories specified") - } - return categories, nil -} diff --git a/internal/app/app_test.go b/internal/app/app_test.go deleted file mode 100644 index fee530b..0000000 --- a/internal/app/app_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package app - -import ( - "context" - "errors" - "io/fs" - "os" - "path/filepath" - "runtime" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/export" -) - -func TestValidate(t *testing.T) { - options, err := ValidateDump(Flags{Browser: " Chrome ", Categories: "cookie, password,cookie", Format: "csv", OutputDir: "out", KeychainPassword: "pw"}) - require.NoError(t, err) - assert.Equal(t, "chrome", options.BrowserName) - assert.Equal(t, []category.Category{category.Cookie, category.Password}, options.Categories, "a repeated category runs once") - assert.Equal(t, export.CSV, options.Format) - assert.Equal(t, "out", options.OutputDir) - assert.NotEmpty(t, options.HomeDir) - password, err := options.KeychainPassword(context.Background()) - require.NoError(t, err) - assert.Equal(t, "pw", password) - - options, err = ValidateDump(Flags{Categories: "all", Format: "json"}) - require.NoError(t, err) - assert.Equal(t, "all", options.BrowserName) - assert.Equal(t, category.All(), options.Categories) -} - -func TestValidate_RejectsBadInput(t *testing.T) { - file := filepath.Join(t.TempDir(), "file") - require.NoError(t, os.WriteFile(file, nil, 0o600)) - missing := filepath.Join(t.TempDir(), "missing") - for name, flags := range map[string]Flags{ - "unknown category": {Categories: "cookie,bogus", Format: "json"}, - "no category": {Categories: " , ", Format: "json"}, - "unknown format": {Categories: "all", Format: "xml"}, - "unknown browser": {Browser: "bogus", Categories: "all", Format: "json"}, - "another OS's browser": {Browser: otherOSBrowser(t), Categories: "all", Format: "json"}, - "-d below a file": {Categories: "all", Format: "json", OutputDir: filepath.Join(file, "out")}, - "-d is a file": {Categories: "all", Format: "json", OutputDir: file}, - "missing -p": {Browser: "chrome", Categories: "all", Format: "json", ProfilePath: missing}, - "-p is a file": {Browser: "chrome", Categories: "all", Format: "json", ProfilePath: file}, - "two password inputs": {Categories: "all", Format: "json", KeychainPassword: "pw", KeychainPasswordStdin: true}, - } { - _, err := ValidateDump(flags) - assert.Error(t, err, name) - } -} - -func otherOSBrowser(t *testing.T) string { - t.Helper() - for _, name := range []string{"sogou", "safari"} { - namedBrowser, ok := browser.Lookup(name) - require.True(t, ok, name) - if len(namedBrowser.Platform().UserDataDirs) == 0 { - return name - } - } - t.Fatal("every candidate is supported here") - return "" -} - -func TestValidate_CreatesNoOutputDir(t *testing.T) { - root := t.TempDir() - options, err := ValidateDump(Flags{Categories: "all", Format: "json", OutputDir: filepath.Join(root, "a", "b")}) - require.NoError(t, err) - assert.Equal(t, filepath.Join(root, "a", "b"), options.OutputDir) - _, err = os.Stat(filepath.Join(root, "a")) - assert.ErrorIs(t, err, fs.ErrNotExist) -} - -func TestValidate_RejectsAnOutputDirThatCannotBeCreated(t *testing.T) { - if runtime.GOOS == "windows" || os.Geteuid() == 0 { - t.Skip("directory permissions do not deny writes here") - } - root := t.TempDir() - require.NoError(t, os.Chmod(root, 0o500)) - defer func() { require.NoError(t, os.Chmod(root, 0o700)) }() - - _, err := ValidateDump(Flags{Categories: "all", Format: "json", OutputDir: filepath.Join(root, "results")}) - assert.Error(t, err) -} - -// TestValidate_IgnoresProfilePathForAllBrowsers keeps -p without a named browser ignored, as before; it is reported. -func TestValidate_IgnoresProfilePathForAllBrowsers(t *testing.T) { - options, err := ValidateDump(Flags{Browser: "all", Categories: "all", Format: "json", ProfilePath: filepath.Join(t.TempDir(), "missing")}) - require.NoError(t, err) - assert.Empty(t, options.ProfilePath) -} - -func TestValidate_KeychainPasswordInputs(t *testing.T) { - tests := []struct { - name string - flags Flags - stdin string - want string - err error - }{ - {name: "flag", flags: Flags{KeychainPassword: "from-flag"}, stdin: "from-stdin\n", want: "from-flag"}, - {name: "stdin", flags: Flags{KeychainPasswordStdin: true}, stdin: "from-stdin\r\nnext\n", want: "from-stdin"}, - {name: "stdin without newline", flags: Flags{KeychainPasswordStdin: true}, stdin: "from-stdin", want: "from-stdin"}, - {name: "none off a terminal", flags: Flags{}, stdin: "from-stdin\n", err: errNoPassword}, - } - for _, testCase := range tests { - testCase := testCase - t.Run(testCase.name, func(t *testing.T) { - pipeReader, pipeWriter, err := os.Pipe() - require.NoError(t, err) - defer pipeReader.Close() - _, err = pipeWriter.WriteString(testCase.stdin) - require.NoError(t, errors.Join(err, pipeWriter.Close())) - - testCase.flags.Categories, testCase.flags.Format = "all", "json" - options, err := validateDump(testCase.flags, pipeReader) - require.NoError(t, err) - got, err := options.KeychainPassword(context.Background()) - require.ErrorIs(t, err, testCase.err) - assert.Equal(t, testCase.want, got) - }) - } -} diff --git a/internal/app/archive.go b/internal/app/archive.go index 470d7f6..fe9ae86 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -7,19 +7,43 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" + "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/log" "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) +// ArchiveFlags are archive's command-line values as cobra parsed them. +type ArchiveFlags struct { + Browser string + Categories string +} + +// ValidateArchive takes no keychain password: an archive copies files and reads no secret. +func ValidateArchive(flags ArchiveFlags) (Options, error) { + browserName, err := parseBrowser(flags.Browser) + if err != nil { + return Options{}, err + } + categories, err := parseCategories(flags.Categories) + if err != nil { + return Options{}, err + } + home, err := homeDir() + if err != nil { + return Options{}, err + } + return Options{Target: Target{BrowserName: browserName, HomeDir: home}, Categories: categories}, nil +} + // Archive returns how many files and directories it captured. -func Archive(ctx context.Context, discovery Discovery, options Options, archivePath string) (int, error) { +func Archive(ctx context.Context, discovery Discovery, categories []category.Category, archivePath string) (int, error) { var dirs []browser.UserDataDir for _, dir := range discovery.Dirs { if dir.Browser.Base == browser.Chromium { dirs = append(dirs, dir) } } - files := archiveFiles(NewPlan(Discovery{Dirs: dirs}, options), dirs) + files := archiveFiles(dirs, categories) snapshots, err := snapshot.Temp() if err != nil { @@ -39,26 +63,19 @@ func Archive(ctx context.Context, discovery Discovery, options Options, archiveP return fileCount, nil } -func archiveFiles(plan Plan, dirs []browser.UserDataDir) []snapshot.File { +func archiveFiles(dirs []browser.UserDataDir, categories []category.Category) []snapshot.File { + extractors := extractorsWith(nil) var files []snapshot.File seen := make(map[snapshot.File]bool) - add := func(file snapshot.File) { - if !seen[file] { - seen[file] = true - files = append(files, file) - } - } for _, dir := range dirs { for _, profile := range dir.Profiles { for _, source := range chromium.ArchiveSources() { if file, ok, err := firstOnDisk(dir, profile, source); err == nil && ok { - add(file) + files = appendNew(files, seen, file) } } } - for _, file := range filesOf(plan, dir.ID) { - add(file) - } + files = appendNew(files, seen, planDir(dir, categories, extractors).files...) } return files } diff --git a/internal/app/archive_golden_test.go b/internal/app/archive_golden_test.go index 48cfa9c..d133b40 100644 --- a/internal/app/archive_golden_test.go +++ b/internal/app/archive_golden_test.go @@ -94,11 +94,11 @@ func TestArchiveGolden(t *testing.T) { for _, testCase := range tests { testCase := testCase t.Run(testCase.name, func(t *testing.T) { - options, err := app.ValidateArchive(app.Flags{Browser: archiveLayoutBrowser, Categories: testCase.categories}) + options, err := app.ValidateArchive(app.ArchiveFlags{Browser: archiveLayoutBrowser, Categories: testCase.categories}) require.NoError(t, err) - options.HomeDir = home + options.Target.HomeDir = home out := filepath.Join(t.TempDir(), "browser-data.zip") - fileCount, err := app.Archive(context.Background(), app.Discover(options), options, out) + fileCount, err := app.Archive(context.Background(), app.Discover(options.Target), options.Categories, out) require.NoError(t, err) golden.Assert(t, testCase.golden, fmt.Sprintf("entries=%d\n", fileCount)+golden.ZipListing(t, out)) @@ -125,11 +125,11 @@ func TestArchiveRestoreRoundTrip(t *testing.T) { require.True(t, ok, fixture.Name) browsertest.WriteChromiumUserDataDir(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])), fixture.Name) } - options, err := app.ValidateArchive(app.Flags{Browser: "all", Categories: "all"}) + options, err := app.ValidateArchive(app.ArchiveFlags{Browser: "all", Categories: "all"}) require.NoError(t, err) - options.HomeDir = home + options.Target.HomeDir = home archive := filepath.Join(t.TempDir(), "data.zip") - _, err = app.Archive(context.Background(), app.Discover(options), options, archive) + _, err = app.Archive(context.Background(), app.Discover(options.Target), options.Categories, archive) require.NoError(t, err) out := restoreGolden(t, app.RestoreFlags{KeyFile: chromiumKeyFile(t), DataZip: archive, OutputDir: t.TempDir()}) diff --git a/internal/app/collector.go b/internal/app/collector.go new file mode 100644 index 0000000..1bc20d6 --- /dev/null +++ b/internal/app/collector.go @@ -0,0 +1,47 @@ +package app + +import ( + "errors" + "io/fs" + + "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +type collector struct { + browserName, profileName string + records []record.Record + failures int + firstFailure error +} + +func (c *collector) Add(row record.Record) { + row.SetBrowserAndProfile(c.browserName, c.profileName) + c.records = append(c.records, row) +} + +func (c *collector) Fail(err error) { + c.failures++ + if c.firstFailure == nil { + c.firstFailure = err + } + log.Debugf("%s/%s: %v", c.browserName, c.profileName, err) +} + +// result treats a file gone since planning as absent; failures alone are an error, and failures beside records partial. +func (c *collector) result(extraction Extraction, err error) Result { + result := Result{Extraction: extraction, Records: len(c.records), Failures: c.failures} + switch { + case err != nil && errors.Is(err, fs.ErrNotExist) && result.Records == 0: + result.Outcome = OutcomeAbsent + case err != nil: + result.Outcome, result.Err = OutcomeError, err + case result.Failures > 0 && result.Records == 0: + result.Outcome, result.Err = OutcomeError, c.firstFailure + case result.Failures > 0: + result.Outcome = OutcomePartial + default: + result.Outcome = OutcomeOK + } + return result +} diff --git a/internal/app/discover.go b/internal/app/discover.go index 93e4b7e..9fa9cf3 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -9,27 +9,27 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser/safari" ) -// Discovery holds an error result per browser whose data could not be read, so it is reported, not taken as absence. +// Discovery keeps a failure per browser whose data could not be read, so it is reported, not taken as absence. type Discovery struct { - Dirs []browser.UserDataDir - Errors []Result + Dirs []browser.UserDataDir + DirFailures []DirFailure } -// Discover applies -p only when one browser is named. -func Discover(options Options) Discovery { +// Discover applies the target's profile path only when one browser is named. +func Discover(target Target) Discovery { var discovery Discovery for _, supportedBrowser := range browser.Supported() { - if options.BrowserName != allBrowsers && supportedBrowser.Name != options.BrowserName { + if target.BrowserName != allBrowsers && supportedBrowser.Name != target.BrowserName { continue } - discoverOptions := browser.DiscoverOptions{HomeDir: options.HomeDir} - if options.BrowserName != allBrowsers { - discoverOptions.ProfilePath = options.ProfilePath + discoverOptions := browser.DiscoverOptions{HomeDir: target.HomeDir} + if target.BrowserName != allBrowsers { + discoverOptions.ProfilePath = target.ProfilePath } dirs, err := discover(supportedBrowser, discoverOptions) discovery.Dirs = append(discovery.Dirs, withData(dirs)...) if err != nil { - discovery.Errors = append(discovery.Errors, dirFailure(browser.UserDataDirID(supportedBrowser.Name), err)) + discovery.DirFailures = append(discovery.DirFailures, DirFailure{UserDataDirID: browser.UserDataDirID(supportedBrowser.Name), Err: err}) } } return discovery diff --git a/internal/app/discover_test.go b/internal/app/discover_test.go index 4917cd8..a1513e7 100644 --- a/internal/app/discover_test.go +++ b/internal/app/discover_test.go @@ -35,11 +35,11 @@ func TestDiscover(t *testing.T) { writeUserDataDir(t, home, "edge") writeUserDataDir(t, home, "chrome") - discovery := Discover(Options{BrowserName: "all", HomeDir: home}) + discovery := Discover(Target{BrowserName: "all", HomeDir: home}) assert.Equal(t, []browser.UserDataDirID{"chrome", "edge"}, userDataDirIDs(discovery), "table order, which is output order") - assert.Empty(t, discovery.Errors) + assert.Empty(t, discovery.DirFailures) - discovery = Discover(Options{BrowserName: "edge", HomeDir: home}) + discovery = Discover(Target{BrowserName: "edge", HomeDir: home}) assert.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery)) } @@ -50,11 +50,11 @@ func TestDiscover_ProfilePathNeedsOneBrowser(t *testing.T) { touch(t, custom, "Default", "Preferences") touch(t, custom, "Default", "History") - discovery := Discover(Options{BrowserName: "chrome", HomeDir: home, ProfilePath: custom}) + discovery := Discover(Target{BrowserName: "chrome", HomeDir: home, ProfilePath: custom}) require.Len(t, discovery.Dirs, 1) assert.Equal(t, custom, discovery.Dirs[0].Path) - discovery = Discover(Options{BrowserName: "all", HomeDir: home, ProfilePath: custom}) + discovery = Discover(Target{BrowserName: "all", HomeDir: home, ProfilePath: custom}) require.Len(t, discovery.Dirs, 1) assert.NotEqual(t, custom, discovery.Dirs[0].Path, "-p is ignored without a specific browser") } @@ -67,7 +67,7 @@ func TestDiscover_KeepsOnlyProfilesWithData(t *testing.T) { edge := writeUserDataDir(t, home, "edge") require.NoError(t, os.Remove(filepath.Join(edge, "Default", "History"))) - discovery := Discover(Options{BrowserName: "all", HomeDir: home}) + discovery := Discover(Target{BrowserName: "all", HomeDir: home}) assert.Equal(t, []browser.UserDataDirID{"chrome"}, userDataDirIDs(discovery)) assert.Equal(t, []browser.Profile{{Name: "Default", RelativePath: "Default"}}, discovery.Dirs[0].Profiles) } @@ -81,11 +81,11 @@ func TestDiscover_UnreadableDirIsReported(t *testing.T) { require.NoError(t, os.Chmod(path, 0o000)) defer func() { require.NoError(t, os.Chmod(path, 0o700)) }() - discovery := Discover(Options{BrowserName: "all", HomeDir: home}) + discovery := Discover(Target{BrowserName: "all", HomeDir: home}) assert.Empty(t, discovery.Dirs) - require.Len(t, discovery.Errors, 1) - assert.Equal(t, Extraction{UserDataDirID: "chrome"}, discovery.Errors[0].Extraction) - assert.Equal(t, OutcomeError, discovery.Errors[0].Outcome) + require.Len(t, discovery.DirFailures, 1) + assert.Equal(t, browser.UserDataDirID("chrome"), discovery.DirFailures[0].UserDataDirID) + assert.Error(t, discovery.DirFailures[0].Err) } // TestWithData_KeepsAProfileItCannotCheck keeps it for the plan to report, since dropping it would hide the failure. diff --git a/internal/app/doc.go b/internal/app/doc.go new file mode 100644 index 0000000..f4d8d7f --- /dev/null +++ b/internal/app/doc.go @@ -0,0 +1,2 @@ +// Package app runs the pipeline: the Validate functions, Discover, Execute, and Report. +package app diff --git a/internal/app/dump.go b/internal/app/dump.go new file mode 100644 index 0000000..5ce9354 --- /dev/null +++ b/internal/app/dump.go @@ -0,0 +1,72 @@ +package app + +import ( + "context" + "fmt" + "os" + + "github.com/moond4rk/hackbrowserdata/internal/export" + "github.com/moond4rk/hackbrowserdata/internal/log" +) + +// DumpFlags are dump's command-line values as cobra parsed them. +type DumpFlags struct { + Browser string + Categories string + Format string + OutputDir string + Zip bool + ProfilePath string +} + +// ValidateDump checks every flag before any browser or secret is touched, so a bad flag fails fast. +func ValidateDump(flags DumpFlags, keychainPassword func(context.Context) (string, error)) (Options, error) { + browserName, err := parseBrowser(flags.Browser) + if err != nil { + return Options{}, err + } + categories, err := parseCategories(flags.Categories) + if err != nil { + return Options{}, err + } + format, err := export.ParseFormat(flags.Format) + if err != nil { + return Options{}, err + } + if err := checkOutputDir(flags.OutputDir); err != nil { + return Options{}, err + } + profilePath, err := checkProfilePath(browserName, flags.ProfilePath) + if err != nil { + return Options{}, err + } + home, err := homeDir() + if err != nil { + return Options{}, err + } + return Options{ + Target: Target{BrowserName: browserName, ProfilePath: profilePath, HomeDir: home}, + Categories: categories, + Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip}, + Keychain: KeychainConfig{HomeDir: home, Password: keychainPassword}, + }, nil +} + +// checkProfilePath keeps -p only when one browser is named; with -b all it is ignored, as it always was, but now said. +func checkProfilePath(browserName, path string) (string, error) { + if path == "" { + return "", nil + } + if browserName == allBrowsers { + log.Warnf("-p needs a specific -b; ignoring %s", path) + return "", nil + } + info, err := os.Stat(path) + if err != nil { + return "", fmt.Errorf("profile path: %w", err) + } + if !info.IsDir() { + return "", fmt.Errorf("profile path %s: not a directory", path) + } + return path, nil +} diff --git a/internal/app/dump_test.go b/internal/app/dump_test.go new file mode 100644 index 0000000..2c7299e --- /dev/null +++ b/internal/app/dump_test.go @@ -0,0 +1,98 @@ +package app + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/export" +) + +func TestValidateDump(t *testing.T) { + keychainPassword := func(context.Context) (string, error) { return "pw", nil } + options, err := ValidateDump(DumpFlags{Browser: " Chrome ", Categories: "cookie, password,cookie", Format: "csv", OutputDir: "out"}, keychainPassword) + require.NoError(t, err) + assert.Equal(t, "chrome", options.Target.BrowserName) + assert.Equal(t, []category.Category{category.Cookie, category.Password}, options.Categories, "a repeated category runs once") + assert.Equal(t, export.CSV, options.Output.Format) + assert.Equal(t, "out", options.Output.Dir) + assert.NotEmpty(t, options.Target.HomeDir) + assert.Equal(t, options.Target.HomeDir, options.Keychain.HomeDir) + password, err := options.Keychain.Password(context.Background()) + require.NoError(t, err) + assert.Equal(t, "pw", password) + + options, err = ValidateDump(DumpFlags{Categories: "all", Format: "json"}, nil) + require.NoError(t, err) + assert.Equal(t, "all", options.Target.BrowserName) + assert.Equal(t, category.All(), options.Categories) +} + +func TestValidateDump_RejectsBadInput(t *testing.T) { + file := filepath.Join(t.TempDir(), "file") + require.NoError(t, os.WriteFile(file, nil, 0o600)) + missing := filepath.Join(t.TempDir(), "missing") + for name, flags := range map[string]DumpFlags{ + "unknown category": {Categories: "cookie,bogus", Format: "json"}, + "no category": {Categories: " , ", Format: "json"}, + "unknown format": {Categories: "all", Format: "xml"}, + "unknown browser": {Browser: "bogus", Categories: "all", Format: "json"}, + "another OS's browser": {Browser: otherOSBrowser(t), Categories: "all", Format: "json"}, + "-d below a file": {Categories: "all", Format: "json", OutputDir: filepath.Join(file, "out")}, + "-d is a file": {Categories: "all", Format: "json", OutputDir: file}, + "missing -p": {Browser: "chrome", Categories: "all", Format: "json", ProfilePath: missing}, + "-p is a file": {Browser: "chrome", Categories: "all", Format: "json", ProfilePath: file}, + } { + _, err := ValidateDump(flags, nil) + assert.Error(t, err, name) + } +} + +func otherOSBrowser(t *testing.T) string { + t.Helper() + for _, name := range []string{"sogou", "safari"} { + namedBrowser, ok := browser.Lookup(name) + require.True(t, ok, name) + if len(namedBrowser.Platform().UserDataDirs) == 0 { + return name + } + } + t.Fatal("every candidate is supported here") + return "" +} + +func TestValidateDump_CreatesNoOutputDir(t *testing.T) { + root := t.TempDir() + options, err := ValidateDump(DumpFlags{Categories: "all", Format: "json", OutputDir: filepath.Join(root, "a", "b")}, nil) + require.NoError(t, err) + assert.Equal(t, filepath.Join(root, "a", "b"), options.Output.Dir) + _, err = os.Stat(filepath.Join(root, "a")) + assert.ErrorIs(t, err, fs.ErrNotExist) +} + +func TestValidateDump_RejectsAnOutputDirThatCannotBeCreated(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("directory permissions do not deny writes here") + } + root := t.TempDir() + require.NoError(t, os.Chmod(root, 0o500)) + defer func() { require.NoError(t, os.Chmod(root, 0o700)) }() + + _, err := ValidateDump(DumpFlags{Categories: "all", Format: "json", OutputDir: filepath.Join(root, "results")}, nil) + assert.Error(t, err) +} + +// TestValidateDump_IgnoresProfilePathForAllBrowsers keeps -p without a named browser ignored, as before; it is reported. +func TestValidateDump_IgnoresProfilePathForAllBrowsers(t *testing.T) { + options, err := ValidateDump(DumpFlags{Browser: "all", Categories: "all", Format: "json", ProfilePath: filepath.Join(t.TempDir(), "missing")}, nil) + require.NoError(t, err) + assert.Empty(t, options.Target.ProfilePath) +} diff --git a/internal/app/keys.go b/internal/app/dumpkeys.go similarity index 79% rename from internal/app/keys.go rename to internal/app/dumpkeys.go index 4eae97e..2b6e420 100644 --- a/internal/app/keys.go +++ b/internal/app/dumpkeys.go @@ -3,7 +3,7 @@ package app import ( "context" "fmt" - "os" + "io" "github.com/moond4rk/hackbrowserdata/internal/atomicfile" "github.com/moond4rk/hackbrowserdata/internal/browser" @@ -13,15 +13,35 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) +// DumpKeysFlags are dumpkeys' command-line values as cobra parsed them. +type DumpKeysFlags struct { + Browser string +} + +func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword func(context.Context) (string, error)) (Options, error) { + browserName, err := parseBrowser(flags.Browser) + if err != nil { + return Options{}, err + } + home, err := homeDir() + if err != nil { + return Options{}, err + } + return Options{ + Target: Target{BrowserName: browserName, HomeDir: home}, + Keychain: KeychainConfig{HomeDir: home, Password: keychainPassword}, + }, nil +} + // DumpKeys writes the key file to outputPath, or to stdout when it is "", and returns how many vaults it holds. // A stopped run writes nothing, so it never leaves a keys.json behind. -func DumpKeys(ctx context.Context, discovery Discovery, options Options, outputPath string) (int, error) { - keyFile, err := dumpKeysWith(ctx, discovery, keysFromMachine(newLoginKeychain(options))) +func DumpKeys(ctx context.Context, discovery Discovery, keychainConfig KeychainConfig, stdout io.Writer, outputPath string) (int, error) { + keyFile, err := dumpKeysWith(ctx, discovery, keysFromMachine(newLoginKeychain(keychainConfig))) if err != nil { return 0, err } if outputPath == "" { - return len(keyFile.Vaults), keyFile.Write(os.Stdout) + return len(keyFile.Vaults), keyFile.Write(stdout) } if err := writeKeyFile(outputPath, keyFile); err != nil { return 0, err diff --git a/internal/app/keys_test.go b/internal/app/dumpkeys_test.go similarity index 100% rename from internal/app/keys_test.go rename to internal/app/dumpkeys_test.go diff --git a/internal/app/execute.go b/internal/app/execute.go index 42f8485..cf81e57 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -4,13 +4,8 @@ import ( "context" "errors" "fmt" - "io/fs" - "os" - "sync" "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" - "github.com/moond4rk/hackbrowserdata/internal/browser/safari" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/export" "github.com/moond4rk/hackbrowserdata/internal/log" @@ -19,90 +14,69 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// loginKeychain is the run's one login keychain, shared by Chromium's v10 key and Safari's passwords; nil off macOS. -type loginKeychain interface { - masterkey.LoginKeychain - safari.LoginKeychain +// Execute retrieves each dir's master keys from this machine. It handles one user data dir at a time, so at most one +// dir's copies are on disk. Its error means the run ended early; like os.ReadDir, it still returns the Summary of what +// ran before it, with the files written, so the caller can list them. +func Execute( + ctx context.Context, discovery Discovery, categories []category.Category, output Output, keychainConfig KeychainConfig, +) (Summary, error) { + keychain := newLoginKeychain(keychainConfig) + return execute(ctx, discovery, categories, output, extractorsWith(keychain), keysFromMachine(keychain)) } -type dirKeysFunc func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) - -// Execute handles one user data dir at a time, so at most one dir's copies are on disk. -// Its error means the run could not finish; every other failure is a Result. -func Execute(ctx context.Context, plan Plan, options Options) (Summary, error) { - keychain := newLoginKeychain(options) - keys := keysFromFile(options.ImportedKeys) - if options.ImportedKeys == nil { - keys = keysFromMachine(keychain) - } - return execute(ctx, plan, options, extractorsWith(keychain), keys) +// ExecuteWithKeys decrypts with a key file's keys, so it never reads this machine's secret stores. +func ExecuteWithKeys( + ctx context.Context, discovery Discovery, categories []category.Category, output Output, keys map[browser.UserDataDirID]masterkey.Set, +) (Summary, error) { + return execute(ctx, discovery, categories, output, extractorsWith(nil), keysFromFile(keys)) } -func execute(ctx context.Context, plan Plan, options Options, extractors extractorsFunc, keys dirKeysFunc) (Summary, error) { - writer, err := export.NewWriter(options.OutputDir, options.Format, options.Zip) +func execute( + ctx context.Context, discovery Discovery, categories []category.Category, output Output, extractors extractorsFunc, keys dirKeysFunc, +) (Summary, error) { + writer, err := export.NewWriter(output.Dir, output.Format, output.Zip) if err != nil { return Summary{}, err } - summary, err := runner{writer: writer, extractors: extractors, keys: keys, logProgress: true}.run(ctx, plan) + summary, err := runner{writer: writer, extractors: extractors, retrieveKeys: keys, logProgress: true}.run(ctx, discovery, categories) closeErr := writer.Close() - announceOutput(writer.Output()) + summary.Exported = writer.Output() return summary, errors.Join(err, closeErr) } -func announceOutput(out export.Output) { - if len(out.Files) == 0 { - return - } - fmt.Fprintln(os.Stderr) - log.Infof("Exported to %s/", out.Dir) - for _, file := range out.Files { - log.Infof(" %-24s %d entries", file.Name, file.Count) - } - if out.ZipName != "" { - log.Infof("Compressed: %s/%s", out.Dir, out.ZipName) - } -} - -// CountRecords runs the plan with no key and the keychain locked, counting records instead of exporting them. -func CountRecords(ctx context.Context, plan Plan, options Options) (Summary, error) { - return runner{writer: discard{}, extractors: extractorsWith(newLoginKeychain(options)), keys: keysFromFile(nil)}.run(ctx, plan) -} - type recordWriter interface { Write(dataCategory category.Category, records []record.Record) error } -type discard struct{} - -func (discard) Write(category.Category, []record.Record) error { return nil } - // runner is what every user data dir of one run shares; logProgress logs each dir as it starts. type runner struct { - writer recordWriter - extractors extractorsFunc - keys dirKeysFunc - logProgress bool + writer recordWriter + extractors extractorsFunc + retrieveKeys dirKeysFunc + logProgress bool } -func (r runner) run(ctx context.Context, plan Plan) (Summary, error) { - results := append([]Result(nil), plan.Skipped...) - for _, dir := range plan.Dirs { +func (r runner) run(ctx context.Context, discovery Discovery, categories []category.Category) (Summary, error) { + summary := Summary{DirFailures: append([]DirFailure(nil), discovery.DirFailures...)} + for _, dir := range discovery.Dirs { if err := ctx.Err(); err != nil { - return Summary{Results: results}, fmt.Errorf("run stopped: %w", err) + return summary, fmt.Errorf("run stopped: %w", err) } - dirResults, err := r.runDir(ctx, dir, plan) - results = append(results, dirResults...) + dirSummary, err := r.runDir(ctx, dir, categories) + summary.Results = append(summary.Results, dirSummary.Results...) + summary.DirFailures = append(summary.DirFailures, dirSummary.DirFailures...) if err != nil { - return Summary{Results: results}, err + return summary, err } } - return Summary{Results: results}, nil + return summary, nil } -func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, plan Plan) ([]Result, error) { - extractions := extractionsOf(plan, dir.ID) - if len(extractions) == 0 { - return nil, nil +func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories []category.Category) (Summary, error) { + plan := planDir(dir, categories, r.extractors) + summary := Summary{Results: plan.skipped} + if len(plan.extractions) == 0 { + return summary, nil } if r.logProgress { log.Infof("Extracting %s...", dir.Browser.DisplayName) @@ -110,82 +84,57 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, plan Plan) snapshots, err := snapshot.Temp() if err != nil { - return failAll(extractions, err), nil + summary.Results = append(summary.Results, failAll(plan.extractions, err)...) + return summary, nil } defer closeSnapshot(snapshots) - if err := snapshots.Capture(ctx, filesOf(plan, dir.ID)); err != nil { + if err := snapshots.Capture(ctx, plan.files); err != nil { if ctx.Err() != nil { - return nil, err + return summary, err } - return failAll(extractions, err), nil + summary.Results = append(summary.Results, failAll(plan.extractions, err)...) + return summary, nil } dirSnapshot := snapshots.Snapshot(string(dir.ID)) - var ( - dirKeyRetrieval *dirKeys - masterKeys func(context.Context) masterkey.Set - ) + keys := &dirKeys{dir: dir, dirSnapshot: dirSnapshot} if dir.Browser.Base == browser.Chromium { - dirKeyRetrieval = &dirKeys{retrieve: func(ctx context.Context) (masterkey.Set, error) { return r.keys(ctx, dir, dirSnapshot) }} - masterKeys = dirKeyRetrieval.get + keys.retrieve = r.retrieveKeys } - - profiles := make(map[string]browser.Profile, len(dir.Profiles)) - byProfile := make(map[string]browser.Extractors, len(dir.Profiles)) - for _, profile := range dir.Profiles { - profiles[profile.Name] = profile - byProfile[profile.Name] = r.extractors(dir, profile) - } - - results := make([]Result, 0, len(extractions)+1) - for _, extraction := range extractions { + for _, extraction := range plan.extractions { if err := ctx.Err(); err != nil { - return results, fmt.Errorf("run stopped: %w", err) + return summary, fmt.Errorf("run stopped: %w", err) } - extractor, ok := byProfile[extraction.ProfileName][extraction.Category] - if !ok || extractor.Extract == nil { - results = append(results, Result{Extraction: extraction, Outcome: OutcomeUnsupported}) - continue + profileSnapshot := browser.NewProfileSnapshot(dirSnapshot, extraction.profile, keys.get) + result, err := r.runExtraction(ctx, extraction, profileSnapshot, dir.Browser.DisplayName) + if err != nil { + return summary, err } - profile := profiles[extraction.ProfileName] - recordCollector := &collector{browserName: dir.Browser.DisplayName, profileName: profile.Name} - err := extractor.Extract(ctx, browser.NewProfileSnapshot(dirSnapshot, profile, masterKeys), recordCollector) - // Records emitted before an extraction failed are kept, as they always were. - if writeErr := r.writer.Write(extraction.Category, recordCollector.records); writeErr != nil { - return results, writeErr - } - results = append(results, recordCollector.result(extraction, err)) + summary.Results = append(summary.Results, result) } - if dirKeyRetrieval != nil && dirKeyRetrieval.err != nil { - results = append(results, dirFailure(dir.ID, fmt.Errorf("master key retrieval: %w", dirKeyRetrieval.err))) + if keys.err != nil { + keyErr := fmt.Errorf("master key retrieval: %w", keys.err) + summary.DirFailures = []DirFailure{{UserDataDirID: dir.ID, Err: keyErr}} } - return results, nil + return summary, nil } -func extractionsOf(plan Plan, id browser.UserDataDirID) []Extraction { - var out []Extraction - for _, extraction := range plan.Extractions { - if extraction.UserDataDirID == id { - out = append(out, extraction) - } +// runExtraction exports the records emitted before an extraction failed, as they always were; its error stops the run. +func (r runner) runExtraction( + ctx context.Context, extraction plannedExtraction, profileSnapshot browser.ProfileSnapshot, browserName string, +) (Result, error) { + recordCollector := &collector{browserName: browserName, profileName: extraction.ProfileName} + err := extraction.extractor.Extract(ctx, profileSnapshot, recordCollector) + if writeErr := r.writer.Write(extraction.Category, recordCollector.records); writeErr != nil { + return Result{}, writeErr } - return out + return recordCollector.result(extraction.Extraction, err), nil } -func filesOf(plan Plan, id browser.UserDataDirID) []snapshot.File { - var out []snapshot.File - for _, file := range plan.Files { - if file.UserDataDirID == string(id) { - out = append(out, file) - } - } - return out -} - -func failAll(extractions []Extraction, err error) []Result { +func failAll(extractions []plannedExtraction, err error) []Result { results := make([]Result, len(extractions)) for i, extraction := range extractions { - results[i] = Result{Extraction: extraction, Outcome: OutcomeError, Err: err} + results[i] = Result{Extraction: extraction.Extraction, Outcome: OutcomeError, Err: err} } return results } @@ -195,72 +144,3 @@ func closeSnapshot(snapshots *snapshot.Dir) { log.Warnf("%v", err) } } - -type collector struct { - browserName, profileName string - records []record.Record - failures int - firstFailure error -} - -func (c *collector) Add(row record.Record) { - row.SetBrowserAndProfile(c.browserName, c.profileName) - c.records = append(c.records, row) -} - -func (c *collector) Fail(err error) { - c.failures++ - if c.firstFailure == nil { - c.firstFailure = err - } - log.Debugf("%s/%s: %v", c.browserName, c.profileName, err) -} - -// result treats a file gone since planning as absent; failures alone are an error, and failures beside records partial. -func (c *collector) result(extraction Extraction, err error) Result { - result := Result{Extraction: extraction, Records: len(c.records), Failures: c.failures} - switch { - case err != nil && errors.Is(err, fs.ErrNotExist) && result.Records == 0: - result.Outcome = OutcomeAbsent - case err != nil: - result.Outcome, result.Err = OutcomeError, err - case result.Failures > 0 && result.Records == 0: - result.Outcome, result.Err = OutcomeError, c.firstFailure - case result.Failures > 0: - result.Outcome = OutcomePartial - default: - result.Outcome = OutcomeOK - } - return result -} - -// dirKeys retrieves a dir's keys on first use, for all its profiles; Go 1.20 has no sync.OnceValues. -type dirKeys struct { - once sync.Once - retrieve func(context.Context) (masterkey.Set, error) - keys masterkey.Set - err error -} - -func (k *dirKeys) get(ctx context.Context) masterkey.Set { - k.once.Do(func() { k.keys, k.err = k.retrieve(ctx) }) - return k.keys -} - -// keysFromMachine asks this machine's secret stores; on macOS that includes the run's login keychain. -func keysFromMachine(keychain masterkey.LoginKeychain) dirKeysFunc { - return func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) { - locator, err := chromium.KeyLocator(dir, dirSnapshot) - if err != nil { - return nil, err - } - locator.Keychain = keychain - return masterkey.RetrieveAll(ctx, locator) - } -} - -func keysFromFile(keys map[browser.UserDataDirID]masterkey.Set) dirKeysFunc { - return func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) (masterkey.Set, error) { - return keys[dir.ID], nil - } -} diff --git a/internal/app/execute_test.go b/internal/app/execute_test.go index 369fe60..52ec789 100644 --- a/internal/app/execute_test.go +++ b/internal/app/execute_test.go @@ -54,10 +54,10 @@ func chromeDir(t *testing.T, id browser.UserDataDirID, profiles ...string) brows func run(t *testing.T, base extractorsFunc, keys dirKeysFunc, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) { t.Helper() - options := Options{Categories: categories, OutputDir: t.TempDir()} - summary, err := execute(context.Background(), newPlan(Discovery{Dirs: dirs}, options, base), options, base, keys) + output := Output{Dir: t.TempDir()} + summary, err := execute(context.Background(), Discovery{Dirs: dirs}, categories, output, base, keys) require.NoError(t, err) - return summary, options.OutputDir + return summary, output.Dir } func outcomes(summary Summary) map[category.Category]Result { @@ -118,6 +118,28 @@ func TestExecute_Outcomes(t *testing.T) { assert.Contains(t, string(data), `"profile": "Default"`) } +func TestExecute_ReportsEachDirWhatNeverRanFirst(t *testing.T) { + failed := DirFailure{UserDataDirID: "edge", Err: errors.New("permission denied")} + chrome, brave := chromeDir(t, "chrome", "Default"), chromeDir(t, "brave", "Default") + base := fakeBase(map[category.Category]extractFunc{ + category.History: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { return nil }, + }) + categories := []category.Category{category.Password, category.History} + discovery := Discovery{Dirs: []browser.UserDataDir{chrome, brave}, DirFailures: []DirFailure{failed}} + + summary, err := execute(context.Background(), discovery, categories, Output{Dir: t.TempDir()}, base, noKeys(t)) + require.NoError(t, err) + assert.Equal(t, []DirFailure{failed}, summary.DirFailures, "discovery's failures are reported with the run's") + var got []string + for _, result := range summary.Results { + got = append(got, fmt.Sprintf("%s/%s %s", result.UserDataDirID, result.Category, result.Outcome)) + } + assert.Equal(t, []string{ + "chrome/password unsupported", "chrome/history ok", + "brave/password unsupported", "brave/history ok", + }, got) +} + func TestExecute_KeysAreRetrievedOncePerUserDataDir(t *testing.T) { cookie := func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { out.Add(&record.Cookie{Value: string(profileSnapshot.MasterKeys(ctx)[masterkey.V10])}) @@ -140,11 +162,10 @@ func TestExecute_KeysAreRetrievedOncePerUserDataDir(t *testing.T) { summary, _ := run(t, base, keys, categories, chromeDir(t, "chrome", "Default", "Profile 1")) assert.Equal(t, 1, calls) - last := summary.Results[len(summary.Results)-1] - assert.Equal(t, Extraction{UserDataDirID: "chrome"}, last.Extraction, "a retrieval error is reported once, for the dir") - assert.Equal(t, OutcomeError, last.Outcome) - require.ErrorContains(t, last.Err, "v20: no ABE") - assert.Len(t, summary.Results, 5) + require.Len(t, summary.DirFailures, 1, "a retrieval error is reported once, for the dir") + assert.Equal(t, browser.UserDataDirID("chrome"), summary.DirFailures[0].UserDataDirID) + require.ErrorContains(t, summary.DirFailures[0].Err, "v20: no ABE") + assert.Len(t, summary.Results, 4) } // TestExecute_HistoryNeverRetrievesKeys checks nothing to decrypt means no key retrieval, so no prompt on macOS. @@ -206,10 +227,10 @@ func TestExecute_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testi return nil }, }) - options := Options{Categories: []category.Category{category.History, category.Download}, OutputDir: t.TempDir()} + categories := []category.Category{category.History, category.Download} discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default")}} - _, err := execute(ctx, newPlan(discovery, options, base), options, base, noKeys(t)) + _, err := execute(ctx, discovery, categories, Output{Dir: t.TempDir()}, base, noKeys(t)) require.ErrorIs(t, err, context.Canceled) require.Len(t, copied, 1, "the next user data dir is never captured") _, statErr := os.Stat(copied[0]) @@ -228,26 +249,14 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { return nil }, }) - options := Options{Categories: []category.Category{category.History}, OutputDir: t.TempDir()} - require.NoError(t, os.Chmod(options.OutputDir, 0o500)) - defer func() { require.NoError(t, os.Chmod(options.OutputDir, 0o700)) }() + output := Output{Dir: t.TempDir()} + require.NoError(t, os.Chmod(output.Dir, 0o500)) + defer func() { require.NoError(t, os.Chmod(output.Dir, 0o700)) }() - plan := newPlan(Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default")}}, options, base) - _, err := execute(context.Background(), plan, options, base, noKeys(t)) + discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default")}} + _, err := execute(context.Background(), discovery, []category.Category{category.History}, output, base, noKeys(t)) require.Error(t, err) require.NotEmpty(t, copied) _, statErr := os.Stat(copied) assert.ErrorIs(t, statErr, fs.ErrNotExist) } - -func TestExecute_ImportedKeys(t *testing.T) { - want := masterkey.Set{masterkey.V10: []byte("dumped")} - keys := keysFromFile(map[browser.UserDataDirID]masterkey.Set{"chrome": want}) - got, err := keys(context.Background(), browser.UserDataDir{ID: "chrome"}, snapshot.Snapshot{}) - require.NoError(t, err) - assert.Equal(t, want, got) - - got, err = keys(context.Background(), browser.UserDataDir{ID: "edge"}, snapshot.Snapshot{}) - require.NoError(t, err) - assert.Empty(t, got, "a dump without the dir's keys decrypts nothing") -} diff --git a/internal/app/extract_golden_test.go b/internal/app/extract_golden_test.go index bf8f116..b1eb7fe 100644 --- a/internal/app/extract_golden_test.go +++ b/internal/app/extract_golden_test.go @@ -59,12 +59,11 @@ func TestExtractGoldenSafari(t *testing.T) { func extractGoldenRun(t *testing.T, home string, keys map[browser.UserDataDirID]masterkey.Set, format string) string { t.Helper() out := t.TempDir() - options, err := app.ValidateDump(app.Flags{Browser: "all", Categories: "all", Format: format, OutputDir: out}) + options, err := app.ValidateDump(app.DumpFlags{Browser: "all", Categories: "all", Format: format, OutputDir: out}, nil) require.NoError(t, err) - options.HomeDir, options.ImportedKeys = home, keys + options.Target.HomeDir = home - plan := app.NewPlan(app.Discover(options), options) - _, err = app.Execute(context.Background(), plan, options) + _, err = app.ExecuteWithKeys(context.Background(), app.Discover(options.Target), options.Categories, options.Output, keys) require.NoError(t, err) return out } diff --git a/internal/app/keychain_darwin.go b/internal/app/keychain_darwin.go index a203612..ffcb1e9 100644 --- a/internal/app/keychain_darwin.go +++ b/internal/app/keychain_darwin.go @@ -14,12 +14,12 @@ import ( ) // newLoginKeychain builds the run's login keychain without opening it, so a run that never decrypts never prompts. -func newLoginKeychain(options Options) loginKeychain { - path := filepath.Join(options.HomeDir, "Library", "Keychains", "login.keychain-db") - if options.KeychainPassword == nil { +func newLoginKeychain(config KeychainConfig) loginKeychain { + path := filepath.Join(config.HomeDir, "Library", "Keychains", "login.keychain-db") + if config.Password == nil { return keychain.New(path, func(context.Context) (string, error) { return "", nil }) } - return &reportingKeychain{Keychain: keychain.New(path, keychain.PasswordFunc(options.KeychainPassword))} + return &reportingKeychain{Keychain: keychain.New(path, keychain.PasswordFunc(config.Password))} } // reportingKeychain says once why the keychain stayed locked, since every consumer then reads metadata only, quietly. diff --git a/internal/app/keychain_other.go b/internal/app/keychain_other.go index 0d1a75e..400c77e 100644 --- a/internal/app/keychain_other.go +++ b/internal/app/keychain_other.go @@ -2,4 +2,4 @@ package app -func newLoginKeychain(Options) loginKeychain { return nil } +func newLoginKeychain(KeychainConfig) loginKeychain { return nil } diff --git a/internal/app/list.go b/internal/app/list.go new file mode 100644 index 0000000..2f55a77 --- /dev/null +++ b/internal/app/list.go @@ -0,0 +1,34 @@ +package app + +import ( + "context" + + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +// ListOptions is what list reads: every browser and category, with the keychain left locked, so counting never prompts. +func ListOptions() (Options, error) { + home, err := homeDir() + if err != nil { + return Options{}, err + } + return Options{ + Target: Target{BrowserName: allBrowsers, HomeDir: home}, + Categories: category.All(), + Keychain: KeychainConfig{HomeDir: home}, + }, nil +} + +// CountRecords runs with no key and the keychain locked, counting records instead of exporting them. +func CountRecords( + ctx context.Context, discovery Discovery, categories []category.Category, keychainConfig KeychainConfig, +) (Summary, error) { + keychain := newLoginKeychain(keychainConfig) + counter := runner{writer: discard{}, extractors: extractorsWith(keychain), retrieveKeys: keysFromFile(nil)} + return counter.run(ctx, discovery, categories) +} + +type discard struct{} + +func (discard) Write(category.Category, []record.Record) error { return nil } diff --git a/internal/app/masterkeys.go b/internal/app/masterkeys.go new file mode 100644 index 0000000..a5038d9 --- /dev/null +++ b/internal/app/masterkeys.go @@ -0,0 +1,57 @@ +package app + +import ( + "context" + "sync" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" + "github.com/moond4rk/hackbrowserdata/internal/browser/safari" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" +) + +// loginKeychain is the run's one login keychain, shared by Chromium's v10 key and Safari's passwords; nil off macOS. +type loginKeychain interface { + masterkey.LoginKeychain + safari.LoginKeychain +} + +type dirKeysFunc func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) + +// dirKeys retrieves a dir's keys on first use, for all its profiles; Go 1.20 has no sync.OnceValues. +type dirKeys struct { + once sync.Once + retrieve dirKeysFunc // nil for a dir whose base keeps no master keys + dir browser.UserDataDir + dirSnapshot snapshot.Snapshot + keys masterkey.Set + err error +} + +func (k *dirKeys) get(ctx context.Context) masterkey.Set { + k.once.Do(func() { + if k.retrieve != nil { + k.keys, k.err = k.retrieve(ctx, k.dir, k.dirSnapshot) + } + }) + return k.keys +} + +// keysFromMachine asks this machine's secret stores; on macOS that includes the run's login keychain. +func keysFromMachine(keychain masterkey.LoginKeychain) dirKeysFunc { + return func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) { + locator, err := chromium.KeyLocator(dir, dirSnapshot) + if err != nil { + return nil, err + } + locator.Keychain = keychain + return masterkey.RetrieveAll(ctx, locator) + } +} + +func keysFromFile(keys map[browser.UserDataDirID]masterkey.Set) dirKeysFunc { + return func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) (masterkey.Set, error) { + return keys[dir.ID], nil + } +} diff --git a/internal/app/masterkeys_test.go b/internal/app/masterkeys_test.go new file mode 100644 index 0000000..ef55c41 --- /dev/null +++ b/internal/app/masterkeys_test.go @@ -0,0 +1,25 @@ +package app + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" +) + +func TestKeysFromFile(t *testing.T) { + want := masterkey.Set{masterkey.V10: []byte("dumped")} + keys := keysFromFile(map[browser.UserDataDirID]masterkey.Set{"chrome": want}) + got, err := keys(context.Background(), browser.UserDataDir{ID: "chrome"}, snapshot.Snapshot{}) + require.NoError(t, err) + assert.Equal(t, want, got) + + got, err = keys(context.Background(), browser.UserDataDir{ID: "edge"}, snapshot.Snapshot{}) + require.NoError(t, err) + assert.Empty(t, got, "a dump without the dir's keys decrypts nothing") +} diff --git a/internal/app/options.go b/internal/app/options.go new file mode 100644 index 0000000..5943a71 --- /dev/null +++ b/internal/app/options.go @@ -0,0 +1,120 @@ +package app + +import ( + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/export" +) + +// Options are a command's validated flags, grouped by the stage that reads them; a command leaves the rest empty. +type Options struct { + Target Target + Categories []category.Category + Output Output + Keychain KeychainConfig +} + +// Target is what Discover looks for. +type Target struct { + BrowserName string // "all" or one Browser.Name + ProfilePath string // a custom profile dir, used only with one browser + HomeDir string +} + +// Output is where and how Execute writes records. +type Output struct { + Dir string + Format export.Format + Zip bool +} + +// KeychainConfig locates the macOS login keychain and says how to get its password; other systems ignore it. +type KeychainConfig struct { + HomeDir string + // Password runs when the keychain first opens; "" leaves it locked, and nil, as list has it, silently. + Password func(ctx context.Context) (string, error) +} + +func homeDir() (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("home directory: %w", err) + } + return home, nil +} + +const allBrowsers = "all" + +// parseBrowser accepts all or one of this OS's browser names; a name from another OS's table has nothing to find here. +func parseBrowser(value string) (string, error) { + name := strings.ToLower(strings.TrimSpace(value)) + if name == "" || name == allBrowsers { + return allBrowsers, nil + } + for _, supportedBrowser := range browser.Supported() { + if supportedBrowser.Name == name { + return name, nil + } + } + return "", fmt.Errorf("unknown browser %q, available: %s|%s", value, allBrowsers, strings.Join(browser.Names(), "|")) +} + +// parseCategories keeps a repeated category once, or its records would be exported twice. +func parseCategories(value string) ([]category.Category, error) { + value = strings.TrimSpace(value) + if strings.EqualFold(value, "all") { + return category.All(), nil + } + var categories []category.Category + seen := make(map[category.Category]bool) + for _, name := range strings.Split(value, ",") { + name = strings.TrimSpace(strings.ToLower(name)) + if name == "" { + continue + } + dataCategory, err := category.Parse(name) + if err != nil { + return nil, fmt.Errorf("%w, available: all|%s", err, strings.Join(category.Names(), ",")) + } + if !seen[dataCategory] { + seen[dataCategory] = true + categories = append(categories, dataCategory) + } + } + if len(categories) == 0 { + return nil, fmt.Errorf("no categories specified") + } + return categories, nil +} + +// checkOutputDir creates nothing: -d, or its nearest existing ancestor, must be a directory we can create in. +func checkOutputDir(dir string) error { + path := filepath.Clean(dir) + for { + info, err := os.Stat(path) + switch { + case err == nil && info.IsDir(): + if err := canCreateIn(path); err != nil { + return fmt.Errorf("output dir %s: %w", dir, err) + } + return nil + case err == nil: + return fmt.Errorf("output dir %s: %s is not a directory", dir, path) + case !errors.Is(err, fs.ErrNotExist): + return fmt.Errorf("output dir %s: %w", dir, err) + } + parent := filepath.Dir(path) + if parent == path { + return fmt.Errorf("output dir %s: no existing parent directory", dir) + } + path = parent + } +} diff --git a/internal/app/plan.go b/internal/app/plan.go index 8bb8853..4b3fda1 100644 --- a/internal/app/plan.go +++ b/internal/app/plan.go @@ -11,71 +11,65 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// Extraction is plain data, looked up again when it runs, so a Plan prints as it is and compares with DeepEqual. -type Extraction struct { - UserDataDirID browser.UserDataDirID - ProfileName string // Profile.Name; "" in a result about a whole user data dir - Category category.Category // zero in a result about a whole user data dir +// dirPlan is what runDir does for one user data dir, decided from which files exist before anything is copied. +type dirPlan struct { + extractions []plannedExtraction // to run, in output order + files []snapshot.File // what they read, each copied once + skipped []Result // requested extractions that will not run, and why } -// Plan lists extractions in output order, each file to capture once, and the requested extractions that cannot run. -type Plan struct { - Dirs []browser.UserDataDir - Files []snapshot.File - Extractions []Extraction - Skipped []Result +// plannedExtraction keeps the extractor that planning checked, so the run uses that same extractor. +type plannedExtraction struct { + Extraction + profile browser.Profile + extractor browser.Extractor } type extractorsFunc func(browser.UserDataDir, browser.Profile) browser.Extractors -// NewPlan only stats the files the extractors' sources name, so it opens nothing and needs no keychain. -func NewPlan(discovery Discovery, options Options) Plan { - return newPlan(discovery, options, extractorsWith(nil)) -} - -func newPlan(discovery Discovery, options Options, extractors extractorsFunc) Plan { - plan := Plan{Dirs: discovery.Dirs, Skipped: append([]Result(nil), discovery.Errors...)} +func planDir(dir browser.UserDataDir, categories []category.Category, extractors extractorsFunc) dirPlan { + var plan dirPlan captured := make(map[snapshot.File]bool) - for _, dir := range discovery.Dirs { - for _, profile := range dir.Profiles { - profileExtractors := extractors(dir, profile) - for _, dataCategory := range options.Categories { - extraction := Extraction{UserDataDirID: dir.ID, ProfileName: profile.Name, Category: dataCategory} - extractor, ok := profileExtractors[dataCategory] - if !ok { - plan.Skipped = append(plan.Skipped, Result{Extraction: extraction, Outcome: OutcomeUnsupported}) - continue - } - files, ok, err := locate(dir, profile, extractor.Sources) - if err != nil { - plan.Skipped = append(plan.Skipped, Result{Extraction: extraction, Outcome: OutcomeError, Err: err}) - continue - } - if !ok { - plan.Skipped = append(plan.Skipped, Result{Extraction: extraction, Outcome: OutcomeAbsent}) - continue - } - plan.Extractions = append(plan.Extractions, extraction) - for _, file := range files { - if !captured[file] { - captured[file] = true - plan.Files = append(plan.Files, file) - } - } + for _, profile := range dir.Profiles { + profileExtractors := extractors(dir, profile) + for _, dataCategory := range categories { + extraction := Extraction{UserDataDirID: dir.ID, ProfileName: profile.Name, Category: dataCategory} + extractor, supported := profileExtractors[dataCategory] + if !supported { + plan.skipped = append(plan.skipped, Result{Extraction: extraction, Outcome: OutcomeUnsupported}) + continue + } + files, present, err := locate(dir, profile, extractor.Sources) + switch { + case err != nil: + plan.skipped = append(plan.skipped, Result{Extraction: extraction, Outcome: OutcomeError, Err: err}) + case !present: + plan.skipped = append(plan.skipped, Result{Extraction: extraction, Outcome: OutcomeAbsent}) + default: + plan.extractions = append(plan.extractions, plannedExtraction{Extraction: extraction, profile: profile, extractor: extractor}) + plan.files = appendNew(plan.files, captured, files...) } } } return plan } +func appendNew(files []snapshot.File, seen map[snapshot.File]bool, more ...snapshot.File) []snapshot.File { + for _, file := range more { + if !seen[file] { + seen[file] = true + files = append(files, file) + } + } + return files +} + // locate needs every required file and one of the profile's own: Local State alone never makes an extraction present. // One that reads no file always runs, and a candidate that cannot be checked is an error, not absence. -func locate(dir browser.UserDataDir, profile browser.Profile, sources []browser.Source) ([]snapshot.File, bool, error) { +func locate(dir browser.UserDataDir, profile browser.Profile, sources []browser.Source) (files []snapshot.File, present bool, err error) { if len(sources) == 0 { return nil, true, nil } - var files []snapshot.File - present := false for _, source := range sources { file, ok, err := firstOnDisk(dir, profile, source) switch { diff --git a/internal/app/plan_test.go b/internal/app/plan_test.go index 0fec8f5..59b2b53 100644 --- a/internal/app/plan_test.go +++ b/internal/app/plan_test.go @@ -1,7 +1,6 @@ package app import ( - "errors" "io/fs" "os" "path/filepath" @@ -30,7 +29,15 @@ func lookup(t *testing.T, name string) browser.Browser { return namedBrowser } -func TestNewPlan(t *testing.T) { +func extractionsOf(plan dirPlan) []Extraction { + var extractions []Extraction + for _, planned := range plan.extractions { + extractions = append(extractions, planned.Extraction) + } + return extractions +} + +func TestPlanDir(t *testing.T) { path := t.TempDir() touch(t, path, "Local State") touch(t, path, "Default", "Login Data") @@ -41,10 +48,9 @@ func TestNewPlan(t *testing.T) { ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}, {Name: "Profile 1", RelativePath: "Profile 1"}}, } - failed := dirFailure("edge", errors.New("permission denied")) - options := Options{Categories: []category.Category{category.Password, category.Cookie, category.History, category.Download, category.CreditCard}} + categories := []category.Category{category.Password, category.Cookie, category.History, category.Download, category.CreditCard} - got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}, Errors: []Result{failed}}, options) + plan := planDir(dir, categories, extractorsWith(nil)) file := func(relativePath string) snapshot.File { return snapshot.File{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: relativePath} @@ -55,69 +61,65 @@ func TestNewPlan(t *testing.T) { skipped := func(profile string, dataCategory category.Category, outcome Outcome) Result { return Result{Extraction: extraction(profile, dataCategory), Outcome: outcome} } - assert.Equal(t, Plan{ - Dirs: []browser.UserDataDir{dir}, - // Local State and History are captured once, however many extractions read them. - Files: []snapshot.File{ - file("Default/Login Data"), file("Local State"), file("Default/Network/Cookies"), file("Default/History"), - file("Profile 1/History"), - }, - Extractions: []Extraction{ - extraction("Default", category.Password), extraction("Default", category.Cookie), - extraction("Default", category.History), extraction("Default", category.Download), - extraction("Profile 1", category.History), extraction("Profile 1", category.Download), - }, - Skipped: []Result{ - failed, - skipped("Default", category.CreditCard, OutcomeAbsent), - // Local State alone does not make a profile's passwords present. - skipped("Profile 1", category.Password, OutcomeAbsent), - skipped("Profile 1", category.Cookie, OutcomeAbsent), - skipped("Profile 1", category.CreditCard, OutcomeAbsent), - }, - }, got) + assert.Equal(t, []Extraction{ + extraction("Default", category.Password), extraction("Default", category.Cookie), + extraction("Default", category.History), extraction("Default", category.Download), + extraction("Profile 1", category.History), extraction("Profile 1", category.Download), + }, extractionsOf(plan)) + assert.Equal(t, []snapshot.File{ + file("Default/Login Data"), file("Local State"), file("Default/Network/Cookies"), file("Default/History"), + file("Profile 1/History"), + }, plan.files, "Local State and History are copied once, however many extractions read them") + assert.Equal(t, []Result{ + skipped("Default", category.CreditCard, OutcomeAbsent), + // Local State alone does not make a profile's passwords present. + skipped("Profile 1", category.Password, OutcomeAbsent), + skipped("Profile 1", category.Cookie, OutcomeAbsent), + skipped("Profile 1", category.CreditCard, OutcomeAbsent), + }, plan.skipped) + assert.Equal(t, dir.Profiles[1], plan.extractions[4].profile) } -func TestNewPlan_PicksTheFirstCandidateOnDisk(t *testing.T) { +func TestPlanDir_PicksTheFirstCandidateOnDisk(t *testing.T) { path := t.TempDir() touch(t, path, "Default", "Cookies") dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}}} - got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.Cookie}}) - assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Cookies"}}, got.Files) + plan := planDir(dir, []category.Category{category.Cookie}, extractorsWith(nil)) + assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Cookies"}}, plan.files) } -func TestNewPlan_FlatLayoutProfile(t *testing.T) { +func TestPlanDir_FlatLayoutProfile(t *testing.T) { path := t.TempDir() touch(t, path, "History") dir := browser.UserDataDir{ID: "opera", Browser: lookup(t, "opera"), Path: path, Profiles: []browser.Profile{{Name: "Opera Stable"}}} - got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.History}}) - assert.Equal(t, []snapshot.File{{UserDataDirID: "opera", UserDataDirPath: path, RelativePath: "History"}}, got.Files) - assert.Equal(t, []Extraction{{UserDataDirID: "opera", ProfileName: "Opera Stable", Category: category.History}}, got.Extractions) + plan := planDir(dir, []category.Category{category.History}, extractorsWith(nil)) + assert.Equal(t, []snapshot.File{{UserDataDirID: "opera", UserDataDirPath: path, RelativePath: "History"}}, plan.files) + assert.Equal(t, []Extraction{{UserDataDirID: "opera", ProfileName: "Opera Stable", Category: category.History}}, extractionsOf(plan)) } -func TestNewPlan_UnsupportedCategory(t *testing.T) { +func TestPlanDir_UnsupportedCategory(t *testing.T) { dir := browser.UserDataDir{ID: "x", Path: t.TempDir(), Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}}} none := func(browser.UserDataDir, browser.Profile) browser.Extractors { return browser.Extractors{} } - got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.CreditCard}}, none) + plan := planDir(dir, []category.Category{category.CreditCard}, none) assert.Equal(t, []Result{{Extraction: Extraction{UserDataDirID: "x", ProfileName: "Default", Category: category.CreditCard}, Outcome: OutcomeUnsupported}}, - got.Skipped) - assert.Empty(t, got.Extractions) + plan.skipped) + assert.Empty(t, plan.extractions) } -// TestNewPlan_ExtractorWithoutFileSpecsRuns covers Safari's passwords: read from the keychain, they are never absent. -func TestNewPlan_ExtractorWithoutFileSpecsRuns(t *testing.T) { +// TestPlanDir_ExtractorWithoutSourcesRuns covers Safari's passwords: read from the keychain, they are never absent. +func TestPlanDir_ExtractorWithoutSourcesRuns(t *testing.T) { dir := browser.UserDataDir{ID: "safari", Path: t.TempDir(), Profiles: []browser.Profile{{Name: "default", RelativePath: "Safari"}}} keychainOnly := func(browser.UserDataDir, browser.Profile) browser.Extractors { return browser.Extractors{category.Password: {}} } - got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.Password}}, keychainOnly) - assert.Equal(t, []Extraction{{UserDataDirID: "safari", ProfileName: "default", Category: category.Password}}, got.Extractions) - assert.Empty(t, got.Files) - assert.Empty(t, got.Skipped) + plan := planDir(dir, []category.Category{category.Password}, keychainOnly) + assert.Equal(t, []Extraction{{UserDataDirID: "safari", ProfileName: "default", Category: category.Password}}, extractionsOf(plan)) + assert.Empty(t, plan.files) + assert.Empty(t, plan.skipped) } // lock makes dir unsearchable until the test ends, so a Stat of anything under it fails with permission denied. @@ -133,16 +135,16 @@ func lock(t *testing.T, dir string) { t.Cleanup(func() { assert.NoError(t, os.Chmod(dir, 0o700)) }) } -func TestNewPlan_UnreadableFileIsAnError(t *testing.T) { +func TestPlanDir_UnreadableFileIsAnError(t *testing.T) { dir := chromeDir(t, "chrome", "Default") lock(t, filepath.Join(dir.Path, "Default")) base := fakeBase(map[category.Category]extractFunc{category.History: nil}) - got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.History}}, base) + plan := planDir(dir, []category.Category{category.History}, base) - require.Len(t, got.Skipped, 1) - assert.Equal(t, OutcomeError, got.Skipped[0].Outcome) - require.ErrorIs(t, got.Skipped[0].Err, fs.ErrPermission) - assert.Empty(t, got.Extractions) - assert.Empty(t, got.Files) + require.Len(t, plan.skipped, 1) + assert.Equal(t, OutcomeError, plan.skipped[0].Outcome) + require.ErrorIs(t, plan.skipped[0].Err, fs.ErrPermission) + assert.Empty(t, plan.extractions) + assert.Empty(t, plan.files) } diff --git a/internal/app/report.go b/internal/app/report.go index e74ccc9..18fdcaa 100644 --- a/internal/app/report.go +++ b/internal/app/report.go @@ -10,15 +10,12 @@ import ( func Report(writer io.Writer, summary Summary) error { table := tabwriter.NewWriter(writer, 0, 0, 2, ' ', 0) fmt.Fprintln(table, "Browser\tProfile\tCategory\tResult\tRecords\tDetail") + for _, failure := range summary.DirFailures { + fmt.Fprintf(table, "%s\t-\t-\t%s\t0\t%s\n", failure.UserDataDirID, OutcomeError, failure.Err) + } for _, result := range summary.Results { - profile, cat := "-", "-" - if result.ProfileName != "" { - profile = result.ProfileName - } - if result.Category != 0 { - cat = result.Category.String() - } - fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%d\t%s\n", result.UserDataDirID, profile, cat, result.Outcome, result.Records, detail(result)) + fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%d\t%s\n", + result.UserDataDirID, result.ProfileName, result.Category, result.Outcome, result.Records, detail(result)) } return table.Flush() } diff --git a/internal/app/report_test.go b/internal/app/report_test.go index a247e9d..61ef9af 100644 --- a/internal/app/report_test.go +++ b/internal/app/report_test.go @@ -15,15 +15,17 @@ import ( func TestReport(t *testing.T) { cookie := Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Cookie} var buffer bytes.Buffer - require.NoError(t, Report(&buffer, Summary{Results: []Result{ - {Extraction: cookie, Outcome: OutcomePartial, Records: 224, Failures: 4}, - dirFailure("arc-2", errors.New("permission denied")), - {Extraction: Extraction{UserDataDirID: "edge", ProfileName: "Default", Category: category.Password}}, - }})) + require.NoError(t, Report(&buffer, Summary{ + Results: []Result{ + {Extraction: cookie, Outcome: OutcomePartial, Records: 224, Failures: 4}, + {Extraction: Extraction{UserDataDirID: "edge", ProfileName: "Default", Category: category.Password}}, + }, + DirFailures: []DirFailure{{UserDataDirID: "arc-2", Err: errors.New("permission denied")}}, + })) lines := strings.Split(strings.TrimSpace(buffer.String()), "\n") require.Len(t, lines, 4) - assert.Equal(t, []string{"chrome", "Default", "cookie", "partial", "224", "4", "not", "recovered"}, strings.Fields(lines[1])) - assert.Equal(t, []string{"arc-2", "-", "-", "error", "0", "permission", "denied"}, strings.Fields(lines[2])) + assert.Equal(t, []string{"arc-2", "-", "-", "error", "0", "permission", "denied"}, strings.Fields(lines[1]), "a dir failure leads") + assert.Equal(t, []string{"chrome", "Default", "cookie", "partial", "224", "4", "not", "recovered"}, strings.Fields(lines[2])) assert.Equal(t, "unset", strings.Fields(lines[3])[3], "a result whose outcome was never set must not read as ok") } diff --git a/internal/app/restore.go b/internal/app/restore.go index a2c4a71..3b2b328 100644 --- a/internal/app/restore.go +++ b/internal/app/restore.go @@ -61,7 +61,11 @@ func ValidateRestore(flags RestoreFlags) (Options, masterkey.KeyFile, error) { if filter != allBrowsers && len(vaultsOf(keyFile, filter)) == 0 { return Options{}, masterkey.KeyFile{}, fmt.Errorf("no vault for browser %q in keys (have: %s)", filter, vaultBrowserNames(keyFile.Vaults)) } - options := Options{BrowserName: filter, Categories: categories, Format: format, OutputDir: flags.OutputDir, Zip: flags.Zip} + options := Options{ + Target: Target{BrowserName: filter}, + Categories: categories, + Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip}, + } return options, keyFile, nil } @@ -98,9 +102,9 @@ func readKeyFile(path string) (masterkey.KeyFile, error) { // DiscoverRestore rebuilds the user data dirs under root, and their keys, from the key file: each vault names a // subdirectory of root, or root is one browser's User Data. func DiscoverRestore( - root string, keyFile masterkey.KeyFile, options Options, + root string, keyFile masterkey.KeyFile, browserName string, ) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) { - vaults := vaultsOf(keyFile, options.BrowserName) + vaults := vaultsOf(keyFile, browserName) archived := false for _, vault := range vaults { if dirExists(filepath.Join(root, string(vaultUserDataDirID(vault)))) { diff --git a/internal/app/restore_golden_test.go b/internal/app/restore_golden_test.go index 340f588..6bd9c6e 100644 --- a/internal/app/restore_golden_test.go +++ b/internal/app/restore_golden_test.go @@ -105,10 +105,9 @@ func restoreGolden(t *testing.T, flags app.RestoreFlags) string { } defer data.Close() - discovery, keys, err := app.DiscoverRestore(data.Path(), keyFile, options) + discovery, keys, err := app.DiscoverRestore(data.Path(), keyFile, options.Target.BrowserName) require.NoError(t, err) - options.ImportedKeys = keys - _, err = app.Execute(context.Background(), app.NewPlan(discovery, options), options) + _, err = app.ExecuteWithKeys(context.Background(), discovery, options.Categories, options.Output, keys) require.NoError(t, err) return flags.OutputDir } diff --git a/internal/app/restore_test.go b/internal/app/restore_test.go index 94433f9..3162ab3 100644 --- a/internal/app/restore_test.go +++ b/internal/app/restore_test.go @@ -55,7 +55,7 @@ func TestValidateRestore_RejectsBadInput(t *testing.T) { options, keyFile, err := ValidateRestore(RestoreFlags{KeyFile: keys, DataDir: data, Browser: "Chrome", Categories: "all", Format: "json", OutputDir: t.TempDir()}) require.NoError(t, err) - assert.Equal(t, "chrome", options.BrowserName) + assert.Equal(t, "chrome", options.Target.BrowserName) assert.Len(t, keyFile.Vaults, 1) } @@ -68,7 +68,7 @@ func TestDiscoverRestore_SecondUserDataDir(t *testing.T) { second.Keys = masterkey.Set{masterkey.V10: []byte("arc-2")} keyFile := masterkey.KeyFile{Vaults: []masterkey.Vault{testVault("chrome"), testVault("arc"), second}} - discovery, keys, err := DiscoverRestore(root, keyFile, Options{BrowserName: "arc"}) + discovery, keys, err := DiscoverRestore(root, keyFile, "arc") require.NoError(t, err) assert.Equal(t, []browser.UserDataDirID{"arc", "arc-2"}, userDataDirIDs(discovery), "a vault's ID names its directory") assert.Equal(t, filepath.Join(root, "arc-2"), discovery.Dirs[1].Path) @@ -84,7 +84,7 @@ func TestDiscoverRestore_FromLayout(t *testing.T) { nightly.Kind = "chromium-yandex" keyFile := masterkey.KeyFile{Vaults: []masterkey.Vault{testVault("chrome"), nightly, testVault("chrome"), testVault("edge")}} - discovery, keys, err := DiscoverRestore(root, keyFile, Options{BrowserName: "all"}) + discovery, keys, err := DiscoverRestore(root, keyFile, "all") require.NoError(t, err) assert.Equal(t, []browser.UserDataDirID{"chrome", "nightly"}, userDataDirIDs(discovery), "a repeated vault restores once, one without data not at all") assert.Len(t, keys, 2) @@ -98,10 +98,10 @@ func TestDiscoverRestore_OneUserDataNeedsOneVault(t *testing.T) { touch(t, root, "Default", "History") keyFile := masterkey.KeyFile{Vaults: []masterkey.Vault{testVault("chrome"), testVault("edge")}} - _, _, err := DiscoverRestore(root, keyFile, Options{BrowserName: "all"}) + _, _, err := DiscoverRestore(root, keyFile, "all") require.Error(t, err) - discovery, _, err := DiscoverRestore(root, keyFile, Options{BrowserName: "edge"}) + discovery, _, err := DiscoverRestore(root, keyFile, "edge") require.NoError(t, err) require.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery)) assert.Equal(t, root, discovery.Dirs[0].Path) diff --git a/internal/app/result.go b/internal/app/result.go index b41b3f4..8c015cf 100644 --- a/internal/app/result.go +++ b/internal/app/result.go @@ -1,6 +1,17 @@ package app -import "github.com/moond4rk/hackbrowserdata/internal/browser" +import ( + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/export" +) + +// Extraction is plain data, so a Result prints as it is and list can key record counts by it. +type Extraction struct { + UserDataDirID browser.UserDataDirID + ProfileName string // Profile.Name + Category category.Category +} // Outcome is how one extraction ended. It starts at 1, so a result whose outcome was never set does not read as ok. type Outcome int @@ -30,7 +41,7 @@ func (o Outcome) String() string { } } -// Result is one extraction's outcome, or a failure of a whole user data dir when Profile and Category are empty. +// Result is one extraction's outcome. type Result struct { Extraction Outcome Outcome @@ -39,11 +50,15 @@ type Result struct { Err error // set when Outcome is OutcomeError } -// Summary is every result of a run, in output order: what never ran first, then each user data dir's extractions. -type Summary struct { - Results []Result +// DirFailure is a whole user data dir that could not be read, or whose master keys could not be retrieved. +type DirFailure struct { + UserDataDirID browser.UserDataDirID + Err error } -func dirFailure(id browser.UserDataDirID, err error) Result { - return Result{Extraction: Extraction{UserDataDirID: id}, Outcome: OutcomeError, Err: err} +// Summary lists each dir's results in turn, what never ran before what ran, and the dirs that failed as a whole. +type Summary struct { + Results []Result + DirFailures []DirFailure + Exported export.Output // the files Execute wrote; empty when nothing was exported } diff --git a/internal/browser/safari/profiles_test.go b/internal/browser/safari/profiles_test.go index 4556f15..3b676b8 100644 --- a/internal/browser/safari/profiles_test.go +++ b/internal/browser/safari/profiles_test.go @@ -117,7 +117,7 @@ func TestDiscover_EmptyDBIsAuthoritative(t *testing.T) { assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home)) } -// TestDiscover_MissingDBFallsBackToReadDir lists the Profiles dir, keeping dirs without data: presence is Plan's call. +// TestDiscover_MissingDBFallsBackToReadDir lists the Profiles dir, keeping dirs without data: presence is planning's call. func TestDiscover_MissingDBFallsBackToReadDir(t *testing.T) { const uuid = "11111111-2222-3333-4444-555555555555" const empty = "4E2D8DD0-A7D2-4684-939A-898B7675C700" diff --git a/rfcs/001-architecture.md b/rfcs/001-architecture.md index 7448b2d..4a96f92 100644 --- a/rfcs/001-architecture.md +++ b/rfcs/001-architecture.md @@ -6,13 +6,13 @@ A run is a fixed, one-way sequence of stages, and no stage reaches back: 1. **Validate** — turn the flags into options, and reject bad input before anything is touched. 2. **Discover** — find each browser's data directories and their profiles. -3. **Plan** — cross directories, profiles, and requested categories into extractions, record why each skipped one cannot run, and list the files to copy. +3. **Plan** — cross one directory's profiles with the requested categories into extractions, record why each skipped one cannot run, and list the files to copy. 4. **Capture** — copy one directory's planned files into a temporary snapshot. 5. **Extract** — parse the snapshot into records, fetching a secret only when a record needs it. 6. **Export** — append each extraction's records to the output files. 7. **Report** — summarize every outcome. -Capture, Extract, and Export run once per data directory, so at most one directory's copies are on disk at a time. Every command is a cut of this pipeline: `list` stops after discovery, `list --detail` counts records instead of exporting them, `archive` captures and zips, `dumpkeys` retrieves keys only, and `restore` extracts from a snapshot it is given. +Plan, Capture, Extract, and Export run once per data directory: a directory is planned right before its files are copied, and at most one directory's copies are on disk at a time. Every command is a cut of this pipeline: `list` stops after discovery, `list --detail` counts records instead of exporting them, `archive` captures and zips, `dumpkeys` retrieves keys only, and `restore` extracts from a snapshot it is given. **Why.** When each browser runs the whole flow itself, every concern is solved several times, and bugs hide where nothing else checks them. Named stages implement each concern once; a browser contributes only where its files are and how to read them.