diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 06497fb..71c8d57 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,27 @@ gofumpt -l -w . goimports -w -local github.com/moond4rk/hackbrowserdata . ``` +## Package Map + +Imports point one way: `cmd` → `app` → the three bases → shared packages. A base never imports another base or `app`, and `internal/app` is the only package that knows all three bases. + +```text +cmd/hack-browser-data the CLI: flags, password prompts, printing +internal/app one file per command, each read top to bottom +internal/browser the browser table and the types every base shares + chromium, firefox, safari the bases: find profiles, name their files, parse them + browsertest fixture profiles for tests +internal/category, record data categories and output records +internal/snapshot copies of the files, taken before anything reads them +internal/masterkey, keychain Chromium master keys and the macOS login keychain +internal/crypto pure decryption functions +internal/export output files +internal/abe, winapi Windows only +internal/sqlitex, timeconv, zipfile, atomicfile, log, golden small helpers +``` + +To follow a run, start at `internal/app/dump.go`: it discovers the user data dirs, then plans, captures, retrieves keys, extracts, and exports each one in turn, the stages [RFC-001](rfcs/001-architecture.md) describes. + ## Pull Requests When creating a PR, please follow these guidelines: diff --git a/cmd/hack-browser-data/archive.go b/cmd/hack-browser-data/archive.go index b8edca3..8b9e6c5 100644 --- a/cmd/hack-browser-data/archive.go +++ b/cmd/hack-browser-data/archive.go @@ -25,7 +25,8 @@ func newArchiveCommand() *cobra.Command { return err } if len(discovery.Dirs) == 0 { - printNothingFound(command.ErrOrStderr(), discovery, "no browsers found") + printDirFailures(command.ErrOrStderr(), discovery.DirFailures) + log.Warnf("no browsers found") return nil } log.Infof("Archived %d entries to %s", fileCount, options.ArchivePath) diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index bbeaeba..ad9bfde 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -8,13 +8,14 @@ import ( "github.com/spf13/cobra" "github.com/moond4rk/hackbrowserdata/internal/app" + "github.com/moond4rk/hackbrowserdata/internal/log" ) func newDumpCommand() *cobra.Command { var ( - flags app.DumpFlags - keychain passwordFlags - firefox passwordFlags + flags app.DumpFlags + keychainFlags passwordFlags + firefoxFlags passwordFlags ) command := &cobra.Command{ @@ -26,7 +27,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, keychain, firefox) + return runDump(command.Context(), command.ErrOrStderr(), flags, keychainFlags, firefoxFlags) }, } @@ -34,19 +35,20 @@ func newDumpCommand() *cobra.Command { command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames()) command.Flags().StringVarP(&flags.ProfilePath, "profile-path", "p", "", "custom profile dir path, get with chrome://version") addOutputFlags(command, &flags.Output) - addPasswordFlags(command, &keychain, "keychain-pw", "macOS keychain password") - addPasswordFlags(command, &firefox, "firefox-pw", "Firefox primary password") + addPasswordFlags(command, &keychainFlags, "keychain-pw", "macOS keychain password") + addPasswordFlags(command, &firefoxFlags, "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, firefox passwordFlags) error { - options, err := app.ValidateDump(flags, keychainPasswordFunc(keychain, os.Stdin)) +func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychainFlags, firefoxFlags passwordFlags) error { + options, err := app.ValidateDump(flags) if err != nil { return err } - if options.FirefoxPrimaryPassword, err = readFirefoxPassword(ctx, firefox, os.Stdin); err != nil { + options.KeychainPassword = keychainPasswordFunc(keychainFlags, os.Stdin) + if options.FirefoxPrimaryPassword, err = readFirefoxPassword(ctx, firefoxFlags, os.Stdin); err != nil { return err } discovery, summary, err := app.Dump(ctx, options) @@ -54,10 +56,15 @@ func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychai return err } if len(discovery.Dirs) == 0 { - printNothingFound(stderr, discovery, "no browsers found") + printDirFailures(stderr, discovery.DirFailures) + log.Warnf("no browsers found") return nil } - printExported(stderr, summary.Exported) + // A stopped run says nothing of the keychain: the stop itself may be what left it locked. + if summary.KeychainErr != nil && ctx.Err() == nil { + log.Warnf("%v; keychain-protected data was exported as metadata only", summary.KeychainErr) + } + printExportedFiles(stderr, summary.Exported) if ctx.Err() == nil { printSummary(stderr, summary) } diff --git a/cmd/hack-browser-data/dumpkeys.go b/cmd/hack-browser-data/dumpkeys.go index a7e9762..ae1eff8 100644 --- a/cmd/hack-browser-data/dumpkeys.go +++ b/cmd/hack-browser-data/dumpkeys.go @@ -11,8 +11,8 @@ import ( func newDumpKeysCommand() *cobra.Command { var ( - flags app.DumpKeysFlags - keychain passwordFlags + flags app.DumpKeysFlags + keychainFlags passwordFlags ) command := &cobra.Command{ @@ -21,22 +21,26 @@ 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, keychainPasswordFunc(keychain, os.Stdin)) + options, err := app.ValidateDumpKeys(flags) if err != nil { return err } - vaultCount, err := app.DumpKeys(command.Context(), options, command.OutOrStdout()) + options.KeychainPassword = keychainPasswordFunc(keychainFlags, os.Stdin) + summary, err := app.DumpKeys(command.Context(), options, command.OutOrStdout()) if err != nil { return err } - log.Infof("Exported keys for %d vault(s)", vaultCount) + if summary.KeychainErr != nil { + log.Warnf("%v; keys only it holds are missing from the key file", summary.KeychainErr) + } + log.Infof("Exported keys for %d vault(s)", summary.Vaults) return nil }, } command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames()) command.Flags().StringVarP(&flags.OutputPath, "output", "o", "", "output file (default: stdout)") - addPasswordFlags(command, &keychain, "keychain-pw", "macOS keychain password") + addPasswordFlags(command, &keychainFlags, "keychain-pw", "macOS keychain password") return command } diff --git a/cmd/hack-browser-data/list.go b/cmd/hack-browser-data/list.go index bb39e3b..6b1c81a 100644 --- a/cmd/hack-browser-data/list.go +++ b/cmd/hack-browser-data/list.go @@ -21,7 +21,7 @@ func newListCommand() *cobra.Command { return err } for _, failure := range discovery.DirFailures { - log.Warnf("%s: %v", failure.UserDataDirID, failure.Err) + log.Warnf("%s: %v", failure.DirID, failure.Err) } if len(discovery.Dirs) == 0 { command.Println("No browsers found.") diff --git a/cmd/hack-browser-data/main_other.go b/cmd/hack-browser-data/main_other.go index 880c21d..9dee934 100644 --- a/cmd/hack-browser-data/main_other.go +++ b/cmd/hack-browser-data/main_other.go @@ -11,7 +11,7 @@ import ( func configureDoubleClickMode() {} -// exitBy ends the process by sig itself, as the signal would have, so a calling shell or script sees it was stopped. +// exitBy ends the process by the signal itself, as it would have, so a calling shell or script sees it was stopped. func exitBy(received os.Signal) { signal.Reset(received) if syscallSignal, ok := received.(syscall.Signal); ok && syscall.Kill(syscall.Getpid(), syscallSignal) == nil { diff --git a/cmd/hack-browser-data/password.go b/cmd/hack-browser-data/password.go index e62a9da..fd96fbe 100644 --- a/cmd/hack-browser-data/password.go +++ b/cmd/hack-browser-data/password.go @@ -32,7 +32,7 @@ func addPasswordFlags(command *cobra.Command, flags *passwordFlags, name, what s // readFirefoxPassword takes the flag, else the first line of stdin; "" is the empty password, and it never prompts. func readFirefoxPassword(ctx context.Context, flags passwordFlags, stdin io.Reader) (string, error) { if flags.fromStdin { - return untilDone(ctx, func() (string, error) { return firstLine(stdin) }) + return readContext(ctx, func() (string, error) { return firstLine(stdin) }) } return flags.value, nil } @@ -47,7 +47,7 @@ func keychainPasswordFunc(flags passwordFlags, stdin *os.File) keychain.Password return func(context.Context) (string, error) { return password, nil } case flags.fromStdin: return func(ctx context.Context) (string, error) { - return untilDone(ctx, func() (string, error) { return firstLine(stdin) }) + return readContext(ctx, func() (string, error) { return firstLine(stdin) }) } case term.IsTerminal(int(stdin.Fd())): return func(ctx context.Context) (string, error) { return promptPassword(ctx, stdin) } @@ -71,7 +71,7 @@ func promptPassword(ctx context.Context, stdin *os.File) (string, error) { return "", fmt.Errorf("read the password: %w", err) } fmt.Fprint(os.Stderr, "Enter macOS login password: ") - password, err := untilDone(ctx, func() (string, error) { + password, err := readContext(ctx, func() (string, error) { entered, err := term.ReadPassword(fileDescriptor) return string(entered), err }) @@ -86,8 +86,8 @@ func promptPassword(ctx context.Context, stdin *os.File) (string, error) { return password, nil } -// untilDone stops waiting when the run is stopped; the read itself stays blocked until the process ends. -func untilDone(ctx context.Context, read func() (string, error)) (string, error) { +// readContext stops waiting when the run is stopped; the read itself stays blocked until the process ends. +func readContext(ctx context.Context, read func() (string, error)) (string, error) { type answer struct { value string err error diff --git a/cmd/hack-browser-data/report.go b/cmd/hack-browser-data/report.go index 8b18b03..458bf4a 100644 --- a/cmd/hack-browser-data/report.go +++ b/cmd/hack-browser-data/report.go @@ -17,11 +17,11 @@ func printSummary(stderr io.Writer, summary app.Summary) { table := tabwriter.NewWriter(stderr, 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, app.OutcomeError, failure.Err) + fmt.Fprintf(table, "%s\t-\t-\t%s\t0\t%s\n", failure.DirID, app.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, resultDetail(result)) + result.DirID, result.Profile.Name, result.Category, result.Outcome, result.Records, resultDetail(result)) } if err := table.Flush(); err != nil { log.Warnf("print summary: %v", err) @@ -39,16 +39,15 @@ func resultDetail(result app.Result) string { } } -// 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}) +// printDirFailures lists discovery's failures, the likely reason a run found no browser data. +func printDirFailures(stderr io.Writer, failures []app.DirFailure) { + if len(failures) > 0 { + printSummary(stderr, app.Summary{DirFailures: failures}) } - log.Warnf("%s", message) } -// printExported lists the files a run wrote, even when it stopped early, so the user finds what it left. -func printExported(stderr io.Writer, exported export.Listing) { +// printExportedFiles lists the files a run wrote, even when it stopped early, so the user finds what it left. +func printExportedFiles(stderr io.Writer, exported export.Listing) { if len(exported.Files) == 0 { return } @@ -90,7 +89,7 @@ func printRecordCounts(out io.Writer, discovery app.Discovery, summary app.Summa for _, profile := range dir.Profiles { fmt.Fprintf(table, "%s\t%s", dir.Browser.DisplayName, profile.Name) for _, dataCategory := range category.All() { - fmt.Fprintf(table, "\t%d", counts[app.Extraction{UserDataDirID: dir.ID, ProfileName: profile.Name, Category: dataCategory}]) + fmt.Fprintf(table, "\t%d", counts[app.Extraction{DirID: dir.ID, Profile: profile, Category: dataCategory}]) } fmt.Fprintln(table) } diff --git a/cmd/hack-browser-data/report_test.go b/cmd/hack-browser-data/report_test.go index 8fa20e4..8bb4e81 100644 --- a/cmd/hack-browser-data/report_test.go +++ b/cmd/hack-browser-data/report_test.go @@ -10,22 +10,24 @@ import ( "github.com/stretchr/testify/require" "github.com/moond4rk/hackbrowserdata/internal/app" + "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/category" ) func TestPrintSummary(t *testing.T) { - cookie := app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Cookie} + defaultProfile := browser.Profile{Name: "Default", RelativePath: "Default"} + cookie := app.Extraction{DirID: "chrome", Profile: defaultProfile, Category: category.Cookie} var buffer bytes.Buffer printSummary(&buffer, app.Summary{ Results: []app.Result{ {Extraction: cookie, Outcome: app.OutcomePartial, Records: 224, Failures: 4}, { - Extraction: app.Extraction{UserDataDirID: "chrome", ProfileName: "Default", Category: category.Password}, + Extraction: app.Extraction{DirID: "chrome", Profile: defaultProfile, Category: category.Password}, Outcome: app.OutcomeError, Failures: 2, Err: errors.New("password not decrypted"), }, - {Extraction: app.Extraction{UserDataDirID: "edge", ProfileName: "Default", Category: category.Password}}, + {Extraction: app.Extraction{DirID: "edge", Profile: defaultProfile, Category: category.Password}}, }, - DirFailures: []app.DirFailure{{UserDataDirID: "arc-2", Err: errors.New("permission denied")}}, + DirFailures: []app.DirFailure{{DirID: "arc-2", Err: errors.New("permission denied")}}, }) lines := strings.Split(strings.TrimSpace(buffer.String()), "\n") diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index bab0c66..44cc97b 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" "github.com/moond4rk/hackbrowserdata/internal/app" + "github.com/moond4rk/hackbrowserdata/internal/log" ) func newRestoreCommand() *cobra.Command { @@ -48,10 +49,11 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e return err } if len(discovery.Dirs) == 0 { - printNothingFound(stderr, discovery, "no browsers to restore from the supplied keys and data") + printDirFailures(stderr, discovery.DirFailures) + log.Warnf("no browsers to restore from the supplied keys and data") return nil } - printExported(stderr, summary.Exported) + printExportedFiles(stderr, summary.Exported) if ctx.Err() == nil { printSummary(stderr, summary) } diff --git a/internal/app/archive.go b/internal/app/archive.go index 263d503..704ae37 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -80,16 +80,17 @@ func Archive(ctx context.Context, options ArchiveOptions) (Discovery, int, error func archiveFiles(dirs []browser.UserDataDir, categories []category.Category) []snapshot.File { var files []snapshot.File - seen := make(map[snapshot.File]bool) + added := make(map[snapshot.File]bool) for _, dir := range dirs { for _, profile := range dir.Profiles { for _, source := range chromium.ArchiveSources() { - if file, ok, err := firstOnDisk(dir, source.CandidatePaths(profile), source.IsDir); err == nil && ok { - files = appendNew(files, seen, file) + if file, ok, err := firstOnDisk(dir, source.DirRelativePaths(profile), source.IsDir); err == nil && ok { + files = appendNew(files, added, file) } } } - files = appendNew(files, seen, planDir(dir, categories, extractorsFor).files...) + _, categoryFiles, _ := planExtractions(dir, categories) + files = appendNew(files, added, categoryFiles...) } return files } diff --git a/internal/app/bases.go b/internal/app/bases.go new file mode 100644 index 0000000..3e6cc9e --- /dev/null +++ b/internal/app/bases.go @@ -0,0 +1,72 @@ +package app + +import ( + "context" + "fmt" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" + "github.com/moond4rk/hackbrowserdata/internal/browser/firefox" + "github.com/moond4rk/hackbrowserdata/internal/browser/safari" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" +) + +// discoverBrowser, like every function in this file, dispatches on Base here because the base packages import browser. +func discoverBrowser(ctx context.Context, targetBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { + switch targetBrowser.Base { + case browser.Chromium: + return chromium.Discover(targetBrowser, options) + case browser.Firefox: + return firefox.Discover(targetBrowser, options) + case browser.Safari: + return safari.Discover(ctx, targetBrowser, options) + default: + return nil, fmt.Errorf("%s: no base package", targetBrowser.Name) + } +} + +func lookupSources( + dir browser.UserDataDir, profile browser.Profile, dataCategory category.Category, +) (sources []browser.Source, supported bool) { + switch dir.Browser.Base { + case browser.Chromium: + return chromium.Sources(dir, dataCategory) + case browser.Firefox: + return firefox.Sources(dataCategory) + case browser.Safari: + return safari.Sources(dir, profile, dataCategory) + default: + return nil, false + } +} + +// needsMasterKeys is false outside Chromium, the one base whose dir holds master keys. +func needsMasterKeys(dir browser.UserDataDir, extractions []Extraction) bool { + if dir.Browser.Base != browser.Chromium { + return false + } + for _, extraction := range extractions { + if chromium.NeedsMasterKeys(dir, extraction.Category) { + return true + } + } + return false +} + +// extract hands each base its own secret: Chromium the dir's master keys, Firefox the primary password, and Safari the +// login keychain. +func (r runner) extract( + ctx context.Context, captured browser.ProfileSnapshot, masterKeys masterkey.Set, dataCategory category.Category, out browser.Collector, +) error { + switch captured.UserDataDir.Browser.Base { + case browser.Chromium: + return chromium.Extract(captured, masterKeys, dataCategory, out) + case browser.Firefox: + return firefox.Extract(captured, r.firefoxPrimaryPassword, dataCategory, out) + case browser.Safari: + return safari.Extract(ctx, captured, r.loginKeychain, dataCategory, out) + default: + return fmt.Errorf("%s: no base package", captured.UserDataDir.Browser.Name) + } +} diff --git a/internal/app/collector_test.go b/internal/app/collector_test.go new file mode 100644 index 0000000..9ed30c9 --- /dev/null +++ b/internal/app/collector_test.go @@ -0,0 +1,55 @@ +package app + +import ( + "errors" + "fmt" + "io/fs" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/record" +) + +func TestCollectorResult(t *testing.T) { + notDecrypted := errors.New("value not decrypted") + corrupt := errors.New("corrupt") + gone := fmt.Errorf("History: %w", fs.ErrNotExist) + extraction := Extraction{DirID: "chrome", Profile: browser.Profile{Name: "Default", RelativePath: "Default"}, Category: category.Cookie} + tests := []struct { + name string + records int + failures int + err error + want Outcome + wantErr error + }{ + {name: "an empty file is ok, not absent", want: OutcomeOK}, + {name: "records", records: 2, want: OutcomeOK}, + {name: "problems beside records", records: 2, failures: 1, want: OutcomePartial}, + {name: "problems and no record", failures: 2, want: OutcomeError, wantErr: notDecrypted}, + {name: "a failed extraction", err: corrupt, want: OutcomeError, wantErr: corrupt}, + {name: "a failed extraction keeps its records", records: 1, err: corrupt, want: OutcomeError, wantErr: corrupt}, + {name: "a file that vanished after planning", err: gone, want: OutcomeAbsent}, + {name: "a file gone after records were read", records: 1, err: gone, want: OutcomeError, wantErr: gone}, + } + for _, testCase := range tests { + recordCollector := &collector{} + for i := 0; i < testCase.records; i++ { + recordCollector.Add(&record.Cookie{}) + } + for i := 0; i < testCase.failures; i++ { + recordCollector.Fail(notDecrypted) + } + + got := recordCollector.result(extraction, testCase.err) + + want := Result{ + Extraction: extraction, Outcome: testCase.want, + Records: testCase.records, Failures: testCase.failures, Err: testCase.wantErr, + } + assert.Equal(t, want, got, testCase.name) + } +} diff --git a/internal/app/discover.go b/internal/app/discover.go index 8ab869d..86532e8 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -2,12 +2,8 @@ package app import ( "context" - "fmt" "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/browser/chromium" - "github.com/moond4rk/hackbrowserdata/internal/browser/firefox" - "github.com/moond4rk/hackbrowserdata/internal/browser/safari" "github.com/moond4rk/hackbrowserdata/internal/category" ) @@ -21,73 +17,42 @@ func discover(ctx context.Context, browsers []browser.Browser, options browser.D var discovery Discovery for _, targetBrowser := range browsers { dirs, err := discoverBrowser(ctx, targetBrowser, options) - discovery.Dirs = append(discovery.Dirs, withData(dirs)...) + discovery.Dirs = append(discovery.Dirs, dropEmptyProfiles(dirs)...) if err != nil { - discovery.DirFailures = append(discovery.DirFailures, DirFailure{UserDataDirID: browser.UserDataDirID(targetBrowser.Name), Err: err}) + discovery.DirFailures = append(discovery.DirFailures, DirFailure{DirID: targetBrowser.UserDataDirID(0), Err: err}) } } return discovery } -// withData drops profiles holding no file any category reads, such as a bare Preferences, but keeps unreadable ones. -func withData(dirs []browser.UserDataDir) []browser.UserDataDir { - var out []browser.UserDataDir +// dropEmptyProfiles drops profiles holding no file any category reads, such as a bare Preferences, and a dir left with +// none. It keeps an unreadable profile, so the failure is reported. +func dropEmptyProfiles(dirs []browser.UserDataDir) []browser.UserDataDir { + var kept []browser.UserDataDir for _, dir := range dirs { var profiles []browser.Profile for _, profile := range dir.Profiles { - if hasData(dir, profile, extractorsFor(dir, profile)) { + if hasData(dir, profile) { profiles = append(profiles, profile) } } if len(profiles) > 0 { dir.Profiles = profiles - out = append(out, dir) + kept = append(kept, dir) } } - return out + return kept } -func hasData(dir browser.UserDataDir, profile browser.Profile, extractors browser.Extractors) bool { - for _, extractor := range extractors { - if len(extractor.Sources) == 0 { +func hasData(dir browser.UserDataDir, profile browser.Profile) bool { + for _, dataCategory := range category.All() { + sources, _ := lookupSources(dir, profile, dataCategory) + if len(sources) == 0 { continue } - if _, ok, err := locate(dir, profile, extractor.Sources); ok || err != nil { + if _, ok, err := locate(dir, profile, sources); ok || err != nil { return true } } return false } - -// discoverBrowser dispatches on Base here, not in browser, because the base packages import browser. -func discoverBrowser(ctx context.Context, targetBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { - switch targetBrowser.Base { - case browser.Chromium: - return chromium.Discover(targetBrowser, options) - case browser.Firefox: - return firefox.Discover(targetBrowser, options) - case browser.Safari: - return safari.Discover(ctx, targetBrowser, options) - default: - return nil, fmt.Errorf("%s: no base package", targetBrowser.Name) - } -} - -// extractorsFor dispatches on Base here for the same reason discoverBrowser does. -func extractorsFor(dir browser.UserDataDir, profile browser.Profile) browser.Extractors { - switch dir.Browser.Base { - case browser.Chromium: - return chromium.Extractors(dir, profile) - case browser.Firefox: - return firefox.Extractors(dir, profile) - case browser.Safari: - return safari.Extractors(dir, profile) - default: - return nil - } -} - -// needsMasterKeys dispatches on Base for the same reason; Chromium is the one base whose dir holds master keys. -func needsMasterKeys(dir browser.UserDataDir, dataCategory category.Category) bool { - return dir.Browser.Base == browser.Chromium && chromium.NeedsMasterKeys(dataCategory) -} diff --git a/internal/app/discover_test.go b/internal/app/discover_test.go index e6c2fa6..4634036 100644 --- a/internal/app/discover_test.go +++ b/internal/app/discover_test.go @@ -81,13 +81,13 @@ func TestDiscover_UnreadableDirIsReported(t *testing.T) { discovery := discover(context.Background(), browser.Supported(), browser.DiscoverOptions{HomeDir: home}) assert.Empty(t, discovery.Dirs) require.Len(t, discovery.DirFailures, 1) - assert.Equal(t, browser.UserDataDirID("chrome"), discovery.DirFailures[0].UserDataDirID) + assert.Equal(t, browser.UserDataDirID("chrome"), discovery.DirFailures[0].DirID) assert.Error(t, discovery.DirFailures[0].Err) } -// TestWithData_KeepsAProfileItCannotCheck keeps it for the plan to report, since dropping it would hide the failure. -func TestWithData_KeepsAProfileItCannotCheck(t *testing.T) { - dir := chromeDir(t, "chrome", "Default") +// TestDropEmptyProfiles_KeepsAProfileItCannotCheck keeps it for the plan to report, since dropping it would hide the failure. +func TestDropEmptyProfiles_KeepsAProfileItCannotCheck(t *testing.T) { + dir := chromeDir(t, "Default") lock(t, filepath.Join(dir.Path, "Default")) - assert.Len(t, withData([]browser.UserDataDir{dir}), 1) + assert.Len(t, dropEmptyProfiles([]browser.UserDataDir{dir}), 1) } diff --git a/internal/app/dump.go b/internal/app/dump.go index abea017..4d767ab 100644 --- a/internal/app/dump.go +++ b/internal/app/dump.go @@ -25,14 +25,14 @@ type DumpOptions struct { HomeDir string Categories []category.Category Output OutputOptions + // The caller sets both passwords once ValidateDump passes, so a bad flag never consumes stdin. // KeychainPassword runs when the macOS login keychain first opens; "" leaves it locked. Other systems ignore it. - KeychainPassword keychain.PasswordFunc - // FirefoxPrimaryPassword is set by the caller once ValidateDump passes, so a bad flag never consumes stdin. + KeychainPassword keychain.PasswordFunc FirefoxPrimaryPassword string } // ValidateDump checks every flag before any browser or secret is touched, so a bad flag fails fast. -func ValidateDump(flags DumpFlags, keychainPassword keychain.PasswordFunc) (DumpOptions, error) { +func ValidateDump(flags DumpFlags) (DumpOptions, error) { browsers, err := parseBrowsers(flags.Browser) if err != nil { return DumpOptions{}, err @@ -45,7 +45,7 @@ func ValidateDump(flags DumpFlags, keychainPassword keychain.PasswordFunc) (Dump if err != nil { return DumpOptions{}, err } - profilePath, err := checkProfilePath(browsers, flags.ProfilePath) + profilePath, err := parseProfilePath(browsers, flags.ProfilePath) if err != nil { return DumpOptions{}, err } @@ -53,18 +53,11 @@ func ValidateDump(flags DumpFlags, keychainPassword keychain.PasswordFunc) (Dump if err != nil { return DumpOptions{}, err } - return DumpOptions{ - Browsers: browsers, - ProfilePath: profilePath, - HomeDir: home, - Categories: categories, - Output: output, - KeychainPassword: keychainPassword, - }, nil + return DumpOptions{Browsers: browsers, ProfilePath: profilePath, HomeDir: home, Categories: categories, Output: output}, nil } -// 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) { +// parseProfilePath keeps -p only for one browser; with -b all it is ignored, as it always was, but now said. +func parseProfilePath(browsers []browser.Browser, path string) (string, error) { if path == "" { return "", nil } @@ -91,13 +84,14 @@ func Dump(ctx context.Context, options DumpOptions) (Discovery, Summary, error) } loginKeychain := newLoginKeychain(loginKeychainPath(options.HomeDir), options.KeychainPassword) fromMachine := runner{ - extractors: extractorsFor, keySource: machineKeys{loginKeychain: loginKeychain}, loginKeychain: loginKeychain, + keySource: machineKeys{loginKeychain: loginKeychain}, firefoxPrimaryPassword: options.FirefoxPrimaryPassword, + loginKeychain: loginKeychain, } - summary, err := execute(ctx, discovery, options.Categories, options.Output, fromMachine) + summary, err := fromMachine.export(ctx, discovery, options.Categories, options.Output) if err != nil { return Discovery{}, Summary{}, err } - warnIfLocked(ctx, loginKeychain, "keychain-protected data was exported as metadata only") + summary.KeychainErr = keychainErr(loginKeychain) return discovery, summary, nil } diff --git a/internal/app/dump_test.go b/internal/app/dump_test.go index 9935964..04a57a3 100644 --- a/internal/app/dump_test.go +++ b/internal/app/dump_test.go @@ -1,7 +1,6 @@ package app import ( - "context" "io/fs" "os" "path/filepath" @@ -17,9 +16,7 @@ import ( ) func TestValidateDump(t *testing.T) { - keychainPassword := func(context.Context) (string, error) { return "pw", nil } - options, err := ValidateDump(DumpFlags{Browser: " Chrome ", Categories: "cookie, password,cookie", Output: OutputFlags{Format: "csv", Dir: "out"}}, - keychainPassword) + options, err := ValidateDump(DumpFlags{Browser: " Chrome ", Categories: "cookie, password,cookie", Output: OutputFlags{Format: "csv", Dir: "out"}}) require.NoError(t, err) require.Len(t, options.Browsers, 1) assert.Equal(t, "chrome", options.Browsers[0].Name) @@ -27,11 +24,8 @@ func TestValidateDump(t *testing.T) { assert.Equal(t, export.CSV, options.Output.Format) assert.Equal(t, "out", options.Output.Dir) assert.NotEmpty(t, options.HomeDir) - password, err := options.KeychainPassword(context.Background()) - require.NoError(t, err) - assert.Equal(t, "pw", password) - options, err = ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json"}}, nil) + options, err = ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json"}}) require.NoError(t, err) assert.Equal(t, browser.Supported(), options.Browsers) assert.Equal(t, category.All(), options.Categories) @@ -52,7 +46,7 @@ func TestValidateDump_RejectsBadInput(t *testing.T) { "missing -p": {Browser: "chrome", Categories: "all", Output: OutputFlags{Format: "json"}, ProfilePath: missing}, "-p is a file": {Browser: "chrome", Categories: "all", Output: OutputFlags{Format: "json"}, ProfilePath: file}, } { - _, err := ValidateDump(flags, nil) + _, err := ValidateDump(flags) assert.Error(t, err, name) } } @@ -72,7 +66,7 @@ func otherOSBrowser(t *testing.T) string { func TestValidateDump_CreatesNoOutputDir(t *testing.T) { root := t.TempDir() - options, err := ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json", Dir: filepath.Join(root, "a", "b")}}, nil) + options, err := ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json", Dir: filepath.Join(root, "a", "b")}}) require.NoError(t, err) assert.Equal(t, filepath.Join(root, "a", "b"), options.Output.Dir) _, err = os.Stat(filepath.Join(root, "a")) @@ -87,13 +81,13 @@ func TestValidateDump_RejectsAnOutputDirThatCannotBeCreated(t *testing.T) { require.NoError(t, os.Chmod(root, 0o500)) defer func() { require.NoError(t, os.Chmod(root, 0o700)) }() - _, err := ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json", Dir: filepath.Join(root, "results")}}, nil) + _, err := ValidateDump(DumpFlags{Categories: "all", Output: OutputFlags{Format: "json", Dir: filepath.Join(root, "results")}}) 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", Output: OutputFlags{Format: "json"}, ProfilePath: filepath.Join(t.TempDir(), "missing")}, nil) + options, err := ValidateDump(DumpFlags{Browser: "all", Categories: "all", Output: OutputFlags{Format: "json"}, ProfilePath: filepath.Join(t.TempDir(), "missing")}) require.NoError(t, err) assert.Empty(t, options.ProfilePath) } diff --git a/internal/app/dumpkeys.go b/internal/app/dumpkeys.go index 1f1428a..0ffe47f 100644 --- a/internal/app/dumpkeys.go +++ b/internal/app/dumpkeys.go @@ -24,11 +24,12 @@ type DumpKeysOptions struct { Browsers []browser.Browser HomeDir string OutputPath string // "" writes the key file to stdout - // KeychainPassword runs when the macOS login keychain first opens; "" leaves it locked. Other systems ignore it. + // KeychainPassword is set by the caller once ValidateDumpKeys passes. It runs when the macOS login keychain first + // opens; "" leaves it locked. Other systems ignore it. KeychainPassword keychain.PasswordFunc } -func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword keychain.PasswordFunc) (DumpKeysOptions, error) { +func ValidateDumpKeys(flags DumpKeysFlags) (DumpKeysOptions, error) { browsers, err := parseBrowsers(flags.Browser) if err != nil { return DumpKeysOptions{}, err @@ -42,26 +43,33 @@ func ValidateDumpKeys(flags DumpKeysFlags, keychainPassword keychain.PasswordFun if err != nil { return DumpKeysOptions{}, err } - return DumpKeysOptions{Browsers: browsers, HomeDir: home, OutputPath: flags.OutputPath, KeychainPassword: keychainPassword}, nil + return DumpKeysOptions{Browsers: browsers, HomeDir: home, OutputPath: flags.OutputPath}, nil } -// DumpKeys writes the key file to options.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, options DumpKeysOptions, stdout io.Writer) (int, error) { +// KeyFileSummary is what DumpKeys reports about the key file it wrote. +type KeyFileSummary struct { + Vaults int // vaults in the key file + KeychainErr error // why the macOS login keychain stayed locked; nil when it opened or was never read +} + +// DumpKeys writes the key file to options.OutputPath, or to stdout when it is "". A stopped run writes nothing, so it +// never leaves a keys.json behind. +func DumpKeys(ctx context.Context, options DumpKeysOptions, stdout io.Writer) (KeyFileSummary, error) { discovery := discover(ctx, options.Browsers, browser.DiscoverOptions{HomeDir: options.HomeDir}) loginKeychain := newLoginKeychain(loginKeychainPath(options.HomeDir), options.KeychainPassword) - keyFile, err := dumpKeysWith(ctx, discovery, machineKeys{loginKeychain: loginKeychain}) + keyFile, err := buildKeyFile(ctx, discovery, machineKeys{loginKeychain: loginKeychain}) if err != nil { - return 0, err + return KeyFileSummary{}, err } - warnIfLocked(ctx, loginKeychain, "keys only it holds are missing from the key file") if options.OutputPath == "" { - return len(keyFile.Vaults), keyFile.Write(stdout) + err = keyFile.Write(stdout) + } else { + err = writeKeyFile(options.OutputPath, keyFile) } - if err := writeKeyFile(options.OutputPath, keyFile); err != nil { - return 0, err + if err != nil { + return KeyFileSummary{}, err } - return len(keyFile.Vaults), nil + return KeyFileSummary{Vaults: len(keyFile.Vaults), KeychainErr: keychainErr(loginKeychain)}, nil } // writeKeyFile replaces outputPath only once the file is complete, so a failure keeps the old keys.json. @@ -72,9 +80,9 @@ func writeKeyFile(outputPath string, keyFile masterkey.KeyFile) error { return nil } -// dumpKeysWith keeps the keys that worked when a dir's others fail, and leaves out a dir with none. +// buildKeyFile keeps the keys that worked when a dir's others fail, and leaves out a dir with none. // It fails only when the run is stopped. -func dumpKeysWith(ctx context.Context, discovery Discovery, keySource keySource) (masterkey.KeyFile, error) { +func buildKeyFile(ctx context.Context, discovery Discovery, keySource keySource) (masterkey.KeyFile, error) { keyFile := masterkey.NewKeyFile() for _, dir := range discovery.Dirs { if dir.Browser.Base != browser.Chromium { diff --git a/internal/app/dumpkeys_test.go b/internal/app/dumpkeys_test.go index c260087..de67b9f 100644 --- a/internal/app/dumpkeys_test.go +++ b/internal/app/dumpkeys_test.go @@ -22,8 +22,8 @@ func dirOf(t *testing.T, userDataDirID browser.UserDataDirID, browserName string return dir } -func TestDumpKeysWith(t *testing.T) { - chrome := chromeDir(t, "chrome", "Default", "Profile 1") +func TestBuildKeyFile(t *testing.T) { + chrome := chromeDir(t, "Default", "Profile 1") touch(t, chrome.Path, "Local State") arc2, opera, vivaldi, brave := dirOf(t, "arc-2", "arc"), dirOf(t, "opera", "opera"), dirOf(t, "vivaldi", "vivaldi"), dirOf(t, "brave", "brave") firefox := dirOf(t, "firefox", "firefox") @@ -43,7 +43,7 @@ func TestDumpKeysWith(t *testing.T) { return masterkey.Retrieval{Keys: masterkey.Set{masterkey.V10: []byte(dir.ID)}} }) discovery := Discovery{Dirs: []browser.UserDataDir{chrome, firefox, arc2, opera, vivaldi, brave}} - keyFile, err := dumpKeysWith(context.Background(), discovery, keys) + keyFile, err := buildKeyFile(context.Background(), discovery, keys) require.NoError(t, err) assert.Equal(t, []masterkey.Vault{ @@ -66,10 +66,10 @@ func TestDumpKeysWith(t *testing.T) { }, keyFile.Vaults, "a failed dir is left out, a partly failed one keeps what it has") } -func TestDumpKeysWith_StoppedRunReturnsNoKeyFile(t *testing.T) { +func TestBuildKeyFile_StoppedRunReturnsNoKeyFile(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - chrome, brave := chromeDir(t, "chrome", "Default"), dirOf(t, "brave", "brave") + chrome, brave := chromeDir(t, "Default"), dirOf(t, "brave", "brave") touch(t, chrome.Path, "Local State") keys := keySourceFunc(func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) masterkey.Retrieval { require.Equal(t, browser.UserDataDirID("chrome"), dir.ID, "keys were retrieved after the stop") @@ -77,7 +77,7 @@ func TestDumpKeysWith_StoppedRunReturnsNoKeyFile(t *testing.T) { return masterkey.Retrieval{Keys: masterkey.Set{masterkey.V10: []byte("chrome")}} }) - keyFile, err := dumpKeysWith(ctx, Discovery{Dirs: []browser.UserDataDir{chrome, brave}}, keys) + keyFile, err := buildKeyFile(ctx, Discovery{Dirs: []browser.UserDataDir{chrome, brave}}, keys) require.ErrorIs(t, err, context.Canceled) assert.Empty(t, keyFile.Vaults) } diff --git a/internal/app/execute_test.go b/internal/app/execute_test.go deleted file mode 100644 index eb91055..0000000 --- a/internal/app/execute_test.go +++ /dev/null @@ -1,304 +0,0 @@ -package app - -import ( - "bytes" - "context" - "errors" - "fmt" - "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/browser/browsertest" - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/internal/record" - "github.com/moond4rk/hackbrowserdata/internal/snapshot" -) - -var history = browser.Source{RelativePath: "History"} - -type extractFunc func(ctx context.Context, input browser.Input, out browser.Collector) error - -// fakeBase reads History for every category, so a test needs one fixture file per profile. -func fakeBase(extractFuncs map[category.Category]extractFunc) extractorsFunc { - return func(browser.UserDataDir, browser.Profile) browser.Extractors { - extractors := make(browser.Extractors, len(extractFuncs)) - for dataCategory, extract := range extractFuncs { - extractors[dataCategory] = browser.Extractor{Sources: []browser.Source{history}, Extract: extract} - } - return extractors - } -} - -type keySourceFunc func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval - -func (f keySourceFunc) MasterKeys(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval { - return f(ctx, dir, dirSnapshot) -} - -func keysNeverRetrieved(t *testing.T) keySource { - return keySourceFunc(func(context.Context, browser.UserDataDir, snapshot.Snapshot) masterkey.Retrieval { - t.Error("keys were retrieved") - return masterkey.Retrieval{} - }) -} - -func chromeDir(t *testing.T, id browser.UserDataDirID, profiles ...string) browser.UserDataDir { - t.Helper() - dir := browser.UserDataDir{ID: id, Browser: lookup(t, "chrome"), Path: t.TempDir()} - for _, name := range profiles { - touch(t, dir.Path, name, "History") - dir.Profiles = append(dir.Profiles, browser.Profile{Name: name, RelativePath: name}) - } - return dir -} - -func run(t *testing.T, base extractorsFunc, keys keySource, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) { - t.Helper() - output := OutputOptions{Dir: t.TempDir()} - summary, err := execute(context.Background(), Discovery{Dirs: dirs}, categories, output, runner{extractors: base, keySource: keys}) - require.NoError(t, err) - require.NoError(t, summary.Err) - return summary, output.Dir -} - -func outcomes(summary Summary) map[category.Category]Result { - out := make(map[category.Category]Result) - for _, result := range summary.Results { - out[result.Category] = result - } - return out -} - -func TestExecute_Outcomes(t *testing.T) { - cookie := func(name string) *record.Cookie { return &record.Cookie{Name: name} } - base := fakeBase(map[category.Category]extractFunc{ - category.Cookie: func(_ context.Context, _ browser.Input, out browser.Collector) error { - out.Add(cookie("a")) - out.Add(cookie("b")) - out.Fail(errors.New("value not decrypted")) - return nil - }, - category.Password: func(_ context.Context, _ browser.Input, out browser.Collector) error { - out.Fail(errors.New("password not decrypted")) - return nil - }, - category.History: func(context.Context, browser.Input, browser.Collector) error { return nil }, - category.Bookmark: func(context.Context, browser.Input, browser.Collector) error { - return errors.New("corrupt") - }, - category.Download: func(context.Context, browser.Input, browser.Collector) error { - return fmt.Errorf("History: %w", fs.ErrNotExist) - }, - category.Extension: func(_ context.Context, _ browser.Input, out browser.Collector) error { - out.Add(&record.Extension{Name: "kept"}) - return errors.New("truncated") - }, - category.CreditCard: func(_ context.Context, _ browser.Input, out browser.Collector) error { - out.Add(&record.CreditCard{Name: "kept"}) - return fmt.Errorf("Web Data: %w", fs.ErrNotExist) - }, - }) - categories := []category.Category{ - category.Cookie, category.Password, category.History, category.Bookmark, category.Download, category.Extension, - category.CreditCard, - } - summary, out := run(t, base, noKeys{}, categories, chromeDir(t, "chrome", "Default")) - - got := outcomes(summary) - assert.Equal(t, OutcomePartial, got[category.Cookie].Outcome) - assert.Equal(t, 2, got[category.Cookie].Records) - assert.Equal(t, 1, got[category.Cookie].Failures) - assert.Equal(t, OutcomeError, got[category.Password].Outcome, "problems and no record") - require.EqualError(t, got[category.Password].Err, "password not decrypted") - assert.Equal(t, OutcomeOK, got[category.History].Outcome, "an empty file is ok, not absent") - assert.Equal(t, OutcomeError, got[category.Bookmark].Outcome) - require.EqualError(t, got[category.Bookmark].Err, "corrupt") - assert.Equal(t, OutcomeAbsent, got[category.Download].Outcome, "a file that vanished after planning") - assert.Equal(t, OutcomeError, got[category.Extension].Outcome) - assert.Equal(t, OutcomeError, got[category.CreditCard].Outcome, "a file gone after records were read is an error, not absent") - - data, err := os.ReadFile(filepath.Join(out, "extension.json")) - require.NoError(t, err) - assert.Contains(t, string(data), `"kept"`, "records emitted before the error are exported") - data, err = os.ReadFile(filepath.Join(out, "cookie.json")) - require.NoError(t, err) - assert.Contains(t, string(data), `"browser": "Chrome"`, "the collector sets the browser's display name") - 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.Input, 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, OutputOptions{Dir: t.TempDir()}, runner{extractors: base, keySource: noKeys{}}) - require.NoError(t, err) - require.NoError(t, summary.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(_ context.Context, input browser.Input, out browser.Collector) error { - out.Add(&record.Cookie{Value: string(input.MasterKeys()[masterkey.V10])}) - return nil - } - login := func(_ context.Context, input browser.Input, out browser.Collector) error { - out.Add(&record.Login{Password: string(input.MasterKeys()[masterkey.V10])}) - return nil - } - calls := 0 - keys := keySourceFunc(func(_ context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval { - calls++ - _, err := dirSnapshot.Path("Default/History") - require.NoError(t, err, "keys are read from the dir's own snapshot") - return masterkey.Retrieval{Keys: masterkey.Set{masterkey.V10: []byte(dir.ID)}, Err: errors.New("v20: no ABE")} - }) - base := fakeBase(map[category.Category]extractFunc{category.Cookie: cookie, category.Password: login}) - categories := []category.Category{category.Cookie, category.Password} - - summary, out := run(t, base, keys, categories, chromeDir(t, "chrome", "Default", "Profile 1")) - - assert.Equal(t, 1, calls) - 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) - data, err := os.ReadFile(filepath.Join(out, "cookie.json")) - require.NoError(t, err) - assert.Contains(t, string(data), `"value": "chrome"`, "keys retrieved beside an error still decrypt") -} - -// TestExecute_HistoryNeverRetrievesKeys checks nothing to decrypt means no key retrieval, so no prompt on macOS. -func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) { - path := t.TempDir() - touch(t, path, "Local State") - touch(t, path, "Default", "History") - dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}}} - - run(t, extractorsFor, keysNeverRetrieved(t), []category.Category{category.History, category.Download}, dir) -} - -func TestExecute_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) { - var captured []string - base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, input browser.Input, _ browser.Collector) error { - for _, earlier := range captured { - _, err := os.Stat(earlier) - require.ErrorIs(t, err, fs.ErrNotExist, "an earlier dir's copy is still on disk") - } - path, err := input.Path(history) - require.NoError(t, err) - captured = append(captured, path) - return nil - }, - }) - run(t, base, keysNeverRetrieved(t), []category.Category{category.History}, chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default")) - - require.Len(t, captured, 2) - for _, path := range captured { - _, err := os.Stat(path) - assert.ErrorIs(t, err, fs.ErrNotExist) - } -} - -func TestExecute_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - var copied []string - base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, input browser.Input, _ browser.Collector) error { - path, err := input.Path(history) - require.NoError(t, err) - copied = append(copied, path) - cancel() - return nil - }, - category.Download: func(context.Context, browser.Input, browser.Collector) error { - t.Error("an extraction ran after the stop") - return nil - }, - }) - categories := []category.Category{category.History, category.Download} - discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default")}} - - summary, err := execute(ctx, discovery, categories, OutputOptions{Dir: t.TempDir()}, runner{extractors: base, keySource: keysNeverRetrieved(t)}) - require.NoError(t, err) - require.ErrorIs(t, summary.Err, context.Canceled) - require.Len(t, summary.Results, 1, "what ran before the stop is still reported") - require.Len(t, copied, 1, "the next user data dir is never captured") - _, statErr := os.Stat(copied[0]) - assert.ErrorIs(t, statErr, fs.ErrNotExist) -} - -func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { - if runtime.GOOS == "windows" || os.Geteuid() == 0 { - t.Skip("directory permissions do not deny writes here") - } - var copied string - base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, input browser.Input, out browser.Collector) error { - var err error - copied, err = input.Path(history) - require.NoError(t, err) - out.Add(&record.History{URL: "https://example.com"}) - return nil - }, - category.Download: func(context.Context, browser.Input, browser.Collector) error { - t.Error("an extraction ran after the output failed") - return nil - }, - }) - output := OutputOptions{Dir: t.TempDir()} - require.NoError(t, os.Chmod(output.Dir, 0o500)) - defer func() { require.NoError(t, os.Chmod(output.Dir, 0o700)) }() - - discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default")}} - summary, err := execute(context.Background(), discovery, []category.Category{category.History, category.Download}, output, runner{extractors: base, keySource: keysNeverRetrieved(t)}) - require.NoError(t, err) - require.Error(t, summary.Err) - require.NotEmpty(t, copied) - _, statErr := os.Stat(copied) - assert.ErrorIs(t, statErr, fs.ErrNotExist) -} - -func TestDump_FirefoxPrimaryPasswordOpensEveryProtectedProfile(t *testing.T) { - home := t.TempDir() - firefoxBrowser, ok := browser.Lookup("firefox") - require.True(t, ok) - profilesDir := filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirPaths[0])) - globalSalt, masterKey := bytes.Repeat([]byte("16-byte-salt-abc"), 3), []byte("firefox-pw-master-key-24") - for _, profile := range []string{"a.default", "b.work"} { - browsertest.WriteFirefoxPrimaryPasswordProfile(t, filepath.Join(profilesDir, profile), globalSalt, []byte("hunter2"), [][]byte{masterKey}) - } - - _, summary, err := Dump(context.Background(), DumpOptions{ - Browsers: []browser.Browser{firefoxBrowser}, HomeDir: home, Categories: []category.Category{category.Password}, - Output: OutputOptions{Dir: t.TempDir()}, FirefoxPrimaryPassword: "hunter2", - }) - require.NoError(t, err) - require.NoError(t, summary.Err) - require.Len(t, summary.Results, 2) - for _, result := range summary.Results { - assert.Equal(t, OutcomeOK, result.Outcome, result.ProfileName) - } -} diff --git a/internal/app/extract_golden_test.go b/internal/app/extract_golden_test.go index d086949..b89b684 100644 --- a/internal/app/extract_golden_test.go +++ b/internal/app/extract_golden_test.go @@ -59,12 +59,12 @@ func extractGoldenRun(t *testing.T, home string, keys map[browser.UserDataDirID] t.Helper() out := t.TempDir() flags := DumpFlags{Browser: "all", Categories: "all", Output: OutputFlags{Format: format, Dir: out, MaxStorageValue: DefaultMaxStorageValue}} - options, err := ValidateDump(flags, nil) + options, err := ValidateDump(flags) require.NoError(t, err) discovery := discover(context.Background(), options.Browsers, browser.DiscoverOptions{HomeDir: home}) - fromFixture := runner{extractors: extractorsFor, keySource: keyFileKeys(keys)} - summary, err := execute(context.Background(), discovery, options.Categories, options.Output, fromFixture) + fromFixture := runner{keySource: keyFileKeys(keys)} + summary, err := fromFixture.export(context.Background(), discovery, options.Categories, options.Output) require.NoError(t, err) require.NoError(t, summary.Err) return out diff --git a/internal/app/keychain.go b/internal/app/keychain.go index 621135a..78282bd 100644 --- a/internal/app/keychain.go +++ b/internal/app/keychain.go @@ -1,26 +1,21 @@ package app import ( - "context" - - "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/log" + "github.com/moond4rk/hackbrowserdata/internal/browser/safari" "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) // 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 - browser.LoginKeychain + safari.LoginKeychain Err() error } -// warnIfLocked speaks once the run is over, because every reader of a locked keychain quietly gets metadata only. -func warnIfLocked(ctx context.Context, loginKeychain loginKeychain, consequence string) { - if loginKeychain == nil || ctx.Err() != nil { - return - } - if err := loginKeychain.Err(); err != nil { - log.Warnf("%v; %s", err, consequence) +// keychainErr is read once the run is over, because every reader of a locked keychain quietly gets metadata only. +func keychainErr(loginKeychain loginKeychain) error { + if loginKeychain == nil { + return nil } + return loginKeychain.Err() } diff --git a/internal/app/list.go b/internal/app/list.go index f9a1d6f..e4b1f20 100644 --- a/internal/app/list.go +++ b/internal/app/list.go @@ -20,7 +20,7 @@ func List(ctx context.Context, detail bool) (Discovery, Summary, error) { return discovery, Summary{}, nil } loginKeychain := newLoginKeychain(loginKeychainPath(home), noPassword) - counter := runner{writer: discard{}, extractors: extractorsFor, keySource: noKeys{}, loginKeychain: loginKeychain} + counter := runner{keySource: noKeys{}, loginKeychain: loginKeychain, writer: discard{}} summary := counter.run(ctx, discovery, category.All()) if summary.Err != nil { return Discovery{}, Summary{}, summary.Err diff --git a/internal/app/options.go b/internal/app/options.go index e8faa74..e22b9d8 100644 --- a/internal/app/options.go +++ b/internal/app/options.go @@ -77,7 +77,7 @@ func parseCategories(value string) ([]category.Category, error) { return category.All(), nil } var categories []category.Category - seen := make(map[category.Category]bool) + added := make(map[category.Category]bool) for _, name := range strings.Split(value, ",") { name = strings.TrimSpace(strings.ToLower(name)) if name == "" { @@ -87,8 +87,8 @@ func parseCategories(value string) ([]category.Category, error) { if err != nil { return nil, fmt.Errorf("%w, available: all|%s", err, strings.Join(category.Names(), ",")) } - if !seen[dataCategory] { - seen[dataCategory] = true + if !added[dataCategory] { + added[dataCategory] = true categories = append(categories, dataCategory) } } @@ -105,7 +105,7 @@ func checkOutputDir(outputDir string) error { info, err := os.Stat(path) switch { case err == nil && info.IsDir(): - if err := canCreateIn(path); err != nil { + if err := checkWritable(path); err != nil { return fmt.Errorf("output dir %s: %w", outputDir, err) } return nil @@ -134,7 +134,7 @@ func checkOutputFile(path string) error { case !info.IsDir(): return fmt.Errorf("output file %s: %s is not a directory", path, parent) } - if err := canCreateIn(parent); err != nil { + if err := checkWritable(parent); err != nil { return fmt.Errorf("output file %s: %w", path, err) } if existing, err := os.Stat(path); err == nil && existing.IsDir() { diff --git a/internal/app/options_test.go b/internal/app/options_test.go index a3f367c..87a67f6 100644 --- a/internal/app/options_test.go +++ b/internal/app/options_test.go @@ -28,11 +28,11 @@ func TestCheckOutputFile(t *testing.T) { // TestValidate_RejectsAnOutputFileItCannotWrite: -o fails before any browser is read, not after the work is done. func TestValidate_RejectsAnOutputFileItCannotWrite(t *testing.T) { missing := filepath.Join(t.TempDir(), "missing", "out") - _, err := ValidateDumpKeys(DumpKeysFlags{Browser: "all", OutputPath: missing}, nil) + _, err := ValidateDumpKeys(DumpKeysFlags{Browser: "all", OutputPath: missing}) require.Error(t, err) _, err = ValidateArchive(ArchiveFlags{Browser: "all", Categories: "all", OutputPath: missing}) require.Error(t, err) - _, err = ValidateDumpKeys(DumpKeysFlags{Browser: "all"}, nil) + _, err = ValidateDumpKeys(DumpKeysFlags{Browser: "all"}) require.NoError(t, err, "without -o the key file goes to stdout") } diff --git a/internal/app/outdir_other.go b/internal/app/outdir_other.go index 7c3277e..bde5d61 100644 --- a/internal/app/outdir_other.go +++ b/internal/app/outdir_other.go @@ -4,6 +4,6 @@ package app import "golang.org/x/sys/unix" -func canCreateIn(dir string) error { - return unix.Access(dir, unix.W_OK|unix.X_OK) +func checkWritable(directory string) error { + return unix.Access(directory, unix.W_OK|unix.X_OK) } diff --git a/internal/app/outdir_windows.go b/internal/app/outdir_windows.go index e2ec434..94dca5e 100644 --- a/internal/app/outdir_windows.go +++ b/internal/app/outdir_windows.go @@ -2,5 +2,5 @@ package app -// canCreateIn accepts every directory: Windows grants writes through ACLs that only the write itself can check. -func canCreateIn(string) error { return nil } +// checkWritable accepts every directory: Windows grants writes through ACLs that only the write itself can check. +func checkWritable(string) error { return nil } diff --git a/internal/app/plan.go b/internal/app/plan.go index 4da5b98..9bf6c08 100644 --- a/internal/app/plan.go +++ b/internal/app/plan.go @@ -11,55 +11,39 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// 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 - needsMasterKeys bool // an extraction decrypts with the dir's master keys, so they are retrieved once -} - -// 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 - -func planDir(dir browser.UserDataDir, categories []category.Category, extractors extractorsFunc) dirPlan { - var plan dirPlan - captured := make(map[snapshot.File]bool) +// planExtractions decides from which files exist, before anything is copied. It returns the extractions to run in +// output order, the files they read, each listed once, and a Result for each requested extraction that cannot run. +func planExtractions( + dir browser.UserDataDir, categories []category.Category, +) (extractions []Extraction, files []snapshot.File, skipped []Result) { + added := make(map[snapshot.File]bool) 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] + extraction := Extraction{DirID: dir.ID, Profile: profile, Category: dataCategory} + sources, supported := lookupSources(dir, profile, dataCategory) if !supported { - plan.skipped = append(plan.skipped, Result{Extraction: extraction, Outcome: OutcomeUnsupported}) + skipped = append(skipped, Result{Extraction: extraction, Outcome: OutcomeUnsupported}) continue } - files, present, err := locate(dir, profile, extractor.Sources) + located, present, err := locate(dir, profile, sources) switch { case err != nil: - plan.skipped = append(plan.skipped, Result{Extraction: extraction, Outcome: OutcomeError, Err: err}) + skipped = append(skipped, Result{Extraction: extraction, Outcome: OutcomeError, Err: err}) case !present: - plan.skipped = append(plan.skipped, Result{Extraction: extraction, Outcome: OutcomeAbsent}) + skipped = append(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...) - plan.needsMasterKeys = plan.needsMasterKeys || needsMasterKeys(dir, dataCategory) + extractions = append(extractions, extraction) + files = appendNew(files, added, located...) } } } - return plan + return extractions, files, skipped } -func appendNew(files []snapshot.File, seen map[snapshot.File]bool, more ...snapshot.File) []snapshot.File { +func appendNew(files []snapshot.File, added map[snapshot.File]bool, more ...snapshot.File) []snapshot.File { for _, file := range more { - if !seen[file] { - seen[file] = true + if !added[file] { + added[file] = true files = append(files, file) } } @@ -73,7 +57,7 @@ func locate(dir browser.UserDataDir, profile browser.Profile, sources []browser. return nil, true, nil } for _, source := range sources { - file, ok, err := firstOnDisk(dir, source.CandidatePaths(profile), source.IsDir) + file, ok, err := firstOnDisk(dir, source.DirRelativePaths(profile), source.IsDir) switch { case err != nil: return nil, false, err diff --git a/internal/app/plan_test.go b/internal/app/plan_test.go index 1d6d4fb..60855e2 100644 --- a/internal/app/plan_test.go +++ b/internal/app/plan_test.go @@ -29,102 +29,92 @@ func lookup(t *testing.T, name string) browser.Browser { return namedBrowser } -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) { +func TestPlanExtractions(t *testing.T) { path := t.TempDir() touch(t, path, "Local State") touch(t, path, "Default", "Login Data") touch(t, path, "Default", "Network", "Cookies") touch(t, path, "Default", "History") touch(t, path, "Profile 1", "History") - dir := browser.UserDataDir{ - ID: "chrome", Browser: lookup(t, "chrome"), Path: path, - Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}, {Name: "Profile 1", RelativePath: "Profile 1"}}, - } + first := browser.Profile{Name: "Default", RelativePath: "Default"} + second := browser.Profile{Name: "Profile 1", RelativePath: "Profile 1"} + dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{first, second}} categories := []category.Category{category.Password, category.Cookie, category.History, category.Download, category.CreditCard} - plan := planDir(dir, categories, extractorsFor) + extractions, files, skipped := planExtractions(dir, categories) file := func(relativePath string) snapshot.File { return snapshot.File{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: relativePath} } - extraction := func(profile string, dataCategory category.Category) Extraction { - return Extraction{UserDataDirID: "chrome", ProfileName: profile, Category: dataCategory} + extraction := func(profile browser.Profile, dataCategory category.Category) Extraction { + return Extraction{DirID: "chrome", Profile: profile, Category: dataCategory} } - skipped := func(profile string, dataCategory category.Category, outcome Outcome) Result { - return Result{Extraction: extraction(profile, dataCategory), Outcome: outcome} + absent := func(profile browser.Profile, dataCategory category.Category) Result { + return Result{Extraction: extraction(profile, dataCategory), Outcome: OutcomeAbsent} } 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)) + extraction(first, category.Password), extraction(first, category.Cookie), + extraction(first, category.History), extraction(first, category.Download), + extraction(second, category.History), extraction(second, category.Download), + }, extractions) 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") + }, files, "Local State and History are copied once, however many extractions read them") assert.Equal(t, []Result{ - skipped("Default", category.CreditCard, OutcomeAbsent), + absent(first, category.CreditCard), // 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) + absent(second, category.Password), + absent(second, category.Cookie), + absent(second, category.CreditCard), + }, skipped) } -func TestPlanDir_PicksTheFirstCandidateOnDisk(t *testing.T) { +func TestPlanExtractions_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"}}} - plan := planDir(dir, []category.Category{category.Cookie}, extractorsFor) - assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Cookies"}}, plan.files) + _, files, _ := planExtractions(dir, []category.Category{category.Cookie}) + assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Cookies"}}, files) touch(t, path, "Default", "Network", "Cookies") - plan = planDir(dir, []category.Category{category.Cookie}, extractorsFor) - assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Network/Cookies"}}, plan.files, + _, files, _ = planExtractions(dir, []category.Category{category.Cookie}) + assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Network/Cookies"}}, files, "a leftover legacy Cookies never wins") } -func TestPlanDir_FlatLayoutProfile(t *testing.T) { +func TestPlanExtractions_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"}}} + profile := browser.Profile{Name: "Opera Stable"} + dir := browser.UserDataDir{ID: "opera", Browser: lookup(t, "opera"), Path: path, Profiles: []browser.Profile{profile}} - plan := planDir(dir, []category.Category{category.History}, extractorsFor) - 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)) + extractions, files, _ := planExtractions(dir, []category.Category{category.History}) + assert.Equal(t, []snapshot.File{{UserDataDirID: "opera", UserDataDirPath: path, RelativePath: "History"}}, files) + assert.Equal(t, []Extraction{{DirID: "opera", Profile: profile, Category: category.History}}, extractions) } -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{} } +// TestPlanExtractions_UnsupportedCategory covers Firefox's credit cards, which it keeps nowhere HBD reads. +func TestPlanExtractions_UnsupportedCategory(t *testing.T) { + profile := browser.Profile{Name: "a.default", RelativePath: "a.default"} + dir := browser.UserDataDir{ID: "firefox", Browser: lookup(t, "firefox"), Path: t.TempDir(), Profiles: []browser.Profile{profile}} - plan := planDir(dir, []category.Category{category.CreditCard}, none) - assert.Equal(t, []Result{{Extraction: Extraction{UserDataDirID: "x", ProfileName: "Default", Category: category.CreditCard}, Outcome: OutcomeUnsupported}}, - plan.skipped) - assert.Empty(t, plan.extractions) + extractions, _, skipped := planExtractions(dir, []category.Category{category.CreditCard}) + unsupported := Extraction{DirID: "firefox", Profile: profile, Category: category.CreditCard} + assert.Equal(t, []Result{{Extraction: unsupported, Outcome: OutcomeUnsupported}}, skipped) + assert.Empty(t, extractions) } -// 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: {}} - } +// TestPlanExtractions_CategoryWithoutSourcesRuns covers Safari's passwords: read from the keychain, they are never absent. +func TestPlanExtractions_CategoryWithoutSourcesRuns(t *testing.T) { + profile := browser.Profile{Name: "default", RelativePath: "Safari"} + dir := browser.UserDataDir{ID: "safari", Browser: lookup(t, "safari"), Path: t.TempDir(), Profiles: []browser.Profile{profile}} - 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) + extractions, files, skipped := planExtractions(dir, []category.Category{category.Password}) + assert.Equal(t, []Extraction{{DirID: "safari", Profile: profile, Category: category.Password}}, extractions) + assert.Empty(t, files) + assert.Empty(t, skipped) } // lock makes dir unsearchable until the test ends, so a Stat of anything under it fails with permission denied. @@ -140,16 +130,14 @@ func lock(t *testing.T, dir string) { t.Cleanup(func() { assert.NoError(t, os.Chmod(dir, 0o700)) }) } -func TestPlanDir_UnreadableFileIsAnError(t *testing.T) { - dir := chromeDir(t, "chrome", "Default") +func TestPlanExtractions_UnreadableFileIsAnError(t *testing.T) { + dir := chromeDir(t, "Default") lock(t, filepath.Join(dir.Path, "Default")) - base := fakeBase(map[category.Category]extractFunc{category.History: nil}) + extractions, files, skipped := planExtractions(dir, []category.Category{category.History}) - plan := planDir(dir, []category.Category{category.History}, base) - - 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) + require.Len(t, skipped, 1) + assert.Equal(t, OutcomeError, skipped[0].Outcome) + require.ErrorIs(t, skipped[0].Err, fs.ErrPermission) + assert.Empty(t, extractions) + assert.Empty(t, files) } diff --git a/internal/app/restore.go b/internal/app/restore.go index 3e97ae8..af836c4 100644 --- a/internal/app/restore.go +++ b/internal/app/restore.go @@ -85,8 +85,8 @@ func Restore(ctx context.Context, options RestoreOptions) (Discovery, Summary, e if len(discovery.Dirs) == 0 { return discovery, Summary{}, nil } - fromKeyFile := runner{extractors: extractorsFor, keySource: keyFileKeys(keys)} - summary, err := execute(ctx, discovery, options.Categories, options.Output, fromKeyFile) + fromKeyFile := runner{keySource: keyFileKeys(keys)} + summary, err := fromKeyFile.export(ctx, discovery, options.Categories, options.Output) if err != nil { return Discovery{}, Summary{}, err } @@ -164,7 +164,7 @@ func readKeyFile(path string, stdin io.Reader) (masterkey.KeyFile, error) { func discoverArchive(archiveDir string, vaults []masterkey.Vault) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) { archived := false for _, vault := range vaults { - if dirExists(filepath.Join(archiveDir, string(vaultUserDataDirID(vault)))) { + if dirExists(filepath.Join(archiveDir, string(vaultDirID(vault)))) { archived = true break } @@ -177,7 +177,7 @@ func discoverArchive(archiveDir string, vaults []masterkey.Vault) (Discovery, ma var discovery Discovery keys := make(map[browser.UserDataDirID]masterkey.Set) for _, vault := range vaults { - id := vaultUserDataDirID(vault) + id := vaultDirID(vault) if _, duplicate := keys[id]; duplicate { log.Warnf("restore: keys hold %s twice, restoring the first", id) continue @@ -203,11 +203,13 @@ func discoverArchive(archiveDir string, vaults []masterkey.Vault) (Discovery, ma func restoredDir(vault masterkey.Vault, id browser.UserDataDirID, path string) (browser.UserDataDir, error) { restoredBrowser, vaultKind := vaultBrowser(vault) - dir, err := chromium.DiscoverAt(restoredBrowser, vaultKind, id, path) + dir := browser.UserDataDir{ID: id, Browser: restoredBrowser, Path: path, VaultKind: vaultKind} + profiles, err := chromium.DiscoverProfiles(dir) if err != nil { return browser.UserDataDir{}, err } - found := withData([]browser.UserDataDir{dir}) + dir.Profiles = profiles + found := dropEmptyProfiles([]browser.UserDataDir{dir}) if len(found) == 0 { return browser.UserDataDir{}, fmt.Errorf("found no profiles under %s", path) } @@ -224,8 +226,8 @@ func vaultBrowser(vault masterkey.Vault) (restored browser.Browser, vaultKind st return browser.Browser{Name: name, DisplayName: vault.Browser, Base: browser.Chromium}, vault.Kind } -// vaultUserDataDirID is the vault's directory in an archive: its ID for a second user data dir, else its browser name. -func vaultUserDataDirID(vault masterkey.Vault) browser.UserDataDirID { +// vaultDirID is the vault's directory in an archive: its ID for a second user data dir, else its browser name. +func vaultDirID(vault masterkey.Vault) browser.UserDataDirID { if vault.ID != "" { return browser.UserDataDirID(vault.ID) } diff --git a/internal/app/result.go b/internal/app/result.go index c978c6e..7b17f92 100644 --- a/internal/app/result.go +++ b/internal/app/result.go @@ -8,9 +8,9 @@ import ( // 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 + DirID browser.UserDataDirID + Profile browser.Profile + 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. @@ -52,8 +52,8 @@ type Result struct { // 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 + DirID browser.UserDataDirID + Err error } // Summary lists each dir's results in turn, what never ran before what ran, and the dirs that failed as a whole. @@ -61,5 +61,6 @@ type Summary struct { Results []Result DirFailures []DirFailure Exported export.Listing // the files the run wrote; empty when nothing was exported + KeychainErr error // why the macOS login keychain stayed locked; nil when it opened or was never read Err error // why the run ended early: it was stopped, or its output could not be written } diff --git a/internal/app/execute.go b/internal/app/run.go similarity index 60% rename from internal/app/execute.go rename to internal/app/run.go index 3d21d70..d7cec75 100644 --- a/internal/app/execute.go +++ b/internal/app/run.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/moond4rk/hackbrowserdata/internal/browser" + "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" @@ -14,38 +15,35 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// execute gives the runner the run's writer; the caller sets where its extractors, keys, and keychain come from. -// It handles one user data dir at a time, so at most one dir's copies are on disk. Its error means nothing ran. -func execute( - ctx context.Context, discovery Discovery, categories []category.Category, output OutputOptions, dirRunner runner, -) (Summary, error) { - writer, err := export.NewWriter(output.Dir, output.Format, output.Zip) - if err != nil { - return Summary{}, err - } - dirRunner.writer, dirRunner.logProgress = writer, true - dirRunner.maxStorageValue = output.MaxStorageValue - summary := dirRunner.run(ctx, discovery, categories) - summary.Err = errors.Join(summary.Err, writer.Close()) - summary.Exported = writer.Listing() - return summary, nil -} - type recordWriter interface { Write(dataCategory category.Category, records []record.Record) error } // runner is what every user data dir of one run shares; logProgress logs each dir as it starts. type runner struct { + keySource keySource // Chromium: each dir's master keys + firefoxPrimaryPassword string // Firefox + loginKeychain safari.LoginKeychain // Safari writer recordWriter - extractors extractorsFunc - keySource keySource - loginKeychain browser.LoginKeychain - firefoxPrimaryPassword string logProgress bool maxStorageValue int } +// export gives the run its writer; the caller sets each base's secret. +// It handles one user data dir at a time, so at most one dir's copies are on disk. Its error means nothing ran. +func (r runner) export(ctx context.Context, discovery Discovery, categories []category.Category, output OutputOptions) (Summary, error) { + writer, err := export.NewWriter(output.Dir, output.Format, output.Zip) + if err != nil { + return Summary{}, err + } + r.writer, r.logProgress = writer, true + r.maxStorageValue = output.MaxStorageValue + summary := r.run(ctx, discovery, categories) + summary.Err = errors.Join(summary.Err, writer.Close()) + summary.Exported = writer.Listing() + return summary, nil +} + // run ends at the first dir whose Summary has an Err, keeping what ran before it. func (r runner) run(ctx context.Context, discovery Discovery, categories []category.Category) Summary { summary := Summary{DirFailures: append([]DirFailure(nil), discovery.DirFailures...)} @@ -54,7 +52,7 @@ func (r runner) run(ctx context.Context, discovery Discovery, categories []categ summary.Err = fmt.Errorf("run stopped: %w", err) return summary } - dirSummary := r.runDir(ctx, dir, categories) + dirSummary := r.runExtractions(ctx, dir, categories) summary.Results = append(summary.Results, dirSummary.Results...) summary.DirFailures = append(summary.DirFailures, dirSummary.DirFailures...) if dirSummary.Err != nil { @@ -65,10 +63,10 @@ func (r runner) run(ctx context.Context, discovery Discovery, categories []categ return summary } -func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories []category.Category) Summary { - plan := planDir(dir, categories, r.extractors) - summary := Summary{Results: plan.skipped} - if len(plan.extractions) == 0 { +func (r runner) runExtractions(ctx context.Context, dir browser.UserDataDir, categories []category.Category) Summary { + extractions, files, skipped := planExtractions(dir, categories) + summary := Summary{Results: skipped} + if len(extractions) == 0 { return summary } if r.logProgress { @@ -77,35 +75,35 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories root, err := snapshot.NewRoot() if err != nil { - summary.Results = append(summary.Results, failAll(plan.extractions, err)...) + summary.Results = append(summary.Results, errorResults(extractions, err)...) return summary } defer closeRoot(root) - if err := root.Capture(ctx, plan.files); err != nil { + if err := root.Capture(ctx, files); err != nil { if ctx.Err() != nil { summary.Err = err return summary } - summary.Results = append(summary.Results, failAll(plan.extractions, err)...) + summary.Results = append(summary.Results, errorResults(extractions, err)...) return summary } dirSnapshot := root.Snapshot(string(dir.ID)) var masterKeys masterkey.Set - if plan.needsMasterKeys { + if needsMasterKeys(dir, extractions) { retrieval := r.keySource.MasterKeys(ctx, dir, dirSnapshot) masterKeys = retrieval.Keys if retrieval.Err != nil { - summary.DirFailures = []DirFailure{{UserDataDirID: dir.ID, Err: fmt.Errorf("master key retrieval: %w", retrieval.Err)}} + summary.DirFailures = []DirFailure{{DirID: dir.ID, Err: fmt.Errorf("master key retrieval: %w", retrieval.Err)}} } } - for _, extraction := range plan.extractions { + for _, extraction := range extractions { if err := ctx.Err(); err != nil { summary.Err = fmt.Errorf("run stopped: %w", err) return summary } - input := browser.NewInput(dirSnapshot, extraction.profile, masterKeys, r.loginKeychain).WithFirefoxPassword(r.firefoxPrimaryPassword) - result, err := r.runExtraction(ctx, extraction, input, dir.Browser.DisplayName) + captured := browser.NewProfileSnapshot(dir, extraction.Profile, dirSnapshot) + result, err := r.runExtraction(ctx, extraction, captured, masterKeys) if err != nil { summary.Err = err return summary @@ -117,20 +115,22 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories // 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, input browser.Input, browserName string, + ctx context.Context, extraction Extraction, captured browser.ProfileSnapshot, masterKeys masterkey.Set, ) (Result, error) { - recordCollector := &collector{browserName: browserName, profileName: extraction.ProfileName, maxStorageValue: r.maxStorageValue} - err := extraction.extractor.Extract(ctx, input, recordCollector) + recordCollector := &collector{ + browserName: captured.UserDataDir.Browser.DisplayName, profileName: extraction.Profile.Name, maxStorageValue: r.maxStorageValue, + } + err := r.extract(ctx, captured, masterKeys, extraction.Category, recordCollector) if writeErr := r.writer.Write(extraction.Category, recordCollector.records); writeErr != nil { return Result{}, writeErr } - return recordCollector.result(extraction.Extraction, err), nil + return recordCollector.result(extraction, err), nil } -func failAll(extractions []plannedExtraction, err error) []Result { +func errorResults(extractions []Extraction, err error) []Result { results := make([]Result, len(extractions)) for i, extraction := range extractions { - results[i] = Result{Extraction: extraction.Extraction, Outcome: OutcomeError, Err: err} + results[i] = Result{Extraction: extraction, Outcome: OutcomeError, Err: err} } return results } diff --git a/internal/app/run_test.go b/internal/app/run_test.go new file mode 100644 index 0000000..be2e926 --- /dev/null +++ b/internal/app/run_test.go @@ -0,0 +1,244 @@ +package app + +import ( + "bytes" + "context" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/browser/browsertest" + "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" + "github.com/moond4rk/hackbrowserdata/internal/record" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" +) + +type keySourceFunc func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval + +func (f keySourceFunc) MasterKeys(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval { + return f(ctx, dir, dirSnapshot) +} + +func keysNeverRetrieved(t *testing.T) keySource { + return keySourceFunc(func(context.Context, browser.UserDataDir, snapshot.Snapshot) masterkey.Retrieval { + t.Error("keys were retrieved") + return masterkey.Retrieval{} + }) +} + +// fixtureKeys notes where each dir's snapshot keeps its Local State, which is on disk only while that dir runs. +func fixtureKeys(t *testing.T, copied *[]string) keySource { + return keySourceFunc(func(_ context.Context, _ browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval { + path, err := dirSnapshot.Path("Local State") + require.NoError(t, err, "keys are read from the dir's own snapshot") + *copied = append(*copied, path) + return masterkey.Retrieval{Keys: browsertest.ChromiumKeys} + }) +} + +// writerFunc lets a test act as the run writes one extraction's records, before the next extraction starts. +type writerFunc func(dataCategory category.Category, records []record.Record) error + +func (f writerFunc) Write(dataCategory category.Category, records []record.Record) error { + return f(dataCategory, records) +} + +func chromeDir(t *testing.T, profiles ...string) browser.UserDataDir { + t.Helper() + dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: t.TempDir()} + for _, name := range profiles { + touch(t, dir.Path, name, "History") + dir.Profiles = append(dir.Profiles, browser.Profile{Name: name, RelativePath: name}) + } + return dir +} + +// chromeDirWithData holds browsertest's two profiles, whose values are sealed with browsertest.ChromiumKeys. +func chromeDirWithData(t *testing.T, id browser.UserDataDirID) browser.UserDataDir { + t.Helper() + dir := browser.UserDataDir{ID: id, Browser: lookup(t, "chrome"), Path: t.TempDir()} + browsertest.WriteChromiumUserDataDir(t, dir.Path, "chrome") + for _, profile := range browsertest.ChromiumProfiles { + dir.Profiles = append(dir.Profiles, browser.Profile{Name: profile.Dir, RelativePath: profile.Dir}) + } + return dir +} + +func run(t *testing.T, keys keySource, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) { + t.Helper() + output := OutputOptions{Dir: t.TempDir()} + summary, err := runner{keySource: keys}.export(context.Background(), Discovery{Dirs: dirs}, categories, output) + require.NoError(t, err) + require.NoError(t, summary.Err) + return summary, output.Dir +} + +// TestRun_ExportsTheRecordsReadBeforeAnError breaks one of Chrome's two login stores; the other's logins still export. +func TestRun_ExportsTheRecordsReadBeforeAnError(t *testing.T) { + dir := chromeDirWithData(t, "chrome") + dir.Profiles = dir.Profiles[:1] + broken := filepath.Join(dir.Path, "Default", "Login Data For Account") + require.NoError(t, os.WriteFile(broken, []byte("not a database"), 0o600)) + + summary, out := run(t, keyFileKeys{"chrome": browsertest.ChromiumKeys}, []category.Category{category.Password}, dir) + + require.Len(t, summary.Results, 1) + assert.Equal(t, OutcomeError, summary.Results[0].Outcome) + assert.Equal(t, 2, summary.Results[0].Records) + data, err := os.ReadFile(filepath.Join(out, "password.json")) + require.NoError(t, err) + assert.Contains(t, string(data), `"password": "correct-horse-battery-staple"`) + assert.Contains(t, string(data), `"browser": "Chrome"`, "the collector sets the browser's display name") + assert.Contains(t, string(data), `"profile": "Default"`) +} + +func TestRun_ReportsEachDirWhatNeverRanFirst(t *testing.T) { + failed := DirFailure{DirID: "edge", Err: errors.New("permission denied")} + chrome, second := chromeDirWithData(t, "chrome"), chromeDirWithData(t, "chrome-2") + for _, dir := range []*browser.UserDataDir{&chrome, &second} { + dir.Profiles = dir.Profiles[:1] + require.NoError(t, os.Remove(filepath.Join(dir.Path, "Default", "Bookmarks"))) + } + categories := []category.Category{category.History, category.Bookmark} + discovery := Discovery{Dirs: []browser.UserDataDir{chrome, second}, DirFailures: []DirFailure{failed}} + + summary, err := runner{keySource: noKeys{}}.export(context.Background(), discovery, categories, OutputOptions{Dir: t.TempDir()}) + require.NoError(t, err) + require.NoError(t, summary.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.DirID, result.Category, result.Outcome)) + } + assert.Equal(t, []string{ + "chrome/bookmark absent", "chrome/history ok", + "chrome-2/bookmark absent", "chrome-2/history ok", + }, got) +} + +func TestRun_KeysAreRetrievedOncePerUserDataDir(t *testing.T) { + calls := 0 + keys := keySourceFunc(func(_ context.Context, _ browser.UserDataDir, dirSnapshot snapshot.Snapshot) masterkey.Retrieval { + calls++ + _, err := dirSnapshot.Path("Local State") + require.NoError(t, err, "keys are read from the dir's own snapshot") + return masterkey.Retrieval{Keys: browsertest.ChromiumKeys, Err: errors.New("v20: no ABE")} + }) + categories := []category.Category{category.Cookie, category.Password} + + summary, out := run(t, keys, categories, chromeDirWithData(t, "chrome")) + + assert.Equal(t, 1, calls, "two profiles and two categories share one retrieval") + require.Len(t, summary.DirFailures, 1, "a retrieval error is reported once, for the dir") + assert.Equal(t, browser.UserDataDirID("chrome"), summary.DirFailures[0].DirID) + require.ErrorContains(t, summary.DirFailures[0].Err, "v20: no ABE") + assert.Len(t, summary.Results, 4) + data, err := os.ReadFile(filepath.Join(out, "cookie.json")) + require.NoError(t, err) + assert.Contains(t, string(data), `"value": "theme=dark"`, "keys retrieved beside an error still decrypt") +} + +// TestRun_HistoryNeverRetrievesKeys checks nothing to decrypt means no key retrieval, so no prompt on macOS. +func TestRun_HistoryNeverRetrievesKeys(t *testing.T) { + path := t.TempDir() + touch(t, path, "Local State") + touch(t, path, "Default", "History") + dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}}} + + run(t, keysNeverRetrieved(t), []category.Category{category.History, category.Download}, dir) +} + +func TestRun_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) { + var copied []string + checkingEarlierCopies := writerFunc(func(category.Category, []record.Record) error { + for _, earlier := range copied[:len(copied)-1] { + _, err := os.Stat(earlier) + require.ErrorIs(t, err, fs.ErrNotExist, "an earlier dir's copy is still on disk") + } + return nil + }) + discovery := Discovery{Dirs: []browser.UserDataDir{chromeDirWithData(t, "chrome"), chromeDirWithData(t, "chrome-2")}} + + summary := runner{keySource: fixtureKeys(t, &copied), writer: checkingEarlierCopies}.run( + context.Background(), discovery, []category.Category{category.Cookie}) + + require.NoError(t, summary.Err) + require.Len(t, copied, 2) + for _, path := range copied { + _, err := os.Stat(path) + assert.ErrorIs(t, err, fs.ErrNotExist) + } +} + +func TestRun_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var copied []string + written := 0 + stopping := writerFunc(func(category.Category, []record.Record) error { + written++ + cancel() + return nil + }) + discovery := Discovery{Dirs: []browser.UserDataDir{chromeDirWithData(t, "chrome"), chromeDirWithData(t, "chrome-2")}} + + summary := runner{keySource: fixtureKeys(t, &copied), writer: stopping}.run( + ctx, discovery, []category.Category{category.Cookie, category.Password}) + + require.ErrorIs(t, summary.Err, context.Canceled) + require.Len(t, summary.Results, 1, "what ran before the stop is still reported") + assert.Equal(t, 1, written, "an extraction ran after the stop") + require.Len(t, copied, 1, "the next user data dir is never captured") + _, err := os.Stat(copied[0]) + assert.ErrorIs(t, err, fs.ErrNotExist) +} + +func TestRun_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { + var copied []string + diskFull := errors.New("disk full") + written := 0 + failing := writerFunc(func(category.Category, []record.Record) error { + written++ + return diskFull + }) + discovery := Discovery{Dirs: []browser.UserDataDir{chromeDirWithData(t, "chrome"), chromeDirWithData(t, "chrome-2")}} + + summary := runner{keySource: fixtureKeys(t, &copied), writer: failing}.run( + context.Background(), discovery, []category.Category{category.Cookie, category.Password}) + + require.ErrorIs(t, summary.Err, diskFull) + assert.Equal(t, 1, written, "an extraction ran after the output failed") + require.Len(t, copied, 1, "the next user data dir is never captured") + _, err := os.Stat(copied[0]) + assert.ErrorIs(t, err, fs.ErrNotExist) +} + +func TestDump_FirefoxPrimaryPasswordOpensEveryProtectedProfile(t *testing.T) { + home := t.TempDir() + firefoxBrowser, ok := browser.Lookup("firefox") + require.True(t, ok) + profilesDir := filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirPaths[0])) + globalSalt, masterKey := bytes.Repeat([]byte("16-byte-salt-abc"), 3), []byte("firefox-pw-master-key-24") + for _, profile := range []string{"a.default", "b.work"} { + browsertest.WriteFirefoxPrimaryPasswordProfile(t, filepath.Join(profilesDir, profile), globalSalt, []byte("hunter2"), [][]byte{masterKey}) + } + + _, summary, err := Dump(context.Background(), DumpOptions{ + Browsers: []browser.Browser{firefoxBrowser}, HomeDir: home, Categories: []category.Category{category.Password}, + Output: OutputOptions{Dir: t.TempDir()}, FirefoxPrimaryPassword: "hunter2", + }) + require.NoError(t, err) + require.NoError(t, summary.Err) + require.Len(t, summary.Results, 2) + for _, result := range summary.Results { + assert.Equal(t, OutcomeOK, result.Outcome, result.Profile.Name) + } +} diff --git a/internal/browser/chromium/chromium.go b/internal/browser/chromium/chromium.go index 5bd1a94..1cb4da3 100644 --- a/internal/browser/chromium/chromium.go +++ b/internal/browser/chromium/chromium.go @@ -19,7 +19,7 @@ var profileMarkers = []string{"Preferences", "Preferences_02"} // Discover yields nothing for a missing user data dir; any other failure is returned beside whatever was found. func Discover(chromiumBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { - if dir, ok := profileAt(chromiumBrowser, options.ProfilePath); ok { + if dir, ok := dirFromProfilePath(chromiumBrowser, options.ProfilePath); ok { return []browser.UserDataDir{dir}, nil } paths, err := userDataDirPaths(chromiumBrowser, options) @@ -41,23 +41,21 @@ func Discover(chromiumBrowser browser.Browser, options browser.DiscoverOptions) return dirs, errors.Join(errs...) } -// DiscoverAt reads the profiles of a user data dir the table does not name, such as a copy restore was given, in the -// on-disk format vaultKind names. -func DiscoverAt(chromiumBrowser browser.Browser, vaultKind string, id browser.UserDataDirID, path string) (browser.UserDataDir, error) { - if !isVaultKind(vaultKind) { - return browser.UserDataDir{}, fmt.Errorf("unknown vault kind %q", vaultKind) +// DiscoverProfiles reads the profiles of a user data dir the table does not name, such as a copy restore was given, in +// the on-disk format dir.VaultKind names. +func DiscoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { + if !isKnownVaultKind(dir.VaultKind) { + return nil, fmt.Errorf("unknown vault kind %q", dir.VaultKind) } - dir := browser.UserDataDir{ID: id, Browser: chromiumBrowser, Path: path, VaultKind: vaultKind} profiles, err := discoverProfiles(dir) if err != nil { - return dir, fmt.Errorf("read %s: %w", path, err) + return nil, fmt.Errorf("read %s: %w", dir.Path, err) } - dir.Profiles = profiles - return dir, nil + return profiles, nil } -// profileAt takes chrome://version's path: a profile dir without Local State selects that profile of its parent. -func profileAt(chromiumBrowser browser.Browser, path string) (browser.UserDataDir, bool) { +// dirFromProfilePath takes chrome://version's path: a profile dir without Local State selects that profile of its parent. +func dirFromProfilePath(chromiumBrowser browser.Browser, path string) (browser.UserDataDir, bool) { if path == "" || !isProfileDir(path) || hasAnyFile(path, localState.RelativePaths()) { return browser.UserDataDir{}, false } @@ -141,9 +139,9 @@ func isSkippedProfileDir(name string) bool { func profileFilePaths(dir browser.UserDataDir) []string { var paths []string - for _, extractor := range kindExtractors(vaultKindOf(dir)) { - for _, source := range extractor.Sources { - if !source.Shared { + for _, extractor := range dirExtractors(dir) { + for _, source := range extractor.sources { + if !source.FromUserDataDir { paths = append(paths, source.RelativePaths()...) } } diff --git a/internal/browser/chromium/extract_extension.go b/internal/browser/chromium/extract_extension.go index 1abc899..173df47 100644 --- a/internal/browser/chromium/extract_extension.go +++ b/internal/browser/chromium/extract_extension.go @@ -1,7 +1,6 @@ package chromium import ( - "context" "errors" "io/fs" "os" @@ -9,10 +8,11 @@ import ( "github.com/tidwall/gjson" "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/masterkey" "github.com/moond4rk/hackbrowserdata/internal/record" ) -var extensionJSONPaths = []string{ +var extensionSettingsKeys = []string{ "extensions.settings", "settings.extensions", "settings.settings", @@ -20,19 +20,20 @@ var extensionJSONPaths = []string{ var errNoExtensionList = errors.New("cannot find extensions in settings") -// newExtensionExtractor falls back to Preferences, where Linux builds and forks such as 360 keep the list. -func newExtensionExtractor(parse func(string, browser.Collector) error) browser.Extractor { +// newExtensionExtractor takes the settings keys the extension list may sit under, since forks such as Opera move it. +// It falls back to Preferences, where Linux builds and forks such as 360 keep the list. +func newExtensionExtractor(settingsKeys ...string) extractor { sources := []browser.Source{securePreferences, preferences} - return browser.Extractor{ - Sources: sources, - Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { + return extractor{ + sources: sources, + extract: func(captured browser.ProfileSnapshot, _ masterkey.Set, out browser.Collector) error { for _, source := range sources { - path, err := input.Path(source) + path, err := captured.Path(source) if errors.Is(err, fs.ErrNotExist) { continue } if err == nil { - err = parse(path, out) + err = extractExtensions(path, settingsKeys, out) } if !errors.Is(err, errNoExtensionList) { return err @@ -43,19 +44,14 @@ func newExtensionExtractor(parse func(string, browser.Collector) error) browser. } } -func extractExtensions(path string, out browser.Collector) error { - return extractExtensionsAt(path, extensionJSONPaths, out) -} - -// extractExtensionsAt takes the JSON paths, because variants such as Opera keep extension settings elsewhere. -func extractExtensionsAt(path string, jsonPaths []string, out browser.Collector) error { +func extractExtensions(path string, settingsKeys []string, out browser.Collector) error { data, err := os.ReadFile(path) if err != nil { return err } var settings gjson.Result - for _, key := range jsonPaths { + for _, key := range settingsKeys { settings = gjson.GetBytes(data, key) if settings.Exists() { break @@ -100,7 +96,3 @@ func isExtensionEnabled(extension gjson.Result) bool { } return extension.Get("state").Int() == 1 } - -func extractOperaExtensions(path string, out browser.Collector) error { - return extractExtensionsAt(path, []string{"extensions.opsettings"}, out) -} diff --git a/internal/browser/chromium/extract_extension_test.go b/internal/browser/chromium/extract_extension_test.go index ca5da13..22f98c7 100644 --- a/internal/browser/chromium/extract_extension_test.go +++ b/internal/browser/chromium/extract_extension_test.go @@ -47,7 +47,7 @@ func TestExtractExtensions(t *testing.T) { path := setupExtensionJSON(t) var out testCollector - err := extractExtensions(path, &out) + err := extractExtensions(path, extensionSettingsKeys, &out) got := collected[record.Extension](t, &out) require.NoError(t, err) require.Len(t, got, 2) // system (location=5) and component (location=10) skipped @@ -66,7 +66,7 @@ func TestExtractExtensions_NoManifestSkipped(t *testing.T) { }`) var out testCollector - err := extractExtensions(path, &out) + err := extractExtensions(path, extensionSettingsKeys, &out) got := collected[record.Extension](t, &out) require.NoError(t, err) assert.Empty(t, got) @@ -74,11 +74,11 @@ func TestExtractExtensions_NoManifestSkipped(t *testing.T) { func TestExtractExtensions_MissingSettingsPath(t *testing.T) { path := createTestJSON(t, "Secure Preferences", `{"something": "else"}`) - err := extractExtensions(path, &testCollector{}) + err := extractExtensions(path, extensionSettingsKeys, &testCollector{}) require.Error(t, err) } -func TestExtractOperaExtensions(t *testing.T) { +func TestExtractExtensions_OperaSettingsKey(t *testing.T) { path := createTestJSON(t, "Secure Preferences", `{ "extensions": { "opsettings": { @@ -100,7 +100,7 @@ func TestExtractOperaExtensions(t *testing.T) { }`) var out testCollector - err := extractOperaExtensions(path, &out) + err := extractExtensions(path, []string{"extensions.opsettings"}, &out) got := collected[record.Extension](t, &out) require.NoError(t, err) require.Len(t, got, 1) // system extension skipped diff --git a/internal/browser/chromium/extract_password.go b/internal/browser/chromium/extract_password.go index 0006079..e075868 100644 --- a/internal/browser/chromium/extract_password.go +++ b/internal/browser/chromium/extract_password.go @@ -15,12 +15,9 @@ const ( defaultLoginQuery = `SELECT origin_url, username_value, password_value, date_created FROM logins` ) -// accountLoginData holds the signed-in account's logins, which Chrome keeps apart from Login Data. -const accountLoginData = "Login Data For Account" - func extractPasswords(masterKeys masterkey.Set, path string, out browser.Collector) error { store := record.StoreLocal - if filepath.Base(path) == accountLoginData { + if filepath.Base(path) == accountLoginData.RelativePath { store = record.StoreAccount } database, err := sqlitex.Open(path) diff --git a/internal/browser/chromium/extract_password_test.go b/internal/browser/chromium/extract_password_test.go index 3a2de1a..d187f11 100644 --- a/internal/browser/chromium/extract_password_test.go +++ b/internal/browser/chromium/extract_password_test.go @@ -40,7 +40,7 @@ func TestExtractPasswords(t *testing.T) { // TestExtractPasswords_UndecryptableBlobStillListed keeps such a login, or a missing key would shrink the export. func TestExtractPasswords_UndecryptableBlobStillListed(t *testing.T) { - path := createTestDB(t, accountLoginData, loginsSchema, + path := createTestDB(t, accountLoginData.RelativePath, loginsSchema, insertLogin("https://enc.com", "https://enc.com/login", "carol", "763130deadbeef", 13350000000000000), ) diff --git a/internal/browser/chromium/extractors.go b/internal/browser/chromium/extractors.go index 0aec2e1..15e98fa 100644 --- a/internal/browser/chromium/extractors.go +++ b/internal/browser/chromium/extractors.go @@ -1,8 +1,8 @@ package chromium import ( - "context" "errors" + "fmt" "io/fs" "github.com/moond4rk/hackbrowserdata/internal/browser" @@ -11,82 +11,92 @@ import ( ) var ( - localState = browser.Source{RelativePath: "Local State", Shared: true, Optional: true} - loginData = browser.Source{RelativePath: "Login Data", Optional: true} - loginDataForAccount = browser.Source{RelativePath: accountLoginData, Optional: true} - cookies = browser.Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}} - bookmarks = browser.Source{RelativePath: "Bookmarks"} - history = browser.Source{RelativePath: "History"} - webData = browser.Source{RelativePath: "Web Data"} - securePreferences = browser.Source{RelativePath: "Secure Preferences"} - preferences = browser.Source{RelativePath: "Preferences", Optional: true} - localStorage = browser.Source{RelativePath: "Local Storage/leveldb", IsDir: true} - sessionStorage = browser.Source{RelativePath: "Session Storage", IsDir: true} - yaPassmanData = browser.Source{RelativePath: "Ya Passman Data"} - yaCreditCards = browser.Source{RelativePath: "Ya Credit Cards"} + localState = browser.Source{RelativePath: "Local State", FromUserDataDir: true, Shared: true, Optional: true} + loginData = browser.Source{RelativePath: "Login Data", Optional: true} + accountLoginData = browser.Source{RelativePath: "Login Data For Account", Optional: true} // the signed-in account's logins + cookies = browser.Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}} + bookmarks = browser.Source{RelativePath: "Bookmarks"} + history = browser.Source{RelativePath: "History"} + webData = browser.Source{RelativePath: "Web Data"} + securePreferences = browser.Source{RelativePath: "Secure Preferences"} + preferences = browser.Source{RelativePath: "Preferences", Optional: true} + localStorage = browser.Source{RelativePath: "Local Storage/leveldb", IsDir: true} + sessionStorage = browser.Source{RelativePath: "Session Storage", IsDir: true} + yaPassmanData = browser.Source{RelativePath: "Ya Passman Data"} + yaCreditCards = browser.Source{RelativePath: "Ya Credit Cards"} ) -var defaultExtractors = browser.Extractors{ - category.Password: newDecryptingExtractor(extractPasswords, loginData, loginDataForAccount), +// extractor is how one category is read: the files it needs, and how it parses them with the dir's master keys. +type extractor struct { + sources []browser.Source + needsMasterKeys bool + extract func(captured browser.ProfileSnapshot, masterKeys masterkey.Set, out browser.Collector) error +} + +var defaultExtractors = map[category.Category]extractor{ + category.Password: newDecryptingExtractor(extractPasswords, loginData, accountLoginData), category.Cookie: newDecryptingExtractor(extractCookies, cookies), category.Bookmark: newPlainExtractor(extractBookmarks, bookmarks), category.History: newPlainExtractor(extractHistories, history), category.Download: newPlainExtractor(extractDownloads, history), category.CreditCard: newDecryptingExtractor(extractCreditCards, webData), - category.Extension: newExtensionExtractor(extractExtensions), + category.Extension: newExtensionExtractor(extensionSettingsKeys...), category.LocalStorage: newPlainExtractor(extractLocalStorage, localStorage), category.SessionStorage: newPlainExtractor(extractSessionStorage, sessionStorage), } -// NeedsMasterKeys reports whether dataCategory's values are sealed with the dir's master keys, so a run that asks only -// for the others never retrieves a key. -func NeedsMasterKeys(dataCategory category.Category) bool { - switch dataCategory { - case category.Password, category.Cookie, category.CreditCard: - return true - default: - return false - } +// Sources lists the files dataCategory is read from in any profile of dir; the dir's browser may not support it. +func Sources(dir browser.UserDataDir, dataCategory category.Category) (sources []browser.Source, supported bool) { + extractor, ok := dirExtractors(dir)[dataCategory] + return extractor.sources, ok } -// withoutExtensionList names forks whose Preferences files hold no extension list, so extensions are unsupported there. -var withoutExtensionList = map[string]bool{"qq": true, "sogou": true} - -func Extractors(dir browser.UserDataDir, _ browser.Profile) browser.Extractors { - extractors := kindExtractors(vaultKindOf(dir)) - if withoutExtensionList[dir.Browser.Name] { - delete(extractors, category.Extension) +// Extract decrypts with masterKeys, which lack each key version that could not be retrieved. +func Extract(captured browser.ProfileSnapshot, masterKeys masterkey.Set, dataCategory category.Category, out browser.Collector) error { + extractor, ok := dirExtractors(captured.UserDataDir)[dataCategory] + if !ok { + return fmt.Errorf("%s has no %s extractor", captured.UserDataDir.Browser.Name, dataCategory) } - return extractors + return extractor.extract(captured, masterKeys, out) } -func kindExtractors(vaultKind string) browser.Extractors { - extractors := make(browser.Extractors, len(defaultExtractors)) +// NeedsMasterKeys reports whether dir seals dataCategory's values with its master keys, so a run that asks only for the +// other categories never retrieves a key. +func NeedsMasterKeys(dir browser.UserDataDir, dataCategory category.Category) bool { + return dirExtractors(dir)[dataCategory].needsMasterKeys +} + +func dirExtractors(dir browser.UserDataDir) map[category.Category]extractor { + extractors := make(map[category.Category]extractor, len(defaultExtractors)) for dataCategory, extractor := range defaultExtractors { extractors[dataCategory] = extractor } - if fork, ok := overrideForVaultKind(vaultKind); ok { + if fork, ok := findFork(dir); ok { for dataCategory, extractor := range fork.extractors { extractors[dataCategory] = extractor } + for _, dataCategory := range fork.unsupported { + delete(extractors, dataCategory) + } } return extractors } -// newDecryptingExtractor parses each file in turn, so a store that is missing or broken keeps the others' records. -func newDecryptingExtractor(parse func(masterkey.Set, string, browser.Collector) error, sources ...browser.Source) browser.Extractor { - return browser.Extractor{ +// newDecryptingExtractor extracts each file in turn, so a store that is missing or broken keeps the others' records. +func newDecryptingExtractor(extractFile func(masterkey.Set, string, browser.Collector) error, dataSources ...browser.Source) extractor { + return extractor{ // The dir's master keys come from KeySources, so a decrypting extraction must find them in the snapshot too. - Sources: append(sources, KeySources()...), - Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { + sources: append(dataSources, KeySources()...), + needsMasterKeys: true, + extract: func(captured browser.ProfileSnapshot, masterKeys masterkey.Set, out browser.Collector) error { var errs []error - for _, source := range sources { - path, err := input.Path(source) + for _, source := range dataSources { + path, err := captured.Path(source) if source.Optional && errors.Is(err, fs.ErrNotExist) { continue } if err == nil { - err = parse(input.MasterKeys(), path, out) + err = extractFile(masterKeys, path, out) } errs = append(errs, err) } @@ -95,15 +105,15 @@ func newDecryptingExtractor(parse func(masterkey.Set, string, browser.Collector) } } -func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor { - return browser.Extractor{ - Sources: []browser.Source{source}, - Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { - path, err := input.Path(source) +func newPlainExtractor(extractFile func(string, browser.Collector) error, source browser.Source) extractor { + return extractor{ + sources: []browser.Source{source}, + extract: func(captured browser.ProfileSnapshot, _ masterkey.Set, out browser.Collector) error { + path, err := captured.Path(source) if err != nil { return err } - return parse(path, out) + return extractFile(path, out) }, } } diff --git a/internal/browser/chromium/extractors_test.go b/internal/browser/chromium/extractors_test.go index 8b6687a..35bc9cd 100644 --- a/internal/browser/chromium/extractors_test.go +++ b/internal/browser/chromium/extractors_test.go @@ -1,7 +1,6 @@ package chromium import ( - "context" "testing" "github.com/stretchr/testify/assert" @@ -10,15 +9,16 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/record" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) func TestExtractors_CoverEveryCategory(t *testing.T) { - extractors := Extractors(browser.UserDataDir{Browser: testBrowser("chrome")}, browser.Profile{}) + extractors := dirExtractors(browser.UserDataDir{Browser: testBrowser("chrome")}) for _, dataCategory := range category.All() { extractor, ok := extractors[dataCategory] if assert.Truef(t, ok, "no extractor for %s", dataCategory) { - assert.NotNil(t, extractor.Extract, dataCategory) - assert.NotEmpty(t, extractor.Sources, dataCategory) + assert.NotNil(t, extractor.extract, dataCategory) + assert.NotEmpty(t, extractor.sources, dataCategory) } } } @@ -26,9 +26,23 @@ func TestExtractors_CoverEveryCategory(t *testing.T) { func TestExtractors_OverridesFollowTheBrowserNotTheDirectory(t *testing.T) { yandex, ok := browser.Lookup("yandex") require.True(t, ok) - extractors := Extractors(browser.UserDataDir{ID: "yandex-2", Browser: yandex}, browser.Profile{}) - assert.Equal(t, "Ya Passman Data", extractors[category.Password].Sources[0].RelativePath) - assert.Equal(t, "Ya Credit Cards", extractors[category.CreditCard].Sources[0].RelativePath) + dir := browser.UserDataDir{ID: "yandex-2", Browser: yandex} + for dataCategory, relativePath := range map[category.Category]string{ + category.Password: "Ya Passman Data", category.CreditCard: "Ya Credit Cards", + } { + sources, supported := Sources(dir, dataCategory) + require.True(t, supported, dataCategory) + assert.Equal(t, relativePath, sources[0].RelativePath) + } +} + +func TestSources_ForksWithoutAnExtensionList(t *testing.T) { + for _, name := range []string{"qq", "sogou"} { + chromiumBrowser, ok := browser.Lookup(name) + require.True(t, ok, name) + _, supported := Sources(browser.UserDataDir{Browser: chromiumBrowser}, category.Extension) + assert.False(t, supported, name) + } } // TestExtractors_EachProfileReadsItsOwnFiles reads one snapshot shared by every profile; each must get its own files. @@ -41,7 +55,7 @@ func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) { want := map[string]string{"Default": "Home", "Profile 1": "Work"} for _, profile := range []browser.Profile{{Name: "Default", RelativePath: "Default"}, {Name: "Profile 1", RelativePath: "Profile 1"}} { var out testCollector - require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, nil), &out)) + require.NoError(t, Extract(browser.NewProfileSnapshot(dir, profile, dirSnapshot), nil, category.History, &out)) got := collected[record.History](t, &out) require.Len(t, got, 1, profile.Name) assert.Equal(t, want[profile.Name], got[0].Title, profile.Name) @@ -58,16 +72,16 @@ func TestExtractors_ExtensionsFallBackToPreferences(t *testing.T) { {"opera", `{"extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Ext", "version": "1.0"}}}}}`}, } for _, testCase := range tests { - input := browser.NewInput(snapshotOf(t, map[string]string{ - "Default/Secure Preferences": createTestJSON(t, "Secure Preferences", `{"protection": {"macs": {}}}`), - "Default/Preferences": createTestJSON(t, "Preferences", testCase.preferences), - }), browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) chromiumBrowser, ok := browser.Lookup(testCase.browserName) require.True(t, ok, testCase.browserName) + captured := browser.NewProfileSnapshot(browser.UserDataDir{Browser: chromiumBrowser}, browser.Profile{Name: "Default", RelativePath: "Default"}, + snapshotOf(t, map[string]string{ + "Default/Secure Preferences": createTestJSON(t, "Secure Preferences", `{"protection": {"macs": {}}}`), + "Default/Preferences": createTestJSON(t, "Preferences", testCase.preferences), + })) var out testCollector - extractor := Extractors(browser.UserDataDir{Browser: chromiumBrowser}, input.Profile)[category.Extension] - require.NoError(t, extractor.Extract(context.Background(), input, &out), testCase.browserName) + require.NoError(t, Extract(captured, nil, category.Extension, &out), testCase.browserName) got := collected[record.Extension](t, &out) require.Len(t, got, 1, testCase.browserName) assert.Equal(t, "Ext", got[0].Name, testCase.browserName) @@ -78,13 +92,13 @@ func TestDecryptingExtractor_ReadsSourcesInOrder(t *testing.T) { local := createTestDB(t, "Login Data", loginsSchema, insertLogin("https://local.example", "", "local-user", "", 13340000000000000)) account := createTestDB(t, "Login Data For Account", loginsSchema, insertLogin("https://account.example", "", "account-user", "", 13360000000000000)) - input := browser.NewInput(snapshotOf(t, map[string]string{ + captured := defaultProfileSnapshot(snapshotOf(t, map[string]string{ "Default/Login Data": local, "Default/Login Data For Account": account, - }), browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) + })) var out testCollector - require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) + require.NoError(t, defaultExtractors[category.Password].extract(captured, nil, &out)) got := collected[record.Login](t, &out) require.Len(t, got, 2) assert.Equal(t, "local-user", got[0].Username) @@ -96,11 +110,10 @@ func TestDecryptingExtractor_ReadsSourcesInOrder(t *testing.T) { func TestDecryptingExtractor_SkipsAbsentOptionalSource(t *testing.T) { account := createTestDB(t, "Login Data For Account", loginsSchema, insertLogin("https://account.example", "", "account-user", "", 13360000000000000)) - input := browser.NewInput(snapshotOf(t, map[string]string{"Default/Login Data For Account": account}), - browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) + captured := defaultProfileSnapshot(snapshotOf(t, map[string]string{"Default/Login Data For Account": account})) var out testCollector - require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) + require.NoError(t, defaultExtractors[category.Password].extract(captured, nil, &out)) got := collected[record.Login](t, &out) require.Len(t, got, 1) assert.Equal(t, record.StoreAccount, got[0].Store) @@ -110,12 +123,16 @@ func TestDecryptingExtractor_BrokenSourceKeepsTheOthers(t *testing.T) { broken := createTestJSON(t, "Login Data", "not a database") account := createTestDB(t, "Login Data For Account", loginsSchema, insertLogin("https://account.example", "", "account-user", "", 13360000000000000)) - input := browser.NewInput(snapshotOf(t, map[string]string{ + captured := defaultProfileSnapshot(snapshotOf(t, map[string]string{ "Default/Login Data": broken, "Default/Login Data For Account": account, - }), browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) + })) var out testCollector - require.Error(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) + require.Error(t, defaultExtractors[category.Password].extract(captured, nil, &out)) assert.Len(t, collected[record.Login](t, &out), 1) } + +func defaultProfileSnapshot(dirSnapshot snapshot.Snapshot) browser.ProfileSnapshot { + return browser.NewProfileSnapshot(browser.UserDataDir{Browser: testBrowser("chrome")}, browser.Profile{Name: "Default", RelativePath: "Default"}, dirSnapshot) +} diff --git a/internal/browser/chromium/fork.go b/internal/browser/chromium/fork.go new file mode 100644 index 0000000..3125c72 --- /dev/null +++ b/internal/browser/chromium/fork.go @@ -0,0 +1,83 @@ +package chromium + +import ( + "github.com/moond4rk/hackbrowserdata/internal/browser" + "github.com/moond4rk/hackbrowserdata/internal/category" +) + +// vaultKindChromium is the keys.json kind of every Chromium browser not listed in forks. +const vaultKindChromium = "chromium" + +// fork is a Chromium fork that stores data its own way: its browsers, its keys.json kind, the extractors it swaps, and +// the categories its files do not hold. +type fork struct { + browserNames []string + vaultKind string // "" keeps vaultKindChromium + extractors map[category.Category]extractor + unsupported []category.Category +} + +// forks match Browser.Name, never UserDataDirID, which differs for a second user data dir of one browser. +var forks = []fork{ + { + browserNames: []string{"yandex"}, + vaultKind: "chromium-yandex", + extractors: map[category.Category]extractor{ + category.Password: newDecryptingExtractor(extractYandexPasswords, yaPassmanData), + category.CreditCard: newDecryptingExtractor(extractYandexCreditCards, yaCreditCards), + }, + }, + { + browserNames: []string{"opera", "opera-gx", "vought"}, + vaultKind: "chromium-opera", + extractors: map[category.Category]extractor{ + category.Extension: newExtensionExtractor("extensions.opsettings"), + }, + }, + { + // QQ and Sogou keep no extension list in their Preferences files. + browserNames: []string{"qq", "sogou"}, + unsupported: []category.Category{category.Extension}, + }, +} + +func findForkByName(browserName string) (fork, bool) { + for _, candidate := range forks { + for _, name := range candidate.browserNames { + if name == browserName { + return candidate, true + } + } + } + return fork{}, false +} + +func findForkByVaultKind(vaultKind string) (fork, bool) { + for _, candidate := range forks { + if candidate.vaultKind != "" && candidate.vaultKind == vaultKind { + return candidate, true + } + } + return fork{}, false +} + +func isKnownVaultKind(vaultKind string) bool { + _, ok := findForkByVaultKind(vaultKind) + return ok || vaultKind == vaultKindChromium +} + +// VaultKind names a vault's on-disk format, so a reader without the browser in its table still picks its files. +func VaultKind(chromiumBrowser browser.Browser) string { + if fork, ok := findForkByName(chromiumBrowser.Name); ok && fork.vaultKind != "" { + return fork.vaultKind + } + return vaultKindChromium +} + +// findFork matches the browser's name first; a restored browser this build does not know matches by its kind. +func findFork(dir browser.UserDataDir) (fork, bool) { + if fork, ok := findForkByName(dir.Browser.Name); ok { + return fork, true + } + return findForkByVaultKind(dir.VaultKind) +} diff --git a/internal/browser/chromium/fork_test.go b/internal/browser/chromium/fork_test.go new file mode 100644 index 0000000..e5deb92 --- /dev/null +++ b/internal/browser/chromium/fork_test.go @@ -0,0 +1,109 @@ +package chromium + +import ( + "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/record" +) + +func TestForks_NameChromiumBrowsers(t *testing.T) { + for _, fork := range forks { + for _, name := range fork.browserNames { + chromiumBrowser, ok := browser.Lookup(name) + if assert.Truef(t, ok, "fork %q names no browser", name) { + assert.Equalf(t, browser.Chromium, chromiumBrowser.Base, "fork %q is not a Chromium browser", name) + } + } + } +} + +// TestForks_KindsAndNamesAreUnique keeps findForkByName and findForkByVaultKind from depending on table order. +func TestForks_KindsAndNamesAreUnique(t *testing.T) { + kinds := map[string]bool{vaultKindChromium: true} + names := map[string]bool{} + for _, fork := range forks { + if fork.vaultKind != "" { + assert.Falsef(t, kinds[fork.vaultKind], "kind %q is used twice", fork.vaultKind) + kinds[fork.vaultKind] = true + } + for _, name := range fork.browserNames { + assert.Falsef(t, names[name], "browser %q is in two forks", name) + names[name] = true + } + } +} + +// TestVaultKind_RoundTripsEveryFork checks a kind leads back to its fork, or restore would parse it as plain Chromium. +func TestVaultKind_RoundTripsEveryFork(t *testing.T) { + for _, fork := range forks { + for _, name := range fork.browserNames { + kind := VaultKind(browser.Browser{Name: name}) + if fork.vaultKind == "" { + assert.Equalf(t, vaultKindChromium, kind, "fork %q keeps Chromium's kind", name) + continue + } + require.Equalf(t, fork.vaultKind, kind, "fork %q", name) + restored, ok := findForkByVaultKind(kind) + require.True(t, ok, kind) + assert.Equalf(t, categoriesOf(fork.extractors), categoriesOf(restored.extractors), "kind %s of %q", kind, name) + } + } + assert.Equal(t, vaultKindChromium, VaultKind(browser.Browser{Name: "chrome"})) + assert.True(t, isKnownVaultKind(vaultKindChromium)) + assert.False(t, isKnownVaultKind("bogus")) + assert.False(t, isKnownVaultKind("")) +} + +// TestDiscoverProfiles_ReadsAnUnknownBrowserInItsVaultKind covers a restored fork this build does not know by name. +func TestDiscoverProfiles_ReadsAnUnknownBrowserInItsVaultKind(t *testing.T) { + nightly := browser.Browser{Name: "nightly", DisplayName: "Nightly", Base: browser.Chromium} + dir := browser.UserDataDir{ID: "nightly", Browser: nightly, Path: t.TempDir(), VaultKind: "chromium-yandex"} + _, err := DiscoverProfiles(dir) + require.NoError(t, err) + sources, supported := Sources(dir, category.Password) + require.True(t, supported) + assert.Equal(t, "Ya Passman Data", sources[0].RelativePath) + + dir.VaultKind = "bogus" + _, err = DiscoverProfiles(dir) + require.Error(t, err) +} + +func categoriesOf(extractors map[category.Category]extractor) []category.Category { + var out []category.Category + for _, dataCategory := range category.All() { + if _, ok := extractors[dataCategory]; ok { + out = append(out, dataCategory) + } + } + return out +} + +func TestExtractors_OperaReadsOpsettings(t *testing.T) { + preferencesPath := createTestJSON(t, "Secure Preferences", `{ + "extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Opera Ext", "version": "1.0"}}}} + }`) + dirSnapshot := snapshotOf(t, map[string]string{"Default/Secure Preferences": preferencesPath}) + profile := browser.Profile{Name: "Default", RelativePath: "Default"} + + for _, name := range []string{"opera", "opera-gx", "vought"} { + chromiumBrowser, ok := browser.Lookup(name) + require.True(t, ok, name) + var out testCollector + captured := browser.NewProfileSnapshot(browser.UserDataDir{Browser: chromiumBrowser}, profile, dirSnapshot) + require.NoError(t, Extract(captured, nil, category.Extension, &out), name) + got := collected[record.Extension](t, &out) + require.Len(t, got, 1, name) + assert.Equal(t, "Opera Ext", got[0].Name, name) + } + + chrome, ok := browser.Lookup("chrome") + require.True(t, ok) + err := Extract(browser.NewProfileSnapshot(browser.UserDataDir{Browser: chrome}, profile, dirSnapshot), nil, category.Extension, &testCollector{}) + require.Error(t, err, "Chrome has no opsettings fallback") +} diff --git a/internal/browser/chromium/override.go b/internal/browser/chromium/override.go deleted file mode 100644 index f61bf41..0000000 --- a/internal/browser/chromium/override.go +++ /dev/null @@ -1,76 +0,0 @@ -package chromium - -import ( - "github.com/moond4rk/hackbrowserdata/internal/browser" - "github.com/moond4rk/hackbrowserdata/internal/category" -) - -// vaultKindChromium is the keys.json kind of every Chromium browser no override covers. -const vaultKindChromium = "chromium" - -// override is a fork that stores data its own way: its browsers, its keys.json kind, and the extractors it swaps. -type override struct { - browserNames []string - vaultKind string - extractors browser.Extractors -} - -// overrides match Browser.Name, never UserDataDirID, which differs for a second user data dir of one browser. -var overrides = []override{ - { - browserNames: []string{"yandex"}, - vaultKind: "chromium-yandex", - extractors: browser.Extractors{ - category.Password: newDecryptingExtractor(extractYandexPasswords, yaPassmanData), - category.CreditCard: newDecryptingExtractor(extractYandexCreditCards, yaCreditCards), - }, - }, - { - browserNames: []string{"opera", "opera-gx", "vought"}, - vaultKind: "chromium-opera", - extractors: browser.Extractors{ - category.Extension: newExtensionExtractor(extractOperaExtensions), - }, - }, -} - -func overrideFor(browserName string) (override, bool) { - for _, fork := range overrides { - for _, name := range fork.browserNames { - if name == browserName { - return fork, true - } - } - } - return override{}, false -} - -func overrideForVaultKind(vaultKind string) (override, bool) { - for _, fork := range overrides { - if fork.vaultKind == vaultKind { - return fork, true - } - } - return override{}, false -} - -func isVaultKind(vaultKind string) bool { - _, ok := overrideForVaultKind(vaultKind) - return ok || vaultKind == vaultKindChromium -} - -// VaultKind names a vault's on-disk format, so a reader without the browser in its table still picks its files. -func VaultKind(chromiumBrowser browser.Browser) string { - if fork, ok := overrideFor(chromiumBrowser.Name); ok { - return fork.vaultKind - } - return vaultKindChromium -} - -// vaultKindOf is a restored dir's own kind, or else its browser's. -func vaultKindOf(dir browser.UserDataDir) string { - if dir.VaultKind != "" { - return dir.VaultKind - } - return VaultKind(dir.Browser) -} diff --git a/internal/browser/chromium/override_test.go b/internal/browser/chromium/override_test.go deleted file mode 100644 index 131a6a9..0000000 --- a/internal/browser/chromium/override_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package chromium - -import ( - "context" - "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/record" -) - -func TestOverrides_NameChromiumBrowsers(t *testing.T) { - for _, fork := range overrides { - for _, name := range fork.browserNames { - chromiumBrowser, ok := browser.Lookup(name) - if assert.Truef(t, ok, "override %q names no browser", name) { - assert.Equalf(t, browser.Chromium, chromiumBrowser.Base, "override %q is not a Chromium browser", name) - } - } - } -} - -// TestOverrides_KindsAndNamesAreUnique keeps overrideFor and overrideForVaultKind from depending on table order. -func TestOverrides_KindsAndNamesAreUnique(t *testing.T) { - kinds := map[string]bool{vaultKindChromium: true} - names := map[string]bool{} - for _, fork := range overrides { - assert.Falsef(t, kinds[fork.vaultKind], "kind %q is used twice", fork.vaultKind) - kinds[fork.vaultKind] = true - for _, name := range fork.browserNames { - assert.Falsef(t, names[name], "browser %q is in two overrides", name) - names[name] = true - } - } -} - -// TestVaultKind_RoundTripsEveryFork checks a kind leads back to its fork, or restore would parse it as plain Chromium. -func TestVaultKind_RoundTripsEveryFork(t *testing.T) { - for _, fork := range overrides { - for _, name := range fork.browserNames { - kind := VaultKind(browser.Browser{Name: name}) - require.Equalf(t, fork.vaultKind, kind, "override %q", name) - restored, ok := overrideForVaultKind(kind) - require.True(t, ok, kind) - assert.Equalf(t, categoriesOf(fork.extractors), categoriesOf(restored.extractors), "kind %s of %q", kind, name) - } - } - assert.Equal(t, vaultKindChromium, VaultKind(browser.Browser{Name: "chrome"})) - assert.True(t, isVaultKind(vaultKindChromium)) - assert.False(t, isVaultKind("bogus")) - assert.False(t, isVaultKind("")) -} - -// TestDiscoverAt_ReadsAnUnknownBrowserInItsVaultKind keeps a restored fork's own name while its kind picks the files. -func TestDiscoverAt_ReadsAnUnknownBrowserInItsVaultKind(t *testing.T) { - nightly := browser.Browser{Name: "nightly", DisplayName: "Nightly", Base: browser.Chromium} - dir, err := DiscoverAt(nightly, "chromium-yandex", "nightly", t.TempDir()) - require.NoError(t, err) - assert.Equal(t, nightly, dir.Browser) - assert.Equal(t, "Ya Passman Data", Extractors(dir, browser.Profile{})[category.Password].Sources[0].RelativePath) - - _, err = DiscoverAt(nightly, "bogus", "nightly", t.TempDir()) - require.Error(t, err) -} - -func categoriesOf(extractors browser.Extractors) []category.Category { - var out []category.Category - for _, dataCategory := range category.All() { - if _, ok := extractors[dataCategory]; ok { - out = append(out, dataCategory) - } - } - return out -} - -func TestExtractors_OperaReadsOpsettings(t *testing.T) { - preferencesPath := createTestJSON(t, "Secure Preferences", `{ - "extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Opera Ext", "version": "1.0"}}}} - }`) - input := browser.NewInput(snapshotOf(t, map[string]string{"Default/Secure Preferences": preferencesPath}), - browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil) - - for _, name := range []string{"opera", "opera-gx", "vought"} { - chromiumBrowser, ok := browser.Lookup(name) - require.True(t, ok, name) - var out testCollector - require.NoError(t, Extractors(browser.UserDataDir{Browser: chromiumBrowser}, input.Profile)[category.Extension].Extract(context.Background(), input, &out), name) - got := collected[record.Extension](t, &out) - require.Len(t, got, 1, name) - assert.Equal(t, "Opera Ext", got[0].Name, name) - } - - chrome, ok := browser.Lookup("chrome") - require.True(t, ok) - err := Extractors(browser.UserDataDir{Browser: chrome}, input.Profile)[category.Extension].Extract(context.Background(), input, &testCollector{}) - require.Error(t, err, "Chrome has no opsettings fallback") -} diff --git a/internal/browser/extract.go b/internal/browser/extract.go new file mode 100644 index 0000000..891635c --- /dev/null +++ b/internal/browser/extract.go @@ -0,0 +1,67 @@ +package browser + +import ( + "errors" + "fmt" + "io/fs" + "path" + "strings" + + "github.com/moond4rk/hackbrowserdata/internal/record" + "github.com/moond4rk/hackbrowserdata/internal/snapshot" +) + +// Source is one file or directory an extraction reads. +type Source struct { + RelativePath string // slash-separated, relative to the profile, or to the user data dir when FromUserDataDir + Fallbacks []string // older locations, read only when RelativePath is absent + IsDir bool + FromUserDataDir bool // lives outside the profile, such as Local State, or Safari's files elsewhere under ~/Library + Shared bool // the whole dir's, such as Local State, so it never makes an extraction present on its own + Optional bool // the extraction still runs without it +} + +// RelativePaths lists RelativePath and then its Fallbacks, the order they are tried in. +func (s Source) RelativePaths() []string { + return append([]string{s.RelativePath}, s.Fallbacks...) +} + +// DirRelativePaths are the RelativePaths for a profile, relative to the user data dir. +func (s Source) DirRelativePaths(profile Profile) []string { + paths := s.RelativePaths() + if !s.FromUserDataDir { + for i, relativePath := range paths { + paths[i] = path.Join(profile.RelativePath, relativePath) + } + } + return paths +} + +// Collector sets every record's Browser and Profile; Fail reports a bad record and the extraction goes on. +type Collector interface { + Add(row record.Record) + Fail(err error) +} + +// ProfileSnapshot is one profile's share of a captured user data dir; an extraction reads nothing else. +type ProfileSnapshot struct { + UserDataDir UserDataDir + Profile Profile + dirSnapshot snapshot.Snapshot +} + +func NewProfileSnapshot(dir UserDataDir, profile Profile, dirSnapshot snapshot.Snapshot) ProfileSnapshot { + return ProfileSnapshot{UserDataDir: dir, Profile: profile, dirSnapshot: dirSnapshot} +} + +// Path skips a candidate that was never captured but returns the error of one whose copy failed. +func (s ProfileSnapshot) Path(source Source) (string, error) { + for _, relativePath := range source.DirRelativePaths(s.Profile) { + capturedPath, err := s.dirSnapshot.Path(relativePath) + if errors.Is(err, fs.ErrNotExist) { + continue + } + return capturedPath, err + } + return "", fmt.Errorf("%s: %w", strings.Join(source.RelativePaths(), " or "), fs.ErrNotExist) +} diff --git a/internal/browser/extractor_test.go b/internal/browser/extract_test.go similarity index 60% rename from internal/browser/extractor_test.go rename to internal/browser/extract_test.go index ad49a11..902254f 100644 --- a/internal/browser/extractor_test.go +++ b/internal/browser/extract_test.go @@ -21,37 +21,37 @@ func writeSnapshotFile(t *testing.T, root, relativePath string) string { return path } -func TestInputPath(t *testing.T) { +func TestProfileSnapshotPath(t *testing.T) { root := t.TempDir() legacyCookies := writeSnapshotFile(t, root, "chrome/Default/Cookies") localState := writeSnapshotFile(t, root, "chrome/Local State") dirSnapshot := snapshot.Open(root).Snapshot("chrome") - input := NewInput(dirSnapshot, Profile{Name: "Default", RelativePath: "Default"}, nil, nil) + captured := NewProfileSnapshot(UserDataDir{ID: "chrome"}, Profile{Name: "Default", RelativePath: "Default"}, dirSnapshot) - got, err := input.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}) + got, err := captured.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}) require.NoError(t, err) assert.Equal(t, legacyCookies, got, "a candidate that was never captured is skipped") - got, err = input.Path(Source{RelativePath: "Local State", Shared: true}) + got, err = captured.Path(Source{RelativePath: "Local State", FromUserDataDir: true}) require.NoError(t, err) - assert.Equal(t, localState, got, "a shared source resolves under the user data dir, not the profile") + assert.Equal(t, localState, got, "a source from the user data dir resolves there, not under the profile") - _, err = input.Path(Source{RelativePath: "History"}) + _, err = captured.Path(Source{RelativePath: "History"}) require.ErrorIs(t, err, fs.ErrNotExist) } -func TestInputPath_FlatLayoutProfile(t *testing.T) { +func TestProfileSnapshotPath_FlatLayoutProfile(t *testing.T) { root := t.TempDir() history := writeSnapshotFile(t, root, "opera/History") - input := NewInput(snapshot.Open(root).Snapshot("opera"), Profile{Name: "Opera Stable"}, nil, nil) + captured := NewProfileSnapshot(UserDataDir{ID: "opera"}, Profile{Name: "Opera Stable"}, snapshot.Open(root).Snapshot("opera")) - got, err := input.Path(Source{RelativePath: "History"}) + got, err := captured.Path(Source{RelativePath: "History"}) require.NoError(t, err) assert.Equal(t, history, got) } -// TestInputPath_FailedCopyIsReported makes a failed copy an error, not a reason to read a lower candidate. -func TestInputPath_FailedCopyIsReported(t *testing.T) { +// TestProfileSnapshotPath_FailedCopyIsReported makes a failed copy an error, not a reason to read a lower candidate. +func TestProfileSnapshotPath_FailedCopyIsReported(t *testing.T) { from := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(from, "Default", "Network", "Cookies"), 0o700)) writeSnapshotFile(t, from, "Default/Cookies") @@ -64,16 +64,16 @@ func TestInputPath_FailedCopyIsReported(t *testing.T) { {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Cookies"}, })) - input := NewInput(root.Snapshot("chrome"), Profile{Name: "Default", RelativePath: "Default"}, nil, nil) - _, err = input.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}) + captured := NewProfileSnapshot(UserDataDir{ID: "chrome"}, Profile{Name: "Default", RelativePath: "Default"}, root.Snapshot("chrome")) + _, err = captured.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}) require.Error(t, err) assert.NotErrorIs(t, err, fs.ErrNotExist) } -func TestSourceCandidatePaths(t *testing.T) { +func TestSourceDirRelativePaths(t *testing.T) { profile := Profile{Name: "Default", RelativePath: "Default"} - assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}.CandidatePaths(profile)) - assert.Equal(t, []string{"Local State"}, Source{RelativePath: "Local State", Shared: true}.CandidatePaths(profile)) - assert.Equal(t, []string{"History"}, Source{RelativePath: "History"}.CandidatePaths(Profile{Name: "default"}), + assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}.DirRelativePaths(profile)) + assert.Equal(t, []string{"Local State"}, Source{RelativePath: "Local State", FromUserDataDir: true}.DirRelativePaths(profile)) + assert.Equal(t, []string{"History"}, Source{RelativePath: "History"}.DirRelativePaths(Profile{Name: "default"}), "a user data dir that is itself the profile") } diff --git a/internal/browser/extractor.go b/internal/browser/extractor.go deleted file mode 100644 index 167babc..0000000 --- a/internal/browser/extractor.go +++ /dev/null @@ -1,106 +0,0 @@ -package browser - -import ( - "context" - "errors" - "fmt" - "io/fs" - "path" - "strings" - - "github.com/moond4rk/hackbrowserdata/internal/category" - "github.com/moond4rk/hackbrowserdata/internal/keychain" - "github.com/moond4rk/hackbrowserdata/internal/masterkey" - "github.com/moond4rk/hackbrowserdata/internal/record" - "github.com/moond4rk/hackbrowserdata/internal/snapshot" -) - -// Source is one file or directory an extractor reads. -type Source struct { - RelativePath string // slash-separated, relative to the profile dir, or to the user data dir when Shared - Fallbacks []string // older locations, read only when RelativePath is absent - IsDir bool - Shared bool // belongs to the whole user data dir, such as Local State, so it is captured once per dir - Optional bool // the extraction still runs without it -} - -// RelativePaths lists RelativePath and then its Fallbacks, the order they are tried in. -func (s Source) RelativePaths() []string { - return append([]string{s.RelativePath}, s.Fallbacks...) -} - -// CandidatePaths are the RelativePaths for a profile, relative to the user data dir. -func (s Source) CandidatePaths(profile Profile) []string { - paths := s.RelativePaths() - if !s.Shared { - for i, relativePath := range paths { - paths[i] = path.Join(profile.RelativePath, relativePath) - } - } - return paths -} - -type Extractor struct { - Sources []Source - Extract func(ctx context.Context, input Input, out Collector) error -} - -type Extractors map[category.Category]Extractor - -// Collector sets every record's Browser and Profile; Fail reports a bad record and the extraction goes on. -type Collector interface { - Add(row record.Record) - Fail(err error) -} - -// LoginKeychain is what an extractor reads from the run's macOS login keychain. -type LoginKeychain interface { - InternetPasswords(ctx context.Context) ([]keychain.InternetPassword, error) -} - -// Input is what an extractor reads for one profile: its captured files, the dir's master keys, and the run's secrets. -type Input struct { - Profile Profile - snapshot snapshot.Snapshot - masterKeys masterkey.Set - loginKeychain LoginKeychain - firefoxPassword string -} - -// NewInput takes the dir's master keys, nil for bases that keep none, and the run's login keychain, nil off macOS and -// in a restore. -func NewInput(dirSnapshot snapshot.Snapshot, profile Profile, masterKeys masterkey.Set, loginKeychain LoginKeychain) Input { - return Input{Profile: profile, snapshot: dirSnapshot, masterKeys: masterKeys, loginKeychain: loginKeychain} -} - -// Path skips a candidate that was never captured but returns the error of one whose copy failed. -func (in Input) Path(source Source) (string, error) { - for _, relativePath := range source.CandidatePaths(in.Profile) { - capturedPath, err := in.snapshot.Path(relativePath) - if errors.Is(err, fs.ErrNotExist) { - continue - } - return capturedPath, err - } - return "", fmt.Errorf("%s: %w", strings.Join(source.RelativePaths(), " or "), fs.ErrNotExist) -} - -// MasterKeys lacks each key version that could not be retrieved. -func (in Input) MasterKeys() masterkey.Set { - return in.masterKeys -} - -func (in Input) LoginKeychain() LoginKeychain { - return in.loginKeychain -} - -// WithFirefoxPassword sets the Firefox primary password; only the dump path supplies one. -func (in Input) WithFirefoxPassword(password string) Input { - in.firefoxPassword = password - return in -} - -// FirefoxPrimaryPassword is the user's primary password, "" when none was given. -func (in Input) FirefoxPrimaryPassword() string { - return in.firefoxPassword -} diff --git a/internal/browser/firefox/firefox.go b/internal/browser/firefox/firefox.go index f43958c..a7b0323 100644 --- a/internal/browser/firefox/firefox.go +++ b/internal/browser/firefox/firefox.go @@ -2,7 +2,6 @@ package firefox import ( - "context" "errors" "fmt" "io/fs" @@ -22,8 +21,14 @@ var ( webappsStore = browser.Source{RelativePath: "webappsstore.sqlite"} ) -// defaultExtractors has no credit card or session storage extractor, because Firefox keeps none that HBD reads. -var defaultExtractors = browser.Extractors{ +// extractor is how one category is read: the files it needs, and how it parses them with the user's primary password. +type extractor struct { + sources []browser.Source + extract func(captured browser.ProfileSnapshot, primaryPassword string, out browser.Collector) error +} + +// extractors has no credit card or session storage extractor, because Firefox keeps none that HBD reads. +var extractors = map[category.Category]extractor{ category.Password: newDecryptingExtractor(extractPasswords, loginsJSON), category.Cookie: newPlainExtractor(extractCookies, cookiesDB), category.Bookmark: newPlainExtractor(extractBookmarks, placesDB), @@ -36,7 +41,10 @@ var defaultExtractors = browser.Extractors{ // Discover takes -p as one profile: its parent is the Profiles directory, and only that profile is selected. func Discover(firefoxBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { if options.ProfilePath != "" { - return profileAt(firefoxBrowser, options.ProfilePath), nil + if dir, ok := dirFromProfilePath(firefoxBrowser, options.ProfilePath); ok { + return []browser.UserDataDir{dir}, nil + } + return nil, nil } var errs []error var dirs []browser.UserDataDir @@ -56,18 +64,18 @@ func Discover(firefoxBrowser browser.Browser, options browser.DiscoverOptions) ( return dirs, errors.Join(errs...) } -func profileAt(firefoxBrowser browser.Browser, path string) []browser.UserDataDir { +func dirFromProfilePath(firefoxBrowser browser.Browser, path string) (browser.UserDataDir, bool) { clean := filepath.Clean(path) if !hasDataFile(clean) { - return nil + return browser.UserDataDir{}, false } name := filepath.Base(clean) - return []browser.UserDataDir{{ + return browser.UserDataDir{ ID: firefoxBrowser.UserDataDirID(0), Browser: firefoxBrowser, Path: filepath.Dir(clean), Profiles: []browser.Profile{{Name: name, RelativePath: name}}, - }} + }, true } func userDataDirPaths(firefoxBrowser browser.Browser, options browser.DiscoverOptions) []string { @@ -94,8 +102,8 @@ func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { } func hasDataFile(path string) bool { - for _, extractor := range defaultExtractors { - for _, source := range extractor.Sources { + for _, extractor := range extractors { + for _, source := range extractor.sources { if source.Optional { continue } @@ -109,46 +117,53 @@ func hasDataFile(path string) bool { return false } -func Extractors(_ browser.UserDataDir, _ browser.Profile) browser.Extractors { - extractors := make(browser.Extractors, len(defaultExtractors)) - for dataCategory, extractor := range defaultExtractors { - extractors[dataCategory] = extractor - } - return extractors +// Sources lists the files dataCategory is read from in any profile; Firefox may not support it. +func Sources(dataCategory category.Category) (sources []browser.Source, supported bool) { + extractor, ok := extractors[dataCategory] + return extractor.sources, ok } -func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor { - return browser.Extractor{ - Sources: []browser.Source{source}, - Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { - path, err := input.Path(source) +// Extract opens a protected profile's key store with primaryPassword, "" when the user gave none. +func Extract(captured browser.ProfileSnapshot, primaryPassword string, dataCategory category.Category, out browser.Collector) error { + extractor, ok := extractors[dataCategory] + if !ok { + return fmt.Errorf("%s has no %s extractor", captured.UserDataDir.Browser.Name, dataCategory) + } + return extractor.extract(captured, primaryPassword, out) +} + +func newPlainExtractor(extractFile func(string, browser.Collector) error, source browser.Source) extractor { + return extractor{ + sources: []browser.Source{source}, + extract: func(captured browser.ProfileSnapshot, _ string, out browser.Collector) error { + path, err := captured.Path(source) if err != nil { return err } - return parse(path, out) + return extractFile(path, out) }, } } // newDecryptingExtractor also captures key4.db, the profile's own key store. -func newDecryptingExtractor(parse func(func() ([]byte, error), string, browser.Collector) error, source browser.Source) browser.Extractor { - return browser.Extractor{ - Sources: []browser.Source{source, keyStore}, - Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { - path, err := input.Path(source) +func newDecryptingExtractor(extractFile func(func() ([]byte, error), string, browser.Collector) error, source browser.Source) extractor { + return extractor{ + sources: []browser.Source{source, keyStore}, + extract: func(captured browser.ProfileSnapshot, primaryPassword string, out browser.Collector) error { + path, err := captured.Path(source) if err != nil { return err } - masterKey := func() ([]byte, error) { return profileKey(input, path) } - return parse(masterKey, path, out) + masterKey := func() ([]byte, error) { return profileKey(captured, path, primaryPassword) } + return extractFile(masterKey, path, out) }, } } -func profileKey(input browser.Input, loginsPath string) ([]byte, error) { - key4Path, err := input.Path(keyStore) +func profileKey(captured browser.ProfileSnapshot, loginsPath, primaryPassword string) ([]byte, error) { + key4Path, err := captured.Path(keyStore) if err != nil { return nil, err } - return retrieveMasterKey(key4Path, loginsPath, []byte(input.FirefoxPrimaryPassword())) + return retrieveMasterKey(key4Path, loginsPath, []byte(primaryPassword)) } diff --git a/internal/browser/firefox/firefox_test.go b/internal/browser/firefox/firefox_test.go index 873d1e5..ac91e53 100644 --- a/internal/browser/firefox/firefox_test.go +++ b/internal/browser/firefox/firefox_test.go @@ -1,7 +1,6 @@ package firefox import ( - "context" "fmt" "io/fs" "os" @@ -107,7 +106,6 @@ func TestDiscover_ProfilePathWithoutDataFindsNothing(t *testing.T) { } func TestExtractors_CoverFirefoxCategories(t *testing.T) { - extractors := Extractors(browser.UserDataDir{Browser: testBrowser()}, browser.Profile{}) for _, dataCategory := range category.All() { extractor, ok := extractors[dataCategory] if dataCategory == category.CreditCard || dataCategory == category.SessionStorage { @@ -115,8 +113,8 @@ func TestExtractors_CoverFirefoxCategories(t *testing.T) { continue } if assert.Truef(t, ok, "no extractor for %s", dataCategory) { - assert.NotNil(t, extractor.Extract, dataCategory) - assert.NotEmpty(t, extractor.Sources, dataCategory) + assert.NotNil(t, extractor.extract, dataCategory) + assert.NotEmpty(t, extractor.sources, dataCategory) } } } @@ -126,11 +124,10 @@ func TestDecryptingExtractor_WithoutKeyStore(t *testing.T) { encodedLogin := loginPBEBase64(t) logins := createTestJSON(t, "logins.json", fmt.Sprintf(`{"logins": [{"hostname": "https://a.test", "encryptedUsername": %q, "encryptedPassword": %q, "timeCreated": 1700000000000}]}`, encodedLogin, encodedLogin)) - input := browser.NewInput(snapshotOf(t, map[string]string{"p/logins.json": logins}), - browser.Profile{Name: "p", RelativePath: "p"}, nil, nil) + captured := profileP(snapshotOf(t, map[string]string{"p/logins.json": logins})) var out testCollector - require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) + require.NoError(t, extractors[category.Password].extract(captured, "", &out)) got := collected[record.Login](t, &out) require.Len(t, got, 1) assert.Equal(t, "https://a.test", got[0].URL) @@ -142,13 +139,13 @@ func TestDecryptingExtractor_WithoutKeyStore(t *testing.T) { // TestPasswordExtractor_NoLoginsNeverReadsTheKey leaves key4.db unread without logins, so an unreadable one is harmless. func TestDecryptingExtractor_NoLoginsNeverReadsTheKey(t *testing.T) { - input := browser.NewInput(snapshotOf(t, map[string]string{ + captured := profileP(snapshotOf(t, map[string]string{ "p/logins.json": createTestJSON(t, "logins.json", `{"logins": []}`), "p/key4.db": createTestJSON(t, "key4.db", "not a database"), - }), browser.Profile{Name: "p", RelativePath: "p"}, nil, nil) + })) var out testCollector - require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out)) + require.NoError(t, extractors[category.Password].extract(captured, "", &out)) assert.Empty(t, out.records) assert.Empty(t, out.fails) } @@ -165,9 +162,13 @@ func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) { want := map[string]string{"a.default": "Home", "b.work": "Work"} for _, profile := range []browser.Profile{{Name: "a.default", RelativePath: "a.default"}, {Name: "b.work", RelativePath: "b.work"}} { var out testCollector - require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, nil), &out)) + require.NoError(t, Extract(browser.NewProfileSnapshot(dir, profile, dirSnapshot), "", category.History, &out)) got := collected[record.History](t, &out) require.Len(t, got, 1, profile.Name) assert.Equal(t, want[profile.Name], got[0].Title, profile.Name) } } + +func profileP(dirSnapshot snapshot.Snapshot) browser.ProfileSnapshot { + return browser.NewProfileSnapshot(browser.UserDataDir{Browser: testBrowser()}, browser.Profile{Name: "p", RelativePath: "p"}, dirSnapshot) +} diff --git a/internal/browser/safari/extract_password.go b/internal/browser/safari/extract_password.go index 51537d9..1f62394 100644 --- a/internal/browser/safari/extract_password.go +++ b/internal/browser/safari/extract_password.go @@ -10,8 +10,7 @@ import ( ) // extractPasswords reads no file, so it always runs; without a usable password the keychain yields metadata only. -func extractPasswords(ctx context.Context, input browser.Input, out browser.Collector) error { - loginKeychain := input.LoginKeychain() +func extractPasswords(ctx context.Context, _ browser.ProfileSnapshot, loginKeychain LoginKeychain, out browser.Collector) error { if loginKeychain == nil { return errNoKeychain } diff --git a/internal/browser/safari/safari.go b/internal/browser/safari/safari.go index dd56025..ab6fac6 100644 --- a/internal/browser/safari/safari.go +++ b/internal/browser/safari/safari.go @@ -13,6 +13,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/category" + "github.com/moond4rk/hackbrowserdata/internal/keychain" ) // Paths below are relative to the user data dir, ~/Library. @@ -57,51 +58,87 @@ func userDataDirPaths(safariBrowser browser.Browser, options browser.DiscoverOpt return paths } -// Extractors builds a named profile's sources from Profile.RelativePath; its files sit under two dirs named for its UUID. -// The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile reads them. -func Extractors(dir browser.UserDataDir, profile browser.Profile) browser.Extractors { - if uuid, named := namedProfileUUID(profile); named { - return namedProfileExtractors(dir, profile, uuid) - } - return defaultProfileExtractors(profile) +// LoginKeychain is what Safari's password extraction reads from the run's macOS login keychain. +type LoginKeychain interface { + InternetPasswords(ctx context.Context) ([]keychain.InternetPassword, error) } -func defaultProfileExtractors(profile browser.Profile) browser.Extractors { +// extractor is how one category is read: the files it needs, and how it parses them; passwords come from the keychain. +type extractor struct { + sources []browser.Source + extract func(ctx context.Context, captured browser.ProfileSnapshot, loginKeychain LoginKeychain, out browser.Collector) error +} + +// Sources lists the files dataCategory is read from in profile; a named profile supports fewer than the default one. +func Sources( + dir browser.UserDataDir, profile browser.Profile, dataCategory category.Category, +) (sources []browser.Source, supported bool) { + extractor, ok := profileExtractors(dir, profile)[dataCategory] + return extractor.sources, ok +} + +// Extract reads passwords from loginKeychain, which is nil off macOS; locked, it yields metadata only. +func Extract( + ctx context.Context, captured browser.ProfileSnapshot, loginKeychain LoginKeychain, dataCategory category.Category, out browser.Collector, +) error { + extractor, ok := profileExtractors(captured.UserDataDir, captured.Profile)[dataCategory] + if !ok { + return fmt.Errorf("%s profile %s has no %s extractor", captured.UserDataDir.Browser.Name, captured.Profile.Name, dataCategory) + } + return extractor.extract(ctx, captured, loginKeychain, out) +} + +// profileExtractors builds a named profile's sources from Profile.RelativePath; its files sit under two dirs named for +// its UUID. The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile +// reads them. +func profileExtractors(dir browser.UserDataDir, profile browser.Profile) map[category.Category]extractor { + if uuid, named := namedProfileUUID(profile); named { + return namedProfileExtractors(dir, uuid) + } + return defaultProfileExtractors() +} + +func defaultProfileExtractors() map[category.Category]extractor { var ( history = browser.Source{RelativePath: "History.db"} cookies = browser.Source{ - RelativePath: fromLibrary(profile, containerDir+"/Cookies/Cookies.binarycookies"), - Fallbacks: []string{fromLibrary(profile, "Cookies/Cookies.binarycookies")}, + RelativePath: containerDir + "/Cookies/Cookies.binarycookies", + Fallbacks: []string{"Cookies/Cookies.binarycookies"}, + FromUserDataDir: true, } bookmarks = browser.Source{RelativePath: "Bookmarks.plist"} downloads = browser.Source{RelativePath: "Downloads.plist"} - localStorage = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/WebKit/WebsiteData/Default"), IsDir: true} - appExtensions = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/Safari/AppExtensions/Extensions.plist"), Optional: true} - webExtensions = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/Safari/WebExtensions/Extensions.plist"), Optional: true} + localStorage = browser.Source{RelativePath: containerDir + "/WebKit/WebsiteData/Default", IsDir: true, FromUserDataDir: true} + appExtensions = browser.Source{ + RelativePath: containerDir + "/Safari/AppExtensions/Extensions.plist", FromUserDataDir: true, Optional: true, + } + webExtensions = browser.Source{ + RelativePath: containerDir + "/Safari/WebExtensions/Extensions.plist", FromUserDataDir: true, Optional: true, + } ) - return browser.Extractors{ - category.Password: {Extract: extractPasswords}, + return map[category.Category]extractor{ + category.Password: {extract: extractPasswords}, category.History: newPlainExtractor(extractHistories, history), category.Cookie: newPlainExtractor(extractCookies, cookies), category.Bookmark: newPlainExtractor(extractBookmarks, bookmarks), - category.Download: newPlainExtractor(downloadsOf(defaultProfileSentinel), downloads), + category.Download: newDownloadExtractor(downloads, defaultProfileSentinel), category.LocalStorage: newPlainExtractor(extractLocalStorage, localStorage), category.Extension: newExtensionExtractor(appExtensions, webExtensions), } } -func namedProfileExtractors(dir browser.UserDataDir, profile browser.Profile, uuid string) browser.Extractors { +func namedProfileExtractors(dir browser.UserDataDir, uuid string) map[category.Category]extractor { store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(uuid) var ( history = browser.Source{RelativePath: "History.db"} - cookies = browser.Source{RelativePath: fromLibrary(profile, store+"/Cookies/Cookies.binarycookies")} - downloads = browser.Source{RelativePath: fromLibrary(profile, defaultProfileDir(dir)+"/Downloads.plist")} - localStorage = browser.Source{RelativePath: fromLibrary(profile, store+"/Origins"), IsDir: true} + cookies = browser.Source{RelativePath: store + "/Cookies/Cookies.binarycookies", FromUserDataDir: true} + downloads = browser.Source{RelativePath: defaultProfileDir(dir) + "/Downloads.plist", FromUserDataDir: true} + localStorage = browser.Source{RelativePath: store + "/Origins", IsDir: true, FromUserDataDir: true} ) - return browser.Extractors{ + return map[category.Category]extractor{ category.History: newPlainExtractor(extractHistories, history), category.Cookie: newPlainExtractor(extractCookies, cookies), - category.Download: newPlainExtractor(downloadsOf(uuid), downloads), + category.Download: newDownloadExtractor(downloads, uuid), category.LocalStorage: newPlainExtractor(extractLocalStorage, localStorage), } } @@ -123,46 +160,41 @@ func defaultProfileDir(dir browser.UserDataDir) string { return "Safari" } -// fromLibrary turns a path under ~/Library into one relative to profile.RelativePath, which sources are joined with. -func fromLibrary(profile browser.Profile, relativePath string) string { - if profile.RelativePath == "" { - return relativePath - } - return strings.Repeat("../", strings.Count(profile.RelativePath, "/")+1) + relativePath -} - -func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor { - return browser.Extractor{ - Sources: []browser.Source{source}, - Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { - captured, err := input.Path(source) +func newPlainExtractor(extractFile func(string, browser.Collector) error, source browser.Source) extractor { + return extractor{ + sources: []browser.Source{source}, + extract: func(_ context.Context, captured browser.ProfileSnapshot, _ LoginKeychain, out browser.Collector) error { + capturedPath, err := captured.Path(source) if err != nil { return err } - return parse(captured, out) + return extractFile(capturedPath, out) }, } } -func downloadsOf(profileUUID string) func(string, browser.Collector) error { - return func(path string, out browser.Collector) error { return extractDownloads(path, profileUUID, out) } +// newDownloadExtractor keeps one profile's entries, because Downloads.plist holds every profile's. +func newDownloadExtractor(source browser.Source, profileUUID string) extractor { + return newPlainExtractor(func(path string, out browser.Collector) error { + return extractDownloads(path, profileUUID, out) + }, source) } // newExtensionExtractor merges every plist, so the extensions come out sorted across both stores. -func newExtensionExtractor(sources ...browser.Source) browser.Extractor { - return browser.Extractor{ - Sources: sources, - Extract: func(_ context.Context, input browser.Input, out browser.Collector) error { +func newExtensionExtractor(sources ...browser.Source) extractor { + return extractor{ + sources: sources, + extract: func(_ context.Context, captured browser.ProfileSnapshot, _ LoginKeychain, out browser.Collector) error { var paths []string for _, source := range sources { - captured, err := input.Path(source) + capturedPath, err := captured.Path(source) if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return err } - paths = append(paths, captured) + paths = append(paths, capturedPath) } return extractExtensions(paths, out) }, diff --git a/internal/browser/safari/safari_test.go b/internal/browser/safari/safari_test.go index cf47f0b..e7f4cb8 100644 --- a/internal/browser/safari/safari_test.go +++ b/internal/browser/safari/safari_test.go @@ -4,7 +4,6 @@ import ( "context" "errors" "os" - "path" "path/filepath" "strings" "testing" @@ -28,20 +27,18 @@ var ( libraryDir = browser.UserDataDir{Browser: testBrowser(), Profiles: []browser.Profile{defaultProfile, workProfile}} ) -func sourcePaths(profile browser.Profile, extractors browser.Extractors) map[category.Category][]string { - got := make(map[category.Category][]string, len(extractors)) - for dataCategory, extractor := range extractors { - for _, source := range extractor.Sources { - for _, relativePath := range source.RelativePaths() { - got[dataCategory] = append(got[dataCategory], path.Join(profile.RelativePath, relativePath)) - } +func sourcePaths(dir browser.UserDataDir, profile browser.Profile) map[category.Category][]string { + got := make(map[category.Category][]string) + for _, dataCategory := range category.All() { + sources, _ := Sources(dir, profile, dataCategory) + for _, source := range sources { + got[dataCategory] = append(got[dataCategory], source.DirRelativePaths(profile)...) } } return got } -func TestExtractors_DefaultProfileSources(t *testing.T) { - extractors := Extractors(libraryDir, defaultProfile) +func TestSources_DefaultProfile(t *testing.T) { assert.Equal(t, map[category.Category][]string{ category.History: {"Safari/History.db"}, category.Cookie: {containerDir + "/Cookies/Cookies.binarycookies", "Cookies/Cookies.binarycookies"}, @@ -54,22 +51,23 @@ func TestExtractors_DefaultProfileSources(t *testing.T) { containerDir + "/Safari/AppExtensions/Extensions.plist", containerDir + "/Safari/WebExtensions/Extensions.plist", }, - }, sourcePaths(defaultProfile, extractors)) - require.Contains(t, extractors, category.Password) - assert.Empty(t, extractors[category.Password].Sources, "passwords come from the keychain, not a file") + }, sourcePaths(libraryDir, defaultProfile)) + passwordSources, supported := Sources(libraryDir, defaultProfile, category.Password) + require.True(t, supported) + assert.Empty(t, passwordSources, "passwords come from the keychain, not a file") } -func TestExtractors_NamedProfileSources(t *testing.T) { +func TestSources_NamedProfile(t *testing.T) { store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(workUUID) assert.Equal(t, map[category.Category][]string{ category.History: {namedProfilesDir + "/" + workUUID + "/History.db"}, category.Cookie: {store + "/Cookies/Cookies.binarycookies"}, category.Download: {"Safari/Downloads.plist"}, category.LocalStorage: {store + "/Origins"}, - }, sourcePaths(workProfile, Extractors(libraryDir, workProfile))) + }, sourcePaths(libraryDir, workProfile)) copied := browser.UserDataDir{Profiles: []browser.Profile{{Name: "default", RelativePath: "SafariCopy"}, workProfile}} - assert.Equal(t, []string{"SafariCopy/Downloads.plist"}, sourcePaths(workProfile, Extractors(copied, workProfile))[category.Download], + assert.Equal(t, []string{"SafariCopy/Downloads.plist"}, sourcePaths(copied, workProfile)[category.Download], "a named profile's downloads sit in the default profile's dir, whatever -p named it") } @@ -96,12 +94,12 @@ func writeTestPlist(t *testing.T, value any) string { return plistPath } -func extract(t *testing.T, dirSnapshot snapshot.Snapshot, profile browser.Profile, loginKeychain browser.LoginKeychain, dataCategory category.Category) (*testCollector, error) { +func extract(t *testing.T, dirSnapshot snapshot.Snapshot, profile browser.Profile, loginKeychain LoginKeychain, dataCategory category.Category) (*testCollector, error) { t.Helper() - extractor, ok := Extractors(libraryDir, profile)[dataCategory] - require.Truef(t, ok, "no %s extractor for %s", dataCategory, profile.Name) + _, supported := Sources(libraryDir, profile, dataCategory) + require.Truef(t, supported, "no %s extractor for %s", dataCategory, profile.Name) var out testCollector - err := extractor.Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, loginKeychain), &out) + err := Extract(context.Background(), browser.NewProfileSnapshot(libraryDir, profile, dirSnapshot), loginKeychain, dataCategory, &out) return &out, err } @@ -179,10 +177,10 @@ func TestExtractors_PasswordsWithoutAKeychain(t *testing.T) { require.ErrorIs(t, err, broken) } -// TestExtractors_NamedProfileSkipsUserWideSources leaves the keychain and the untagged plists to the default profile. -func TestExtractors_NamedProfileSkipsUserWideSources(t *testing.T) { - extractors := Extractors(libraryDir, workProfile) +// TestSources_NamedProfileSkipsUserWideSources leaves the keychain and the untagged plists to the default profile. +func TestSources_NamedProfileSkipsUserWideSources(t *testing.T) { for _, dataCategory := range []category.Category{category.Password, category.Bookmark, category.Extension} { - assert.NotContains(t, extractors, dataCategory) + _, supported := Sources(libraryDir, workProfile, dataCategory) + assert.False(t, supported, dataCategory) } } diff --git a/internal/export/order.go b/internal/export/order.go index 36e00ac..c26ca8c 100644 --- a/internal/export/order.go +++ b/internal/export/order.go @@ -10,7 +10,7 @@ import ( // sortRecords is stable, so ties and keyless records keep source order: Safari bookmarks and downloads lack a time. func sortRecords(records []record.Record) { sort.SliceStable(records, func(i, j int) bool { - return sortKeyOf(records[i]).before(sortKeyOf(records[j])) + return newSortKey(records[i]).before(newSortKey(records[j])) }) } @@ -19,7 +19,7 @@ type sortKey struct { timestamp time.Time } -func sortKeyOf(row record.Record) sortKey { +func newSortKey(row record.Record) sortKey { switch typed := row.(type) { case *record.Login: return sortKey{timestamp: typed.CreatedAt}