mirror of
https://github.com/moonD4rk/HackBrowserData.git
synced 2026-12-04 05:43:27 +01:00
refactor(app): export one function per command (#712)
* refactor(app): export one function per command Step 2 of #710. A command's logic was split between cmd and stage-shaped app calls; cmd now parses flags, calls one function and prints what it returns. An error means the command never ran, and a run that ended early says so in Summary.Err. * fix(app): check dumpkeys and archive -o up front A missing output directory was reported only after the keys were retrieved or the files copied. * docs(rfcs): move restore's input out of the command layer Restore now discovers its directories in an archive itself, so the command layer no longer holds the data it reads.
This commit is contained in:
1 parent
6ddfe48493
commit
a734e777a8
35 files changed
+513
-439
No files matched your search
@@ -8,10 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func newArchiveCommand() *cobra.Command {
|
||||
var (
|
||||
flags app.ArchiveFlags
|
||||
outputPath string
|
||||
)
|
||||
var flags app.ArchiveFlags
|
||||
|
||||
command := &cobra.Command{
|
||||
Use: "archive",
|
||||
@@ -23,22 +20,22 @@ func newArchiveCommand() *cobra.Command {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
discovery := app.Discover(command.Context(), options.Target)
|
||||
if warnIfNothingFound(command.ErrOrStderr(), discovery, "no browsers found") {
|
||||
return nil
|
||||
}
|
||||
fileCount, err := app.Archive(command.Context(), discovery, options.Categories, outputPath)
|
||||
discovery, fileCount, err := app.Archive(command.Context(), options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infof("Archived %d entries to %s", fileCount, outputPath)
|
||||
if len(discovery.Dirs) == 0 {
|
||||
printNothingFound(command.ErrOrStderr(), discovery, "no browsers found")
|
||||
return nil
|
||||
}
|
||||
log.Infof("Archived %d entries to %s", fileCount, options.ArchivePath)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
|
||||
command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
command.Flags().StringVarP(&outputPath, "output", "o", "browser-data.zip", "output archive of decryption-relevant browser files")
|
||||
command.Flags().StringVarP(&flags.OutputPath, "output", "o", "browser-data.zip", "output archive of decryption-relevant browser files")
|
||||
|
||||
return command
|
||||
}
|
||||
@@ -13,8 +13,8 @@ import (
|
||||
func newDumpCommand() *cobra.Command {
|
||||
var (
|
||||
flags app.DumpFlags
|
||||
keychain keychainFlags
|
||||
firefox firefoxFlags
|
||||
keychain passwordFlags
|
||||
firefox passwordFlags
|
||||
)
|
||||
|
||||
command := &cobra.Command{
|
||||
@@ -32,31 +32,31 @@ func newDumpCommand() *cobra.Command {
|
||||
|
||||
command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames())
|
||||
command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
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, &keychain)
|
||||
addFirefoxPasswordFlags(command, &firefox)
|
||||
command.Flags().BoolVar(&flags.Zip, "zip", false, "compress output to zip")
|
||||
command.Flags().IntVar(&flags.MaxStorageValue, "max-storage-value", app.DefaultMaxStorageValue, "max storage value chars, 0=unlimited")
|
||||
addOutputFlags(command, &flags.Output)
|
||||
addPasswordFlags(command, &keychain, "keychain-pw", "macOS keychain password")
|
||||
addPasswordFlags(command, &firefox, "firefox-pw", "Firefox primary password")
|
||||
command.MarkFlagsMutuallyExclusive("keychain-pw-stdin", "firefox-pw-stdin")
|
||||
|
||||
return command
|
||||
}
|
||||
|
||||
func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychain keychainFlags, firefox firefoxFlags) error {
|
||||
func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychain, firefox passwordFlags) error {
|
||||
options, err := app.ValidateDump(flags, keychainPasswordFunc(keychain, os.Stdin), firefoxPasswordFunc(firefox, os.Stdin))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
discovery := app.Discover(ctx, options.Target)
|
||||
if warnIfNothingFound(stderr, discovery, "no browsers found") {
|
||||
discovery, summary, err := app.Dump(ctx, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(discovery.Dirs) == 0 {
|
||||
printNothingFound(stderr, discovery, "no browsers found")
|
||||
return nil
|
||||
}
|
||||
summary, err := app.Execute(ctx, discovery, options.Categories, options.Output, options.Keychain, options.FirefoxPassword)
|
||||
printExported(stderr, summary.Exported)
|
||||
if ctx.Err() == nil {
|
||||
printSummary(stderr, summary)
|
||||
}
|
||||
return err
|
||||
return summary.Err
|
||||
}
|
||||
@@ -11,9 +11,8 @@ import (
|
||||
|
||||
func newDumpKeysCommand() *cobra.Command {
|
||||
var (
|
||||
flags app.DumpKeysFlags
|
||||
keychain keychainFlags
|
||||
outputPath string
|
||||
flags app.DumpKeysFlags
|
||||
keychain passwordFlags
|
||||
)
|
||||
|
||||
command := &cobra.Command{
|
||||
@@ -26,8 +25,7 @@ func newDumpKeysCommand() *cobra.Command {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
discovery := app.Discover(command.Context(), options.Target)
|
||||
vaultCount, err := app.DumpKeys(command.Context(), discovery, options.Keychain, command.OutOrStdout(), outputPath)
|
||||
vaultCount, err := app.DumpKeys(command.Context(), options, command.OutOrStdout())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -37,8 +35,8 @@ 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, &keychain)
|
||||
command.Flags().StringVarP(&flags.OutputPath, "output", "o", "", "output file (default: stdout)")
|
||||
addPasswordFlags(command, &keychain, "keychain-pw", "macOS keychain password")
|
||||
|
||||
return command
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/app"
|
||||
)
|
||||
|
||||
// addOutputFlags defines the output flags once, so dump and restore keep one wording and one set of defaults.
|
||||
func addOutputFlags(command *cobra.Command, flags *app.OutputFlags) {
|
||||
command.Flags().StringVarP(&flags.Format, "format", "f", "json", "output format: csv|json|cookie-editor")
|
||||
command.Flags().StringVarP(&flags.Dir, "dir", "d", "results", "output directory")
|
||||
command.Flags().BoolVar(&flags.Zip, "zip", false, "compress output to zip")
|
||||
command.Flags().IntVar(&flags.MaxStorageValue, "max-storage-value", app.DefaultMaxStorageValue, "max storage value chars, 0=unlimited")
|
||||
}
|
||||
@@ -16,11 +16,10 @@ func newListCommand() *cobra.Command {
|
||||
Example: ` hack-browser-data list
|
||||
hack-browser-data list --detail`,
|
||||
RunE: func(command *cobra.Command, args []string) error {
|
||||
options, err := app.ValidateList()
|
||||
discovery, summary, err := app.List(command.Context(), detail)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
discovery := app.Discover(command.Context(), options.Target)
|
||||
for _, failure := range discovery.DirFailures {
|
||||
log.Warnf("%s: %v", failure.UserDataDirID, failure.Err)
|
||||
}
|
||||
@@ -31,10 +30,6 @@ func newListCommand() *cobra.Command {
|
||||
if !detail {
|
||||
return printProfiles(command.OutOrStdout(), discovery)
|
||||
}
|
||||
summary, err := app.CountRecords(command.Context(), discovery, options.Keychain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printRecordCounts(command.OutOrStdout(), discovery, summary)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -13,39 +13,27 @@ import (
|
||||
"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
|
||||
// passwordFlags say where one password comes from: its flag, or the first line of stdin. Neither leaves it to the
|
||||
// password's own default: a prompt or nothing for the keychain, the empty password for Firefox.
|
||||
type passwordFlags struct {
|
||||
value string
|
||||
fromStdin 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")
|
||||
}
|
||||
|
||||
// firefoxFlags say where a Firefox primary password comes from; both empty means the empty password, the common case.
|
||||
type firefoxFlags struct {
|
||||
password string
|
||||
passwordStdin bool
|
||||
}
|
||||
|
||||
func addFirefoxPasswordFlags(command *cobra.Command, flags *firefoxFlags) {
|
||||
command.Flags().StringVar(&flags.password, "firefox-pw", "", "Firefox primary password (visible in ps and shell history)")
|
||||
command.Flags().BoolVar(&flags.passwordStdin, "firefox-pw-stdin", false,
|
||||
"read the Firefox primary password from the first line of stdin")
|
||||
command.MarkFlagsMutuallyExclusive("firefox-pw", "firefox-pw-stdin")
|
||||
// addPasswordFlags defines --<name> and --<name>-stdin for the password that what names.
|
||||
func addPasswordFlags(command *cobra.Command, flags *passwordFlags, name, what string) {
|
||||
command.Flags().StringVar(&flags.value, name, "", what+" (visible in ps and shell history)")
|
||||
command.Flags().BoolVar(&flags.fromStdin, name+"-stdin", false, "read the "+what+" from the first line of stdin")
|
||||
command.MarkFlagsMutuallyExclusive(name, name+"-stdin")
|
||||
}
|
||||
|
||||
// firefoxPasswordFunc reads a flag, else the first line of stdin; nil means the empty password, and it never prompts.
|
||||
func firefoxPasswordFunc(flags firefoxFlags, stdin *os.File) func(context.Context) (string, error) {
|
||||
func firefoxPasswordFunc(flags passwordFlags, stdin *os.File) func(context.Context) (string, error) {
|
||||
switch {
|
||||
case flags.password != "":
|
||||
password := flags.password
|
||||
case flags.value != "":
|
||||
password := flags.value
|
||||
return func(context.Context) (string, error) { return password, nil }
|
||||
case flags.passwordStdin:
|
||||
case flags.fromStdin:
|
||||
return func(ctx context.Context) (string, error) {
|
||||
return untilDone(ctx, func() (string, error) { return firstLine(stdin) })
|
||||
}
|
||||
@@ -57,12 +45,12 @@ func firefoxPasswordFunc(flags firefoxFlags, stdin *os.File) func(context.Contex
|
||||
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 keychainFlags, stdin *os.File) func(context.Context) (string, error) {
|
||||
func keychainPasswordFunc(flags passwordFlags, stdin *os.File) func(context.Context) (string, error) {
|
||||
switch {
|
||||
case flags.password != "":
|
||||
password := flags.password
|
||||
case flags.value != "":
|
||||
password := flags.value
|
||||
return func(context.Context) (string, error) { return password, nil }
|
||||
case flags.passwordStdin:
|
||||
case flags.fromStdin:
|
||||
return func(ctx context.Context) (string, error) {
|
||||
return untilDone(ctx, func() (string, error) { return firstLine(stdin) })
|
||||
}
|
||||
|
||||
@@ -14,14 +14,14 @@ import (
|
||||
func TestKeychainPasswordFunc(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
flags keychainFlags
|
||||
flags passwordFlags
|
||||
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: "flag", flags: passwordFlags{value: "from-flag"}, stdin: "from-stdin\n", want: "from-flag"},
|
||||
{name: "stdin", flags: passwordFlags{fromStdin: true}, stdin: "from-stdin\r\nnext\n", want: "from-stdin"},
|
||||
{name: "stdin without newline", flags: passwordFlags{fromStdin: true}, stdin: "from-stdin", want: "from-stdin"},
|
||||
{name: "none off a terminal", stdin: "from-stdin\n", err: errNoPassword},
|
||||
}
|
||||
for _, testCase := range tests {
|
||||
|
||||
@@ -39,16 +39,12 @@ func resultDetail(result app.Result) string {
|
||||
}
|
||||
}
|
||||
|
||||
// warnIfNothingFound reports discovery's failures, the likely reason it found no browser data, then says so.
|
||||
func warnIfNothingFound(stderr io.Writer, discovery app.Discovery, message string) bool {
|
||||
if len(discovery.Dirs) > 0 {
|
||||
return false
|
||||
}
|
||||
// printNothingFound lists discovery's failures first, the likely reason a run found no browser data.
|
||||
func printNothingFound(stderr io.Writer, discovery app.Discovery, message string) {
|
||||
if len(discovery.DirFailures) > 0 {
|
||||
printSummary(stderr, app.Summary{DirFailures: discovery.DirFailures})
|
||||
}
|
||||
log.Warnf("%s", message)
|
||||
return true
|
||||
}
|
||||
|
||||
// printExported lists the files a run wrote, even when it stopped early, so the user finds what it left.
|
||||
|
||||
@@ -2,15 +2,12 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/app"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
func newRestoreCommand() *cobra.Command {
|
||||
@@ -33,10 +30,7 @@ func newRestoreCommand() *cobra.Command {
|
||||
command.Flags().StringVar(&flags.DataZip, "data-zip", "", "zip produced by the archive command (alternative to --data-dir)")
|
||||
command.Flags().StringVarP(&flags.Browser, "browser", "b", "", "restore only this browser (optional; must match a vault in --keys)")
|
||||
command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames())
|
||||
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().BoolVar(&flags.Zip, "zip", false, "compress output to zip")
|
||||
command.Flags().IntVar(&flags.MaxStorageValue, "max-storage-value", app.DefaultMaxStorageValue, "max storage value chars, 0=unlimited")
|
||||
addOutputFlags(command, &flags.Output)
|
||||
|
||||
_ = command.MarkFlagRequired("keys")
|
||||
command.MarkFlagsMutuallyExclusive("data-dir", "data-zip")
|
||||
@@ -49,40 +43,17 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
root, err := openRestoreData(flags.DataDir, flags.DataZip)
|
||||
discovery, summary, err := app.Restore(ctx, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeRestoreData(root)
|
||||
|
||||
discovery, keys, err := app.DiscoverRestore(root.Path(), options.Vaults)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if warnIfNothingFound(stderr, discovery, "no browsers to restore from the supplied keys and data") {
|
||||
if len(discovery.Dirs) == 0 {
|
||||
printNothingFound(stderr, discovery, "no browsers to restore from the supplied keys and data")
|
||||
return nil
|
||||
}
|
||||
summary, err := app.ExecuteWithKeys(ctx, discovery, options.Categories, options.Output, keys)
|
||||
printExported(stderr, summary.Exported)
|
||||
if ctx.Err() == nil {
|
||||
printSummary(stderr, summary)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func openRestoreData(dataDir, dataZip string) (*snapshot.Root, error) {
|
||||
if dataDir != "" {
|
||||
return snapshot.Open(dataDir), nil
|
||||
}
|
||||
root, err := snapshot.Unzip(dataZip)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("extract %s: %w", dataZip, err)
|
||||
}
|
||||
return root, nil
|
||||
}
|
||||
|
||||
func closeRestoreData(root *snapshot.Root) {
|
||||
if err := root.Close(); err != nil {
|
||||
log.Warnf("restore: %v", err)
|
||||
}
|
||||
return summary.Err
|
||||
}
|
||||
@@ -14,15 +14,15 @@ import (
|
||||
"github.com/moond4rk/hackbrowserdata/internal/app"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/browsertest"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
// TestRunRestore_FromADataZip goes through the command's own unzip, which the app restore goldens do themselves.
|
||||
func TestRunRestore_FromADataZip(t *testing.T) {
|
||||
// restoreFixture zips the Chromium fixture dirs and writes the key file that opens them.
|
||||
func restoreFixture(t *testing.T) (keys, dataZip string) {
|
||||
t.Helper()
|
||||
userData := t.TempDir()
|
||||
browsertest.WriteChromiumUserDataDirs(t, userData)
|
||||
dataZip := filepath.Join(t.TempDir(), "data.zip")
|
||||
require.NoError(t, snapshot.Open(userData).Zip(dataZip))
|
||||
dataZip = filepath.Join(t.TempDir(), "data.zip")
|
||||
browsertest.ZipDir(t, userData, dataZip)
|
||||
|
||||
keyFile := masterkey.NewKeyFile()
|
||||
for _, fixture := range browsertest.ChromiumUserDataDirs {
|
||||
@@ -30,13 +30,27 @@ func TestRunRestore_FromADataZip(t *testing.T) {
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
require.NoError(t, keyFile.Write(&buffer))
|
||||
keys := filepath.Join(t.TempDir(), "keys.json")
|
||||
keys = filepath.Join(t.TempDir(), "keys.json")
|
||||
require.NoError(t, os.WriteFile(keys, buffer.Bytes(), 0o600))
|
||||
return keys, dataZip
|
||||
}
|
||||
|
||||
// TestRunRestore_FromADataZip runs the command from its flags to the file it writes.
|
||||
func TestRunRestore_FromADataZip(t *testing.T) {
|
||||
keys, dataZip := restoreFixture(t)
|
||||
out := t.TempDir()
|
||||
flags := app.RestoreFlags{KeyFile: keys, DataZip: dataZip, Categories: "cookie", Format: "json", OutputDir: out}
|
||||
flags := app.RestoreFlags{KeyFile: keys, DataZip: dataZip, Categories: "cookie", Output: app.OutputFlags{Format: "json", Dir: out}}
|
||||
require.NoError(t, runRestore(context.Background(), io.Discard, flags))
|
||||
cookies, err := os.ReadFile(filepath.Join(out, "cookie.json"))
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(cookies), `"value": "theme=dark"`)
|
||||
}
|
||||
|
||||
// TestRunRestore_FailsWhenItsOutputCannotBeWritten: the run's own error is in its Summary, which the command returns.
|
||||
func TestRunRestore_FailsWhenItsOutputCannotBeWritten(t *testing.T) {
|
||||
keys, dataZip := restoreFixture(t)
|
||||
out := t.TempDir()
|
||||
require.NoError(t, os.Mkdir(filepath.Join(out, "cookie.json"), 0o700))
|
||||
flags := app.RestoreFlags{KeyFile: keys, DataZip: dataZip, Categories: "cookie", Output: app.OutputFlags{Format: "json", Dir: out}}
|
||||
require.Error(t, runRestore(context.Background(), io.Discard, flags))
|
||||
}
|
||||
Reference in new issue
Block a user