mirror of
https://github.com/moonD4rk/HackBrowserData.git
synced 2026-12-04 05:43:27 +01:00
refactor(app): typed per-command options, render in cmd (#693)
Validate now returns only what each command reads, with -b resolved to browsers or vaults, so no stage compares against "all"; printing moves to cmd, which already printed the list tables.
This commit is contained in:
1 parent
a7741eaab2
commit
b5eddf799b
21 files changed
+281
-266
No files matched your search
+11
-6
@@ -18,21 +18,26 @@ type ArchiveFlags struct {
|
||||
Categories string
|
||||
}
|
||||
|
||||
type ArchiveOptions struct {
|
||||
Target Target
|
||||
Categories []category.Category
|
||||
}
|
||||
|
||||
// ValidateArchive takes no keychain password: an archive copies files and reads no secret.
|
||||
func ValidateArchive(flags ArchiveFlags) (Options, error) {
|
||||
browserName, err := parseBrowser(flags.Browser)
|
||||
func ValidateArchive(flags ArchiveFlags) (ArchiveOptions, error) {
|
||||
browsers, err := parseBrowsers(flags.Browser)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return ArchiveOptions{}, err
|
||||
}
|
||||
categories, err := parseCategories(flags.Categories)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return ArchiveOptions{}, err
|
||||
}
|
||||
home, err := homeDir()
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return ArchiveOptions{}, err
|
||||
}
|
||||
return Options{Target: Target{BrowserName: browserName, HomeDir: home}, Categories: categories}, nil
|
||||
return ArchiveOptions{Target: Target{Browsers: browsers, HomeDir: home}, Categories: categories}, nil
|
||||
}
|
||||
|
||||
// Archive returns how many files and directories it captured.
|
||||
|
||||
@@ -15,21 +15,14 @@ type Discovery struct {
|
||||
DirFailures []DirFailure
|
||||
}
|
||||
|
||||
// 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 target.BrowserName != allBrowsers && supportedBrowser.Name != target.BrowserName {
|
||||
continue
|
||||
}
|
||||
discoverOptions := browser.DiscoverOptions{HomeDir: target.HomeDir}
|
||||
if target.BrowserName != allBrowsers {
|
||||
discoverOptions.ProfilePath = target.ProfilePath
|
||||
}
|
||||
dirs, err := discover(supportedBrowser, discoverOptions)
|
||||
discoverOptions := browser.DiscoverOptions{HomeDir: target.HomeDir, ProfilePath: target.ProfilePath}
|
||||
for _, targetBrowser := range target.Browsers {
|
||||
dirs, err := discover(targetBrowser, discoverOptions)
|
||||
discovery.Dirs = append(discovery.Dirs, withData(dirs)...)
|
||||
if err != nil {
|
||||
discovery.DirFailures = append(discovery.DirFailures, DirFailure{UserDataDirID: browser.UserDataDirID(supportedBrowser.Name), Err: err})
|
||||
discovery.DirFailures = append(discovery.DirFailures, DirFailure{UserDataDirID: browser.UserDataDirID(targetBrowser.Name), Err: err})
|
||||
}
|
||||
}
|
||||
return discovery
|
||||
|
||||
@@ -35,28 +35,24 @@ func TestDiscover(t *testing.T) {
|
||||
writeUserDataDir(t, home, "edge")
|
||||
writeUserDataDir(t, home, "chrome")
|
||||
|
||||
discovery := Discover(Target{BrowserName: "all", HomeDir: home})
|
||||
discovery := Discover(Target{Browsers: browser.Supported(), HomeDir: home})
|
||||
assert.Equal(t, []browser.UserDataDirID{"chrome", "edge"}, userDataDirIDs(discovery), "table order, which is output order")
|
||||
assert.Empty(t, discovery.DirFailures)
|
||||
|
||||
discovery = Discover(Target{BrowserName: "edge", HomeDir: home})
|
||||
discovery = Discover(Target{Browsers: []browser.Browser{lookup(t, "edge")}, HomeDir: home})
|
||||
assert.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery))
|
||||
}
|
||||
|
||||
func TestDiscover_ProfilePathNeedsOneBrowser(t *testing.T) {
|
||||
func TestDiscover_ProfilePath(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
writeUserDataDir(t, home, "chrome")
|
||||
custom := t.TempDir()
|
||||
touch(t, custom, "Default", "Preferences")
|
||||
touch(t, custom, "Default", "History")
|
||||
|
||||
discovery := Discover(Target{BrowserName: "chrome", HomeDir: home, ProfilePath: custom})
|
||||
discovery := Discover(Target{Browsers: []browser.Browser{lookup(t, "chrome")}, HomeDir: home, ProfilePath: custom})
|
||||
require.Len(t, discovery.Dirs, 1)
|
||||
assert.Equal(t, custom, discovery.Dirs[0].Path)
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
// TestDiscover_KeepsOnlyProfilesWithData drops a never-used profile, which holds only its Preferences marker.
|
||||
@@ -67,7 +63,7 @@ func TestDiscover_KeepsOnlyProfilesWithData(t *testing.T) {
|
||||
edge := writeUserDataDir(t, home, "edge")
|
||||
require.NoError(t, os.Remove(filepath.Join(edge, "Default", "History")))
|
||||
|
||||
discovery := Discover(Target{BrowserName: "all", HomeDir: home})
|
||||
discovery := Discover(Target{Browsers: browser.Supported(), HomeDir: home})
|
||||
assert.Equal(t, []browser.UserDataDirID{"chrome"}, userDataDirIDs(discovery))
|
||||
assert.Equal(t, []browser.Profile{{Name: "Default", RelativePath: "Default"}}, discovery.Dirs[0].Profiles)
|
||||
}
|
||||
@@ -81,7 +77,7 @@ func TestDiscover_UnreadableDirIsReported(t *testing.T) {
|
||||
require.NoError(t, os.Chmod(path, 0o000))
|
||||
defer func() { require.NoError(t, os.Chmod(path, 0o700)) }()
|
||||
|
||||
discovery := Discover(Target{BrowserName: "all", HomeDir: home})
|
||||
discovery := Discover(Target{Browsers: browser.Supported(), HomeDir: home})
|
||||
assert.Empty(t, discovery.Dirs)
|
||||
require.Len(t, discovery.DirFailures, 1)
|
||||
assert.Equal(t, browser.UserDataDirID("chrome"), discovery.DirFailures[0].UserDataDirID)
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
// Package app runs the pipeline: the Validate functions, Discover, Execute, and Report.
|
||||
// Package app runs the pipeline's stages: the Validate functions, Discover, and Execute; cmd prints what they return.
|
||||
package app
|
||||
+24
-15
@@ -5,6 +5,8 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/export"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
)
|
||||
@@ -19,45 +21,52 @@ type DumpFlags struct {
|
||||
ProfilePath string
|
||||
}
|
||||
|
||||
type DumpOptions struct {
|
||||
Target Target
|
||||
Categories []category.Category
|
||||
Output Output
|
||||
Keychain KeychainConfig
|
||||
}
|
||||
|
||||
// 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)
|
||||
func ValidateDump(flags DumpFlags, keychainPassword func(context.Context) (string, error)) (DumpOptions, error) {
|
||||
browsers, err := parseBrowsers(flags.Browser)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return DumpOptions{}, err
|
||||
}
|
||||
categories, err := parseCategories(flags.Categories)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return DumpOptions{}, err
|
||||
}
|
||||
format, err := export.ParseFormat(flags.Format)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return DumpOptions{}, err
|
||||
}
|
||||
if err := checkOutputDir(flags.OutputDir); err != nil {
|
||||
return Options{}, err
|
||||
return DumpOptions{}, err
|
||||
}
|
||||
profilePath, err := checkProfilePath(browserName, flags.ProfilePath)
|
||||
profilePath, err := checkProfilePath(browsers, flags.ProfilePath)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return DumpOptions{}, err
|
||||
}
|
||||
home, err := homeDir()
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return DumpOptions{}, err
|
||||
}
|
||||
return Options{
|
||||
Target: Target{BrowserName: browserName, ProfilePath: profilePath, HomeDir: home},
|
||||
return DumpOptions{
|
||||
Target: Target{Browsers: browsers, ProfilePath: profilePath, HomeDir: home},
|
||||
Categories: categories,
|
||||
Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip},
|
||||
Keychain: KeychainConfig{HomeDir: home, Password: keychainPassword},
|
||||
Keychain: KeychainConfig{Path: loginKeychainPath(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) {
|
||||
// checkProfilePath keeps -p only for one browser; with -b all it is ignored, as it always was, but now said.
|
||||
func checkProfilePath(browsers []browser.Browser, path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", nil
|
||||
}
|
||||
if browserName == allBrowsers {
|
||||
if len(browsers) != 1 {
|
||||
log.Warnf("-p needs a specific -b; ignoring %s", path)
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -20,19 +20,20 @@ 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)
|
||||
require.Len(t, options.Target.Browsers, 1)
|
||||
assert.Equal(t, "chrome", options.Target.Browsers[0].Name)
|
||||
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)
|
||||
assert.Equal(t, loginKeychainPath(options.Target.HomeDir), options.Keychain.Path)
|
||||
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, browser.Supported(), options.Target.Browsers)
|
||||
assert.Equal(t, category.All(), options.Categories)
|
||||
}
|
||||
|
||||
|
||||
@@ -18,18 +18,23 @@ type DumpKeysFlags struct {
|
||||
Browser string
|
||||
}
|
||||
|
||||
func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword func(context.Context) (string, error)) (Options, error) {
|
||||
browserName, err := parseBrowser(flags.Browser)
|
||||
type DumpKeysOptions struct {
|
||||
Target Target
|
||||
Keychain KeychainConfig
|
||||
}
|
||||
|
||||
func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword func(context.Context) (string, error)) (DumpKeysOptions, error) {
|
||||
browsers, err := parseBrowsers(flags.Browser)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return DumpKeysOptions{}, err
|
||||
}
|
||||
home, err := homeDir()
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return DumpKeysOptions{}, err
|
||||
}
|
||||
return Options{
|
||||
Target: Target{BrowserName: browserName, HomeDir: home},
|
||||
Keychain: KeychainConfig{HomeDir: home, Password: keychainPassword},
|
||||
return DumpKeysOptions{
|
||||
Target: Target{Browsers: browsers, HomeDir: home},
|
||||
Keychain: KeychainConfig{Path: loginKeychainPath(home), Password: keychainPassword},
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -15,11 +15,14 @@ import (
|
||||
|
||||
// newLoginKeychain builds the run's login keychain without opening it, so a run that never decrypts never prompts.
|
||||
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 keychain.New(config.Path, func(context.Context) (string, error) { return "", nil })
|
||||
}
|
||||
return &reportingKeychain{Keychain: keychain.New(path, keychain.PasswordFunc(config.Password))}
|
||||
return &reportingKeychain{Keychain: keychain.New(config.Path, keychain.PasswordFunc(config.Password))}
|
||||
}
|
||||
|
||||
func loginKeychainPath(home string) string {
|
||||
return filepath.Join(home, "Library", "Keychains", "login.keychain-db")
|
||||
}
|
||||
|
||||
// reportingKeychain says once why the keychain stayed locked, since every consumer then reads metadata only, quietly.
|
||||
|
||||
@@ -3,3 +3,5 @@
|
||||
package app
|
||||
|
||||
func newLoginKeychain(KeychainConfig) loginKeychain { return nil }
|
||||
|
||||
func loginKeychainPath(string) string { return "" }
|
||||
+15
-12
@@ -3,30 +3,33 @@ package app
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"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) {
|
||||
type ListOptions struct {
|
||||
Target Target
|
||||
Keychain KeychainConfig
|
||||
}
|
||||
|
||||
// ValidateList targets every browser and leaves the keychain without a password, so counting never prompts.
|
||||
func ValidateList() (ListOptions, error) {
|
||||
home, err := homeDir()
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
return ListOptions{}, err
|
||||
}
|
||||
return Options{
|
||||
Target: Target{BrowserName: allBrowsers, HomeDir: home},
|
||||
Categories: category.All(),
|
||||
Keychain: KeychainConfig{HomeDir: home},
|
||||
return ListOptions{
|
||||
Target: Target{Browsers: browser.Supported(), HomeDir: home},
|
||||
Keychain: KeychainConfig{Path: loginKeychainPath(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) {
|
||||
// CountRecords runs every category with no key and the keychain locked, counting records instead of exporting them.
|
||||
func CountRecords(ctx context.Context, discovery Discovery, keychainConfig KeychainConfig) (Summary, error) {
|
||||
keychain := newLoginKeychain(keychainConfig)
|
||||
counter := runner{writer: discard{}, extractors: extractorsWith(keychain), retrieveKeys: keysFromFile(nil)}
|
||||
return counter.run(ctx, discovery, categories)
|
||||
return counter.run(ctx, discovery, category.All())
|
||||
}
|
||||
|
||||
type discard struct{}
|
||||
|
||||
+8
-16
@@ -14,18 +14,10 @@ import (
|
||||
"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
|
||||
Browsers []browser.Browser
|
||||
ProfilePath string // a custom profile dir; set only when Browsers holds one browser
|
||||
HomeDir string
|
||||
}
|
||||
|
||||
@@ -38,7 +30,7 @@ type Output struct {
|
||||
|
||||
// KeychainConfig locates the macOS login keychain and says how to get its password; other systems ignore it.
|
||||
type KeychainConfig struct {
|
||||
HomeDir string
|
||||
Path 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)
|
||||
}
|
||||
@@ -53,18 +45,18 @@ func homeDir() (string, error) {
|
||||
|
||||
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) {
|
||||
// parseBrowsers accepts all or one of this OS's browser names; a name from another OS's table has nothing to find here.
|
||||
func parseBrowsers(value string) ([]browser.Browser, error) {
|
||||
name := strings.ToLower(strings.TrimSpace(value))
|
||||
if name == "" || name == allBrowsers {
|
||||
return allBrowsers, nil
|
||||
return browser.Supported(), nil
|
||||
}
|
||||
for _, supportedBrowser := range browser.Supported() {
|
||||
if supportedBrowser.Name == name {
|
||||
return name, nil
|
||||
return []browser.Browser{supportedBrowser}, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("unknown browser %q, available: %s|%s", value, allBrowsers, strings.Join(browser.Names(), "|"))
|
||||
return nil, 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.
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"text/tabwriter"
|
||||
)
|
||||
|
||||
// Report prints a summary that is not part of the output contract and never changes the exit status.
|
||||
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 {
|
||||
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()
|
||||
}
|
||||
|
||||
func detail(result Result) string {
|
||||
switch {
|
||||
case result.Err != nil:
|
||||
return result.Err.Error()
|
||||
case result.Failures > 0:
|
||||
return fmt.Sprintf("%d not recovered", result.Failures)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
)
|
||||
|
||||
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},
|
||||
{
|
||||
Extraction: Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Password},
|
||||
Outcome: OutcomeError, Failures: 2, Err: errors.New("password not decrypted"),
|
||||
},
|
||||
{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, 5)
|
||||
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, []string{"chrome", "Default", "password", "error", "0", "password", "not", "decrypted"}, strings.Fields(lines[3]),
|
||||
"an error's message wins over the failure count")
|
||||
assert.Equal(t, "unset", strings.Fields(lines[4])[3], "a result whose outcome was never set must not read as ok")
|
||||
}
|
||||
+45
-37
@@ -10,6 +10,7 @@ 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/export"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
@@ -27,46 +28,66 @@ type RestoreFlags struct {
|
||||
Zip bool
|
||||
}
|
||||
|
||||
// ValidateRestore checks restore's flags and reads its keys before any data is opened. A restore's browsers are the
|
||||
// key file's vaults, not this OS's table, so -b is checked against them.
|
||||
func ValidateRestore(flags RestoreFlags) (Options, masterkey.KeyFile, error) {
|
||||
type RestoreOptions struct {
|
||||
Vaults []masterkey.Vault // the key file's vaults that -b selects
|
||||
Categories []category.Category
|
||||
Output Output
|
||||
}
|
||||
|
||||
// ValidateRestore checks restore's flags and reads its keys, from stdin for "-", before any data is opened. A restore's
|
||||
// browsers are the key file's vaults, not this OS's table, so -b selects among them.
|
||||
func ValidateRestore(flags RestoreFlags, stdin io.Reader) (RestoreOptions, error) {
|
||||
if flags.KeyFile == "" {
|
||||
return Options{}, masterkey.KeyFile{}, errors.New("requires --keys <file> (or - for stdin)")
|
||||
return RestoreOptions{}, errors.New("requires --keys <file> (or - for stdin)")
|
||||
}
|
||||
if (flags.DataDir == "") == (flags.DataZip == "") {
|
||||
return Options{}, masterkey.KeyFile{}, errors.New("exactly one of --data-dir or --data-zip is required")
|
||||
return RestoreOptions{}, errors.New("exactly one of --data-dir or --data-zip is required")
|
||||
}
|
||||
categories, err := parseCategories(flags.Categories)
|
||||
if err != nil {
|
||||
return Options{}, masterkey.KeyFile{}, err
|
||||
return RestoreOptions{}, err
|
||||
}
|
||||
format, err := export.ParseFormat(flags.Format)
|
||||
if err != nil {
|
||||
return Options{}, masterkey.KeyFile{}, err
|
||||
return RestoreOptions{}, err
|
||||
}
|
||||
if err := checkOutputDir(flags.OutputDir); err != nil {
|
||||
return Options{}, masterkey.KeyFile{}, err
|
||||
return RestoreOptions{}, err
|
||||
}
|
||||
if err := checkRestoreData(flags.DataDir, flags.DataZip); err != nil {
|
||||
return Options{}, masterkey.KeyFile{}, err
|
||||
return RestoreOptions{}, err
|
||||
}
|
||||
keyFile, err := readKeyFile(flags.KeyFile)
|
||||
keyFile, err := readKeyFile(flags.KeyFile, stdin)
|
||||
if err != nil {
|
||||
return Options{}, masterkey.KeyFile{}, err
|
||||
return RestoreOptions{}, err
|
||||
}
|
||||
filter := strings.ToLower(strings.TrimSpace(flags.Browser))
|
||||
if filter == "" {
|
||||
filter = allBrowsers
|
||||
vaults, err := selectVaults(keyFile.Vaults, flags.Browser)
|
||||
if err != nil {
|
||||
return RestoreOptions{}, err
|
||||
}
|
||||
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{
|
||||
Target: Target{BrowserName: filter},
|
||||
return RestoreOptions{
|
||||
Vaults: vaults,
|
||||
Categories: categories,
|
||||
Output: Output{Dir: flags.OutputDir, Format: format, Zip: flags.Zip},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// selectVaults keeps the vaults of the browser -b names, or every vault when it names none.
|
||||
func selectVaults(vaults []masterkey.Vault, browserName string) ([]masterkey.Vault, error) {
|
||||
name := strings.ToLower(strings.TrimSpace(browserName))
|
||||
if name == "" || name == allBrowsers {
|
||||
return vaults, nil
|
||||
}
|
||||
return options, keyFile, nil
|
||||
var selected []masterkey.Vault
|
||||
for _, vault := range vaults {
|
||||
if strings.EqualFold(vault.Browser, name) {
|
||||
selected = append(selected, vault)
|
||||
}
|
||||
}
|
||||
if len(selected) == 0 {
|
||||
return nil, fmt.Errorf("no vault for browser %q in keys (have: %s)", name, vaultBrowserNames(vaults))
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
|
||||
func checkRestoreData(dataDir, dataZip string) error {
|
||||
@@ -82,8 +103,8 @@ func checkRestoreData(dataDir, dataZip string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func readKeyFile(path string) (masterkey.KeyFile, error) {
|
||||
var reader io.Reader = os.Stdin
|
||||
func readKeyFile(path string, stdin io.Reader) (masterkey.KeyFile, error) {
|
||||
reader := stdin
|
||||
if path != "-" {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
@@ -99,12 +120,9 @@ func readKeyFile(path string) (masterkey.KeyFile, error) {
|
||||
return keyFile, nil
|
||||
}
|
||||
|
||||
// DiscoverRestore rebuilds the user data dirs under root, and their keys, from the key file: each vault names a
|
||||
// DiscoverRestore rebuilds the user data dirs under root, and their keys, from the vaults: each vault names a
|
||||
// subdirectory of root, or root is one browser's User Data.
|
||||
func DiscoverRestore(
|
||||
root string, keyFile masterkey.KeyFile, browserName string,
|
||||
) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) {
|
||||
vaults := vaultsOf(keyFile, browserName)
|
||||
func DiscoverRestore(root string, vaults []masterkey.Vault) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) {
|
||||
archived := false
|
||||
for _, vault := range vaults {
|
||||
if dirExists(filepath.Join(root, string(vaultUserDataDirID(vault)))) {
|
||||
@@ -182,16 +200,6 @@ func vaultUserDataDirID(vault masterkey.Vault) browser.UserDataDirID {
|
||||
return browser.UserDataDirID(strings.ToLower(vault.Browser))
|
||||
}
|
||||
|
||||
func vaultsOf(keyFile masterkey.KeyFile, filter string) []masterkey.Vault {
|
||||
var out []masterkey.Vault
|
||||
for _, vault := range keyFile.Vaults {
|
||||
if filter == allBrowsers || strings.EqualFold(vault.Browser, filter) {
|
||||
out = append(out, vault)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func vaultBrowserNames(vaults []masterkey.Vault) string {
|
||||
keys := make([]string, 0, len(vaults))
|
||||
for _, vault := range vaults {
|
||||
|
||||
@@ -115,17 +115,17 @@ func restoreGolden(t *testing.T, flags app.RestoreFlags) string {
|
||||
if flags.Format == "" {
|
||||
flags.Format = "json"
|
||||
}
|
||||
options, keyFile, err := app.ValidateRestore(flags)
|
||||
options, err := app.ValidateRestore(flags, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
data := snapshot.Open(flags.DataDir)
|
||||
root := snapshot.Open(flags.DataDir)
|
||||
if flags.DataZip != "" {
|
||||
data, err = snapshot.Unzip(flags.DataZip)
|
||||
root, err = snapshot.Unzip(flags.DataZip)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
defer data.Close()
|
||||
defer root.Close()
|
||||
|
||||
discovery, keys, err := app.DiscoverRestore(data.Path(), keyFile, options.Target.BrowserName)
|
||||
discovery, keys, err := app.DiscoverRestore(root.Path(), options.Vaults)
|
||||
require.NoError(t, err)
|
||||
_, err = app.ExecuteWithKeys(context.Background(), discovery, options.Categories, options.Output, keys)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -49,14 +49,23 @@ func TestValidateRestore_RejectsBadInput(t *testing.T) {
|
||||
} {
|
||||
flags := base
|
||||
edit(&flags)
|
||||
_, _, err := ValidateRestore(flags)
|
||||
_, err := ValidateRestore(flags, nil)
|
||||
require.Error(t, err, name)
|
||||
}
|
||||
|
||||
options, keyFile, err := ValidateRestore(RestoreFlags{KeyFile: keys, DataDir: data, Browser: "Chrome", Categories: "all", Format: "json", OutputDir: t.TempDir()})
|
||||
options, err := ValidateRestore(RestoreFlags{KeyFile: keys, DataDir: data, Browser: "Chrome", Categories: "all", Format: "json", OutputDir: t.TempDir()}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "chrome", options.Target.BrowserName)
|
||||
assert.Len(t, keyFile.Vaults, 1)
|
||||
require.Len(t, options.Vaults, 1)
|
||||
assert.Equal(t, "chrome", options.Vaults[0].Browser)
|
||||
}
|
||||
|
||||
func TestValidateRestore_ReadsKeysFromTheGivenStdin(t *testing.T) {
|
||||
keys, err := os.ReadFile(keysFile(t, testVault("chrome"), testVault("edge")))
|
||||
require.NoError(t, err)
|
||||
flags := RestoreFlags{KeyFile: "-", DataDir: t.TempDir(), Categories: "all", Format: "json", OutputDir: t.TempDir()}
|
||||
options, err := ValidateRestore(flags, bytes.NewReader(keys))
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, options.Vaults, 2)
|
||||
}
|
||||
|
||||
func TestDiscoverRestore_SecondUserDataDir(t *testing.T) {
|
||||
@@ -66,9 +75,7 @@ func TestDiscoverRestore_SecondUserDataDir(t *testing.T) {
|
||||
second := testVault("arc")
|
||||
second.ID = "arc-2"
|
||||
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, "arc")
|
||||
discovery, keys, err := DiscoverRestore(root, []masterkey.Vault{testVault("arc"), second})
|
||||
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)
|
||||
@@ -82,9 +89,9 @@ func TestDiscoverRestore_FromLayout(t *testing.T) {
|
||||
layoutProfile(t, root, "nightly")
|
||||
nightly := testVault("Nightly")
|
||||
nightly.Kind = "chromium-yandex"
|
||||
keyFile := masterkey.KeyFile{Vaults: []masterkey.Vault{testVault("chrome"), nightly, testVault("chrome"), testVault("edge")}}
|
||||
vaults := []masterkey.Vault{testVault("chrome"), nightly, testVault("chrome"), testVault("edge")}
|
||||
|
||||
discovery, keys, err := DiscoverRestore(root, keyFile, "all")
|
||||
discovery, keys, err := DiscoverRestore(root, vaults)
|
||||
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)
|
||||
@@ -96,12 +103,10 @@ func TestDiscoverRestore_OneUserDataNeedsOneVault(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
touch(t, root, "Default", "Preferences")
|
||||
touch(t, root, "Default", "History")
|
||||
keyFile := masterkey.KeyFile{Vaults: []masterkey.Vault{testVault("chrome"), testVault("edge")}}
|
||||
|
||||
_, _, err := DiscoverRestore(root, keyFile, "all")
|
||||
_, _, err := DiscoverRestore(root, []masterkey.Vault{testVault("chrome"), testVault("edge")})
|
||||
require.Error(t, err)
|
||||
|
||||
discovery, _, err := DiscoverRestore(root, keyFile, "edge")
|
||||
discovery, _, err := DiscoverRestore(root, []masterkey.Vault{testVault("edge")})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery))
|
||||
assert.Equal(t, root, discovery.Dirs[0].Path)
|
||||
|
||||
Reference in new issue
Block a user