diff --git a/.golangci.yml b/.golangci.yml index 12bab05..a562d4b 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -52,6 +52,7 @@ linters: - unconvert - unparam - usestdlibvars + - varnamelen - wastedassign - whitespace @@ -159,6 +160,15 @@ linters: rules: json: snake csv: snake + varnamelen: + # 1 is the strictest the linter allows: it only spares a name used on the line after its declaration. + max-distance: 1 + ignore-names: [i, j, ok, id, iv] + ignore-decls: + - t *testing.T + - b *testing.B + - t testing.TB + - tb testing.TB staticcheck: checks: - "all" @@ -167,11 +177,14 @@ linters: exclusions: presets: - - comments - std-error-handling - common-false-positives - legacy rules: + # The Windows API and ABE packages keep their short names until they get their own pass. + - path: internal/(winapi|abe)/|internal/masterkey/(abe_windows|gcoredump_darwin)\.go + linters: + - varnamelen - path: _test\.go linters: - dupl diff --git a/CLAUDE.md b/CLAUDE.md index 1367ffb..0c94cd1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,8 +59,8 @@ make payload-clean # rm internal/abe/payload/*.bin - **C payload**: all sources in `internal/abe/native/` are first-party (no vendored C). See RFC-016 §9.2 for why Stephen Fewer's reflective loader was rejected. - **Error handling**: `fmt.Errorf("context: %w", err)` for wrapping, never `_ =` to ignore errors - **Logging**: `log.Debugf` for record-level diagnostics, `log.Infof` for user-facing progress/status, `log.Warnf` for unexpected conditions. Extract methods should return errors, not log them. -- **Naming**: follow Go conventions and the settled names in `rfcs/004-naming-decisions.md` — `Def` not `BrowserConfig`, `Extract` not `BrowsingData` -- **Comments**: none by default; when one is needed, one line of at most 120 characters that says why, never what the code does (up to 3 lines only when the reason cannot fit) +- **Naming**: follow Go conventions and the settled names in `rfcs/004-naming-decisions.md` — `browser.Browser` not `BrowserConfig`, `Extract` not `BrowsingData`; spell names out (`extractors`, `snapshotDir`, `profile`), leaving only `i`/`j`, `err`, `ctx`, `ok`, `t`/`tb`, `id`, `iv`, and one-letter receivers short (`varnamelen` enforces it) +- **Comments**: none by default; when one is needed, one line of at most 120 characters that says why, never what the code does (up to 3 lines only when the reason cannot fit); a comment on a declaration starts with its name (`// AssertJSONFallback checks …`) - **Tests**: `internal/browser/browsertest` builds real fixture files (SQLite, JSON, LevelDB, plist) into a `t.TempDir()` — never a live browser, never a database mock; goldens live in each package's `testdata/` and `HBD_UPDATE_GOLDEN=1 go test ./...` regenerates them - **Architecture**: see `rfcs/README.md` — design RFCs 000–011, format and technique RFCs 013–021 diff --git a/cmd/hack-browser-data/archive.go b/cmd/hack-browser-data/archive.go index 2ca40f6..278dacd 100644 --- a/cmd/hack-browser-data/archive.go +++ b/cmd/hack-browser-data/archive.go @@ -9,37 +9,37 @@ import ( func archiveCmd() *cobra.Command { var ( - f app.Flags + flags app.Flags outputPath string ) - cmd := &cobra.Command{ + command := &cobra.Command{ Use: "archive", Short: "Pack decryption-relevant profile files into a zip for cross-host restore", Example: ` hack-browser-data archive hack-browser-data archive -b chrome -c cookie -o chrome-cookies.zip`, - RunE: func(cmd *cobra.Command, args []string) error { - req, err := app.ValidateArchive(f) + RunE: func(command *cobra.Command, args []string) error { + options, err := app.ValidateArchive(flags) if err != nil { return err } - d := app.Discover(req) - if len(d.Dirs) == 0 { + discovery := app.Discover(options) + if len(discovery.Dirs) == 0 { log.Warnf("no browsers found") return nil } - n, err := app.Archive(cmd.Context(), d, req, outputPath) + fileCount, err := app.Archive(command.Context(), discovery, options, outputPath) if err != nil { return err } - log.Infof("Archived %d entries to %s", n, outputPath) + log.Infof("Archived %d entries to %s", fileCount, outputPath) return nil }, } - cmd.Flags().StringVarP(&f.Browser, "browser", "b", "all", "target browser: all|"+browserNames()) - cmd.Flags().StringVarP(&f.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames()) - cmd.Flags().StringVarP(&outputPath, "output", "o", "browser-data.zip", "output archive of decryption-relevant browser files") + command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames()) + command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames()) + command.Flags().StringVarP(&outputPath, "output", "o", "browser-data.zip", "output archive of decryption-relevant browser files") - return cmd + return command } diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index b1b4f43..8e6cb70 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -11,9 +11,9 @@ import ( ) func dumpCmd() *cobra.Command { - var f app.Flags + var flags app.Flags - cmd := &cobra.Command{ + command := &cobra.Command{ Use: "dump", Short: "Extract and decrypt browser data (default command)", Example: ` hack-browser-data dump @@ -21,42 +21,43 @@ func dumpCmd() *cobra.Command { hack-browser-data dump -b chrome -f json -d output hack-browser-data dump -f cookie-editor hack-browser-data dump --zip`, - RunE: func(cmd *cobra.Command, args []string) error { - return runDump(cmd.Context(), cmd.ErrOrStderr(), f) + RunE: func(command *cobra.Command, args []string) error { + return runDump(command.Context(), command.ErrOrStderr(), flags) }, } - cmd.Flags().StringVarP(&f.Browser, "browser", "b", "all", "target browser: all|"+browserNames()) - cmd.Flags().StringVarP(&f.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames()) - cmd.Flags().StringVarP(&f.Format, "format", "f", "json", "output format: csv|json|cookie-editor") - cmd.Flags().StringVarP(&f.Dir, "dir", "d", "results", "output directory") - cmd.Flags().StringVarP(&f.ProfilePath, "profile-path", "p", "", "custom profile dir path, get with chrome://version") - keychainPasswordFlags(cmd, &f) - cmd.Flags().BoolVar(&f.Zip, "zip", false, "compress output to zip") + command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames()) + command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames()) + command.Flags().StringVarP(&flags.Format, "format", "f", "json", "output format: csv|json|cookie-editor") + command.Flags().StringVarP(&flags.Dir, "dir", "d", "results", "output directory") + command.Flags().StringVarP(&flags.ProfilePath, "profile-path", "p", "", "custom profile dir path, get with chrome://version") + keychainPasswordFlags(command, &flags) + command.Flags().BoolVar(&flags.Zip, "zip", false, "compress output to zip") - return cmd + return command } -func keychainPasswordFlags(cmd *cobra.Command, f *app.Flags) { - cmd.Flags().StringVar(&f.KeychainPassword, "keychain-pw", "", "macOS keychain password (visible in ps and shell history)") - cmd.Flags().BoolVar(&f.KeychainPasswordStdin, "keychain-pw-stdin", false, "read the macOS keychain password from the first line of stdin") - cmd.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin") +func keychainPasswordFlags(command *cobra.Command, flags *app.Flags) { + command.Flags().StringVar(&flags.KeychainPassword, "keychain-pw", "", "macOS keychain password (visible in ps and shell history)") + command.Flags().BoolVar(&flags.KeychainPasswordStdin, "keychain-pw-stdin", false, + "read the macOS keychain password from the first line of stdin") + command.MarkFlagsMutuallyExclusive("keychain-pw", "keychain-pw-stdin") } -func runDump(ctx context.Context, stderr io.Writer, f app.Flags) error { - req, err := app.Validate(f) +func runDump(ctx context.Context, stderr io.Writer, flags app.Flags) error { + options, err := app.Validate(flags) if err != nil { return err } - d := app.Discover(req) - if len(d.Dirs) == 0 { - if len(d.Failed) > 0 { - report(stderr, app.Summary{Results: d.Failed}) + discovery := app.Discover(options) + if len(discovery.Dirs) == 0 { + if len(discovery.Failed) > 0 { + report(stderr, app.Summary{Results: discovery.Failed}) } log.Warnf("no browsers found") return nil } - summary, err := app.Execute(ctx, app.NewPlan(d, req), req) + summary, err := app.Execute(ctx, app.NewPlan(discovery, options), options) if ctx.Err() == nil { report(stderr, summary) } diff --git a/cmd/hack-browser-data/dumpkeys.go b/cmd/hack-browser-data/dumpkeys.go index 468b102..8700189 100644 --- a/cmd/hack-browser-data/dumpkeys.go +++ b/cmd/hack-browser-data/dumpkeys.go @@ -13,21 +13,21 @@ import ( func dumpKeysCmd() *cobra.Command { var ( - f app.Flags + flags app.Flags outputPath string ) - cmd := &cobra.Command{ + command := &cobra.Command{ Use: "dumpkeys", Short: "Export Chromium master keys as JSON for cross-host decryption", Example: ` hack-browser-data dumpkeys -o keys.json hack-browser-data dumpkeys -b chrome`, - RunE: func(cmd *cobra.Command, args []string) error { - req, err := app.ValidateKeys(f) + RunE: func(command *cobra.Command, args []string) error { + options, err := app.ValidateKeys(flags) if err != nil { return err } - dump, err := app.DumpKeys(cmd.Context(), app.Discover(req), req) + dump, err := app.DumpKeys(command.Context(), app.Discover(options), options) if err != nil { return err } @@ -44,9 +44,9 @@ func dumpKeysCmd() *cobra.Command { }, } - cmd.Flags().StringVarP(&f.Browser, "browser", "b", "all", "target browser: all|"+browserNames()) - cmd.Flags().StringVarP(&outputPath, "output", "o", "", "output file (default: stdout)") - keychainPasswordFlags(cmd, &f) + command.Flags().StringVarP(&flags.Browser, "browser", "b", "all", "target browser: all|"+browserNames()) + command.Flags().StringVarP(&outputPath, "output", "o", "", "output file (default: stdout)") + keychainPasswordFlags(command, &flags) - return cmd + return command } diff --git a/cmd/hack-browser-data/flags_test.go b/cmd/hack-browser-data/flags_test.go index 9b5a1e6..0f73a7f 100644 --- a/cmd/hack-browser-data/flags_test.go +++ b/cmd/hack-browser-data/flags_test.go @@ -18,46 +18,46 @@ func TestFlagSurface(t *testing.T) { func flagSurface(root *cobra.Command) string { var lines []string - for _, cmd := range sortedCommands(root) { - cmd.InitDefaultHelpFlag() - path := cmd.CommandPath() - for _, f := range sortedFlags(cmd.LocalFlags()) { + for _, command := range sortedCommands(root) { + command.InitDefaultHelpFlag() + path := command.CommandPath() + for _, flag := range sortedFlags(command.LocalFlags()) { marker := "" - if cmd.PersistentFlags().Lookup(f.Name) == f { + if command.PersistentFlags().Lookup(flag.Name) == flag { marker = "persistent" } - lines = append(lines, flagLine(path, f, marker)) + lines = append(lines, flagLine(path, flag, marker)) } - for _, f := range sortedFlags(cmd.InheritedFlags()) { - lines = append(lines, flagLine(path, f, "inherited")) + for _, flag := range sortedFlags(command.InheritedFlags()) { + lines = append(lines, flagLine(path, flag, "inherited")) } } return strings.Join(lines, "\n") + "\n" } func sortedCommands(root *cobra.Command) []*cobra.Command { - cmds := []*cobra.Command{root} - for i := 0; i < len(cmds); i++ { - cmds = append(cmds, cmds[i].Commands()...) + commands := []*cobra.Command{root} + for i := 0; i < len(commands); i++ { + commands = append(commands, commands[i].Commands()...) } - sort.Slice(cmds, func(i, j int) bool { return cmds[i].CommandPath() < cmds[j].CommandPath() }) - return cmds + sort.Slice(commands, func(i, j int) bool { return commands[i].CommandPath() < commands[j].CommandPath() }) + return commands } -func sortedFlags(fs *pflag.FlagSet) []*pflag.Flag { +func sortedFlags(flagSet *pflag.FlagSet) []*pflag.Flag { var flags []*pflag.Flag - fs.VisitAll(func(f *pflag.Flag) { flags = append(flags, f) }) + flagSet.VisitAll(func(flag *pflag.Flag) { flags = append(flags, flag) }) sort.Slice(flags, func(i, j int) bool { return flags[i].Name < flags[j].Name }) return flags } -func flagLine(path string, f *pflag.Flag, marker string) string { +func flagLine(path string, flag *pflag.Flag, marker string) string { // Usage text is excluded: its wording may still be clarified, while name, shorthand, type and default are frozen. - fields := []string{path, "--" + f.Name} - if f.Shorthand != "" { - fields = append(fields, "-"+f.Shorthand) + fields := []string{path, "--" + flag.Name} + if flag.Shorthand != "" { + fields = append(fields, "-"+flag.Shorthand) } - fields = append(fields, f.Value.Type(), strconv.Quote(f.DefValue)) + fields = append(fields, flag.Value.Type(), strconv.Quote(flag.DefValue)) if marker != "" { fields = append(fields, marker) } diff --git a/cmd/hack-browser-data/helpers_test.go b/cmd/hack-browser-data/helpers_test.go index 8eeeebc..1728414 100644 --- a/cmd/hack-browser-data/helpers_test.go +++ b/cmd/hack-browser-data/helpers_test.go @@ -7,15 +7,15 @@ import ( "github.com/stretchr/testify/require" ) -// Windows reads USERPROFILE rather than HOME, so both point at the fixture. +// setHome sets USERPROFILE too, because Windows reads it rather than HOME. func setHome(t *testing.T, home string) { t.Helper() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) } -func runCmd(t *testing.T, cmd *cobra.Command, args ...string) { +func runCmd(t *testing.T, command *cobra.Command, args ...string) { t.Helper() - cmd.SetArgs(args) - require.NoError(t, cmd.Execute()) + command.SetArgs(args) + require.NoError(t, command.Execute()) } diff --git a/cmd/hack-browser-data/list.go b/cmd/hack-browser-data/list.go index 44f2ff0..cb071cc 100644 --- a/cmd/hack-browser-data/list.go +++ b/cmd/hack-browser-data/list.go @@ -16,70 +16,70 @@ import ( func listCmd() *cobra.Command { var detail bool - cmd := &cobra.Command{ + command := &cobra.Command{ Use: "list", Short: "List detected browsers and profiles", Example: ` hack-browser-data list hack-browser-data list --detail`, - RunE: func(cmd *cobra.Command, args []string) error { - req, err := app.ListRequest() + RunE: func(command *cobra.Command, args []string) error { + options, err := app.ListOptions() if err != nil { return err } - d := app.Discover(req) - for _, r := range d.Failed { - log.Warnf("%s: %v", r.DirID, r.Err) + discovery := app.Discover(options) + for _, result := range discovery.Failed { + log.Warnf("%s: %v", result.UserDataDirID, result.Err) } - if len(d.Dirs) == 0 { - cmd.Println("No browsers found.") + if len(discovery.Dirs) == 0 { + command.Println("No browsers found.") return nil } if !detail { - return printBasic(cmd.OutOrStdout(), d) + return printBasic(command.OutOrStdout(), discovery) } - summary, err := app.Count(cmd.Context(), app.NewPlan(d, req), req) + summary, err := app.Count(command.Context(), app.NewPlan(discovery, options), options) if err != nil { return err } - return printDetail(cmd.OutOrStdout(), d, summary) + return printDetail(command.OutOrStdout(), discovery, summary) }, } - cmd.Flags().BoolVar(&detail, "detail", false, "show per-category entry counts") - return cmd + command.Flags().BoolVar(&detail, "detail", false, "show per-category entry counts") + return command } -func printBasic(out io.Writer, d app.Discovery) error { - w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) - fmt.Fprintln(w, "Browser\tProfile\tPath") - for _, dir := range d.Dirs { - for _, p := range dir.Profiles { - fmt.Fprintf(w, "%s\t%s\t%s\n", dir.Def.Name, p.Name, filepath.Join(dir.Path, filepath.FromSlash(p.Dir))) +func printBasic(out io.Writer, discovery app.Discovery) error { + table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) + fmt.Fprintln(table, "Browser\tProfile\tPath") + for _, dir := range discovery.Dirs { + for _, profile := range dir.Profiles { + fmt.Fprintf(table, "%s\t%s\t%s\n", dir.Browser.DisplayName, profile.Name, filepath.Join(dir.Path, filepath.FromSlash(profile.Dir))) } } - return w.Flush() + return table.Flush() } -func printDetail(out io.Writer, d app.Discovery, s app.Summary) error { - counts := make(map[app.Extraction]int, len(s.Results)) - for _, r := range s.Results { - counts[r.Extraction] = r.Count +func printDetail(out io.Writer, discovery app.Discovery, summary app.Summary) error { + counts := make(map[app.Extraction]int, len(summary.Results)) + for _, result := range summary.Results { + counts[result.Extraction] = result.Count } - w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) - fmt.Fprint(w, "Browser\tProfile") - for _, c := range category.All() { - fmt.Fprintf(w, "\t%s", c.String()) + table := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) + fmt.Fprint(table, "Browser\tProfile") + for _, dataCategory := range category.All() { + fmt.Fprintf(table, "\t%s", dataCategory.String()) } - fmt.Fprintln(w) - for _, dir := range d.Dirs { - for _, p := range dir.Profiles { - fmt.Fprintf(w, "%s\t%s", dir.Def.Name, p.Name) - for _, c := range category.All() { - fmt.Fprintf(w, "\t%d", counts[app.Extraction{DirID: dir.ID, Profile: p.Name, Category: c}]) + fmt.Fprintln(table) + for _, dir := range discovery.Dirs { + 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, Profile: profile.Name, Category: dataCategory}]) } - fmt.Fprintln(w) + fmt.Fprintln(table) } } - return w.Flush() + return table.Flush() } diff --git a/cmd/hack-browser-data/list_test.go b/cmd/hack-browser-data/list_test.go index eec250a..3543d16 100644 --- a/cmd/hack-browser-data/list_test.go +++ b/cmd/hack-browser-data/list_test.go @@ -18,10 +18,10 @@ func TestListGolden(t *testing.T) { home := t.TempDir() setHome(t, home) var paths []string - for _, inst := range browsertest.ChromiumInstalls { - dir := userDataDirOf(t, home, inst.Key) - browsertest.ChromiumUserData(t, dir, inst.Key) - paths = append(paths, dir, "<"+inst.Key+">") + for _, fixture := range browsertest.ChromiumInstalls { + dir := userDataDirOf(t, home, fixture.Name) + browsertest.ChromiumUserData(t, dir, fixture.Name) + paths = append(paths, dir, "<"+fixture.Name+">") } dir := userDataDirOf(t, home, "firefox") browsertest.FirefoxUserData(t, dir) @@ -40,25 +40,25 @@ func TestListGoldenSafari(t *testing.T) { assertListGoldens(t, "list-safari", strings.NewReplacer(library, "")) } -// The goldens hold the fixture's paths as placeholders, so one golden serves every OS. +// assertListGoldens compares with the fixture's paths as placeholders, so one golden serves every OS. func assertListGoldens(t *testing.T, prefix string, paths *strings.Replacer) { t.Helper() for _, detail := range []bool{false, true} { var out bytes.Buffer - cmd := listCmd() - cmd.SetOut(&out) + command := listCmd() + command.SetOut(&out) name, args := prefix+".golden", []string{} if detail { name, args = prefix+"-detail.golden", []string{"--detail"} } - runCmd(t, cmd, args...) + runCmd(t, command, args...) golden.Assert(t, name, paths.Replace(out.String())) } } -func userDataDirOf(t *testing.T, home, id string) string { +func userDataDirOf(t *testing.T, home, browserName string) string { t.Helper() - def, ok := browser.Lookup(id) - require.True(t, ok, id) - return filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])) + namedBrowser, ok := browser.Lookup(browserName) + require.True(t, ok, browserName) + return filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])) } diff --git a/cmd/hack-browser-data/main.go b/cmd/hack-browser-data/main.go index ed46e68..7c6b0bc 100644 --- a/cmd/hack-browser-data/main.go +++ b/cmd/hack-browser-data/main.go @@ -22,7 +22,7 @@ func rootCmd() *cobra.Command { browsers, Firefox, and Safari on Windows, macOS, and Linux. GitHub: https://github.com/moonD4rk/HackBrowserData`, - PersistentPreRun: func(cmd *cobra.Command, args []string) { + PersistentPreRun: func(command *cobra.Command, args []string) { if verbose { log.SetVerbose() } @@ -37,33 +37,33 @@ GitHub: https://github.com/moonD4rk/HackBrowserData`, root.AddCommand(dump, dumpKeysCmd(), archiveCmd(), restoreCmd(), listCmd(), versionCmd()) // Without a subcommand the root runs dump, as v1.1.0 did, so it carries dump's flags too. - root.RunE = func(cmd *cobra.Command, args []string) error { - dump.SetContext(cmd.Context()) + root.RunE = func(command *cobra.Command, args []string) error { + dump.SetContext(command.Context()) return dump.RunE(dump, args) } - dump.Flags().VisitAll(func(f *pflag.Flag) { - if root.Flags().Lookup(f.Name) == nil { - root.Flags().AddFlag(f) + dump.Flags().VisitAll(func(flag *pflag.Flag) { + if root.Flags().Lookup(flag.Name) == nil { + root.Flags().AddFlag(flag) } }) - for _, c := range root.Commands() { - quietWhenStopped(c) + for _, command := range root.Commands() { + quietWhenStopped(command) } quietWhenStopped(root) return root } // quietWhenStopped keeps a stopped run's error and usage off the screen; main then ends the process by the signal. -func quietWhenStopped(c *cobra.Command) { - run := c.RunE +func quietWhenStopped(command *cobra.Command) { + run := command.RunE if run == nil { return } - c.RunE = func(cmd *cobra.Command, args []string) error { - err := run(cmd, args) - if err != nil && cmd.Context().Err() != nil { - cmd.SilenceErrors, cmd.SilenceUsage = true, true + command.RunE = func(invoked *cobra.Command, args []string) error { + err := run(invoked, args) + if err != nil && invoked.Context().Err() != nil { + invoked.SilenceErrors, invoked.SilenceUsage = true, true } return err } @@ -72,33 +72,33 @@ func quietWhenStopped(c *cobra.Command) { // stopSignals end the process by default; each first cancels the run, so its temporary copies are removed. var stopSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP} -type stopError struct{ sig os.Signal } +type stopError struct{ received os.Signal } -func (e stopError) Error() string { return "stopped by " + e.sig.String() } +func (e stopError) Error() string { return "stopped by " + e.received.String() } func main() { configureDoubleClickMode() ctx, cancel := context.WithCancelCause(context.Background()) signals := make(chan os.Signal, 1) - for _, sig := range stopSignals { - if !signal.Ignored(sig) { // nohup and background jobs keep ignoring what they ignore today - signal.Notify(signals, sig) + for _, received := range stopSignals { + if !signal.Ignored(received) { // nohup and background jobs keep ignoring what they ignore today + signal.Notify(signals, received) } } go func() { - sig := <-signals + received := <-signals signal.Stop(signals) // a second signal ends the process at once - if sig == os.Interrupt { + if received == os.Interrupt { log.Warnf("Interrupted; cleaning up (press Ctrl-C again to quit at once)") } else { log.Warnf("Stopping; cleaning up") } - cancel(stopError{sig}) + cancel(stopError{received}) }() err := rootCmd().ExecuteContext(ctx) var stop stopError if errors.As(context.Cause(ctx), &stop) { - exitBy(stop.sig) + exitBy(stop.received) } if err != nil { os.Exit(1) diff --git a/cmd/hack-browser-data/main_others.go b/cmd/hack-browser-data/main_others.go index c60c4aa..880c21d 100644 --- a/cmd/hack-browser-data/main_others.go +++ b/cmd/hack-browser-data/main_others.go @@ -12,9 +12,9 @@ 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. -func exitBy(sig os.Signal) { - signal.Reset(sig) - if s, ok := sig.(syscall.Signal); ok && syscall.Kill(syscall.Getpid(), s) == nil { +func exitBy(received os.Signal) { + signal.Reset(received) + if syscallSignal, ok := received.(syscall.Signal); ok && syscall.Kill(syscall.Getpid(), syscallSignal) == nil { time.Sleep(time.Second) // the signal ends the process first unless it was ignored at start } os.Exit(1) diff --git a/cmd/hack-browser-data/main_others_test.go b/cmd/hack-browser-data/main_others_test.go index 577ac82..7cd08e5 100644 --- a/cmd/hack-browser-data/main_others_test.go +++ b/cmd/hack-browser-data/main_others_test.go @@ -11,9 +11,9 @@ import ( "github.com/stretchr/testify/require" ) -func assertEndedByInterrupt(t *testing.T, ps *os.ProcessState) { +func assertEndedByInterrupt(t *testing.T, state *os.ProcessState) { t.Helper() - status, ok := ps.Sys().(syscall.WaitStatus) + status, ok := state.Sys().(syscall.WaitStatus) require.True(t, ok) assert.True(t, status.Signaled(), "ended by the signal, not by an exit code") assert.Equal(t, syscall.SIGINT, status.Signal()) diff --git a/cmd/hack-browser-data/main_test.go b/cmd/hack-browser-data/main_test.go index 3978a2a..4bdbb2a 100644 --- a/cmd/hack-browser-data/main_test.go +++ b/cmd/hack-browser-data/main_test.go @@ -19,29 +19,29 @@ func TestStoppedRunPrintsNoErrorOrUsage(t *testing.T) { setHome(t, home) browsertest.ChromiumUserData(t, userDataDirOf(t, home, "chrome"), "chrome") - for _, tc := range []struct { + for _, testCase := range []struct { name, browser string stop bool }{ {name: "stopped", browser: "chrome", stop: true}, {name: "failed", browser: "nosuch"}, } { - tc := tc - t.Run(tc.name, func(t *testing.T) { + testCase := testCase + t.Run(testCase.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - if tc.stop { + if testCase.stop { cancel() } var screen bytes.Buffer root := rootCmd() root.SetOut(&screen) root.SetErr(&screen) - root.SetArgs([]string{"-b", tc.browser, "-d", filepath.Join(t.TempDir(), "results")}) + root.SetArgs([]string{"-b", testCase.browser, "-d", filepath.Join(t.TempDir(), "results")}) err := root.ExecuteContext(ctx) require.Error(t, err) - if tc.stop { + if testCase.stop { require.ErrorIs(t, err, context.Canceled) assert.Empty(t, screen.String()) } else { @@ -56,9 +56,9 @@ func TestExitByEndsTheProcessAsTheSignalWould(t *testing.T) { exitBy(os.Interrupt) return } - cmd := exec.Command(os.Args[0], "-test.run=^TestExitByEndsTheProcessAsTheSignalWould$") - cmd.Env = append(os.Environ(), "HBD_TEST_EXIT_BY=1") + command := exec.Command(os.Args[0], "-test.run=^TestExitByEndsTheProcessAsTheSignalWould$") + command.Env = append(os.Environ(), "HBD_TEST_EXIT_BY=1") var exitErr *exec.ExitError - require.ErrorAs(t, cmd.Run(), &exitErr) + require.ErrorAs(t, command.Run(), &exitErr) assertEndedByInterrupt(t, exitErr.ProcessState) } diff --git a/cmd/hack-browser-data/main_windows_test.go b/cmd/hack-browser-data/main_windows_test.go index 91a7e83..2cc4590 100644 --- a/cmd/hack-browser-data/main_windows_test.go +++ b/cmd/hack-browser-data/main_windows_test.go @@ -10,7 +10,7 @@ import ( "golang.org/x/sys/windows" ) -func assertEndedByInterrupt(t *testing.T, ps *os.ProcessState) { +func assertEndedByInterrupt(t *testing.T, state *os.ProcessState) { t.Helper() - assert.Equal(t, uint32(windows.STATUS_CONTROL_C_EXIT), uint32(ps.ExitCode())) + assert.Equal(t, uint32(windows.STATUS_CONTROL_C_EXIT), uint32(state.ExitCode())) } diff --git a/cmd/hack-browser-data/names.go b/cmd/hack-browser-data/names.go index 1c513c2..2b78f8f 100644 --- a/cmd/hack-browser-data/names.go +++ b/cmd/hack-browser-data/names.go @@ -11,7 +11,7 @@ import ( ) func browserNames() string { - return strings.Join(browser.IDs(), "|") + return strings.Join(browser.Names(), "|") } func categoryNames() string { @@ -19,8 +19,8 @@ func categoryNames() string { } // report prints the run's summary; it is not part of the output, so failing to print it never fails the run. -func report(w io.Writer, s app.Summary) { - if err := app.Report(w, s); err != nil { +func report(writer io.Writer, summary app.Summary) { + if err := app.Report(writer, summary); err != nil { log.Warnf("print summary: %v", err) } } diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index 7324912..852a730 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -13,56 +13,56 @@ import ( ) func restoreCmd() *cobra.Command { - var f app.RestoreFlags + var flags app.RestoreFlags - cmd := &cobra.Command{ + command := &cobra.Command{ Use: "restore", Short: "Decrypt copied profile data using exported master keys", Example: ` hack-browser-data restore --keys keys.json --data-zip data.zip hack-browser-data restore --keys keys.json --data-dir ./data -b chrome -c cookie hack-browser-data restore --keys keys.json --data-dir ./chrome-userdata -b chrome ssh origin "hack-browser-data dumpkeys" | hack-browser-data restore --keys - --data-zip data.zip`, - RunE: func(cmd *cobra.Command, args []string) error { - return runRestore(cmd.Context(), cmd.ErrOrStderr(), f) + RunE: func(command *cobra.Command, args []string) error { + return runRestore(command.Context(), command.ErrOrStderr(), flags) }, } - cmd.Flags().StringVar(&f.Keys, "keys", "", "keys file from dumpkeys (use - for stdin)") - cmd.Flags().StringVar(&f.DataDir, "data-dir", "", "copied profile data dir (archive layout, or one browser's User Data with -b)") - cmd.Flags().StringVar(&f.DataZip, "data-zip", "", "zip produced by the archive command (alternative to --data-dir)") - cmd.Flags().StringVarP(&f.Browser, "browser", "b", "", "restore only this browser (optional; must match a vault in --keys)") - cmd.Flags().StringVarP(&f.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames()) - cmd.Flags().StringVarP(&f.Format, "format", "f", "json", "output format: csv|json|cookie-editor") - cmd.Flags().StringVarP(&f.Dir, "dir", "d", "results", "output directory") - cmd.Flags().BoolVar(&f.Zip, "zip", false, "compress output to zip") + command.Flags().StringVar(&flags.Keys, "keys", "", "keys file from dumpkeys (use - for stdin)") + command.Flags().StringVar(&flags.DataDir, "data-dir", "", "copied profile data dir (archive layout, or one browser's User Data with -b)") + command.Flags().StringVar(&flags.DataZip, "data-zip", "", "zip produced by the archive command (alternative to --data-dir)") + command.Flags().StringVarP(&flags.Browser, "browser", "b", "", "restore only this browser (optional; must match a vault in --keys)") + command.Flags().StringVarP(&flags.Categories, "category", "c", "all", "data categories (comma-separated): all|"+categoryNames()) + command.Flags().StringVarP(&flags.Format, "format", "f", "json", "output format: csv|json|cookie-editor") + command.Flags().StringVarP(&flags.Dir, "dir", "d", "results", "output directory") + command.Flags().BoolVar(&flags.Zip, "zip", false, "compress output to zip") - _ = cmd.MarkFlagRequired("keys") - cmd.MarkFlagsMutuallyExclusive("data-dir", "data-zip") + _ = command.MarkFlagRequired("keys") + command.MarkFlagsMutuallyExclusive("data-dir", "data-zip") - return cmd + return command } -func runRestore(ctx context.Context, stderr io.Writer, f app.RestoreFlags) error { - req, dump, err := app.ValidateRestore(f) +func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) error { + options, dump, err := app.ValidateRestore(flags) if err != nil { return err } - data, err := openRestoreData(f.DataDir, f.DataZip) + data, err := openRestoreData(flags.DataDir, flags.DataZip) if err != nil { return err } defer closeRestoreData(data) - d, keys, err := app.RestoreDiscovery(data, dump, req) + discovery, keys, err := app.RestoreDiscovery(data, dump, options) if err != nil { return err } - if len(d.Dirs) == 0 { + if len(discovery.Dirs) == 0 { log.Warnf("no browsers to restore from the supplied keys and data") return nil } - req.Keys = keys - summary, err := app.Execute(ctx, app.NewPlan(d, req), req) + options.Keys = keys + summary, err := app.Execute(ctx, app.NewPlan(discovery, options), options) if ctx.Err() == nil { report(stderr, summary) } @@ -73,15 +73,15 @@ func openRestoreData(dataDir, dataZip string) (*snapshot.Dir, error) { if dataDir != "" { return snapshot.Open(dataDir), nil } - d, err := snapshot.Unzip(dataZip) + snapshotDir, err := snapshot.Unzip(dataZip) if err != nil { return nil, fmt.Errorf("extract %s: %w", dataZip, err) } - return d, nil + return snapshotDir, nil } -func closeRestoreData(d *snapshot.Dir) { - if err := d.Close(); err != nil { +func closeRestoreData(snapshotDir *snapshot.Dir) { + if err := snapshotDir.Close(); err != nil { log.Warnf("restore: %v", err) } } diff --git a/cmd/hack-browser-data/version.go b/cmd/hack-browser-data/version.go index 60f1a3c..7aee0db 100644 --- a/cmd/hack-browser-data/version.go +++ b/cmd/hack-browser-data/version.go @@ -17,9 +17,9 @@ func versionCmd() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Print version information", - Run: func(cmd *cobra.Command, _ []string) { + Run: func(command *cobra.Command, _ []string) { resolveVersionFromBuildInfo() - fmt.Fprintf(cmd.OutOrStdout(), "hack-browser-data %s\n commit: %s\n built: %s\n", + fmt.Fprintf(command.OutOrStdout(), "hack-browser-data %s\n commit: %s\n built: %s\n", version, commit, buildDate) }, } @@ -36,17 +36,17 @@ func resolveVersionFromBuildInfo() { if info.Main.Version != "" && info.Main.Version != "(devel)" { version = info.Main.Version } - for _, s := range info.Settings { - switch s.Key { + for _, setting := range info.Settings { + switch setting.Key { case "vcs.revision": - if len(s.Value) > 8 { - commit = s.Value[:8] - } else if s.Value != "" { - commit = s.Value + if len(setting.Value) > 8 { + commit = setting.Value[:8] + } else if setting.Value != "" { + commit = setting.Value } case "vcs.time": - if s.Value != "" { - buildDate = s.Value + if setting.Value != "" { + buildDate = setting.Value } } } diff --git a/internal/app/app.go b/internal/app/app.go index d272b06..393779d 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -28,8 +28,8 @@ type Flags struct { KeychainPasswordStdin bool } -type Request struct { - Browser string // "all" or one Def.ID +type Options struct { + Browser string // "all" or one Browser.Name Categories []category.Category Format export.Format Dir string @@ -37,97 +37,97 @@ type Request struct { ProfilePath string Home string - // Called when the login keychain is first opened; "" leaves it locked, and nil, as list has it, does so silently. + // KeychainPassword runs when the keychain first opens; "" leaves it locked, and nil, as list has it, silently. KeychainPassword func(ctx context.Context) (string, error) // Keys are a dump's keys by user data dir; nil retrieves every dir's keys from this machine. - Keys map[browser.DirID]masterkey.Set + Keys map[browser.UserDataDirID]masterkey.Set } // Validate checks every flag before any browser or secret is touched, so a bad flag fails fast. -func Validate(f Flags) (Request, error) { - return validate(f, os.Stdin) +func Validate(flags Flags) (Options, error) { + return validate(flags, os.Stdin) } -func validate(f Flags, stdin *os.File) (Request, error) { - id, err := parseBrowser(f.Browser) +func validate(flags Flags, stdin *os.File) (Options, error) { + browserName, err := parseBrowser(flags.Browser) if err != nil { - return Request{}, err + return Options{}, err } - categories, err := parseCategories(f.Categories) + categories, err := parseCategories(flags.Categories) if err != nil { - return Request{}, err + return Options{}, err } - format, err := export.ParseFormat(f.Format) + format, err := export.ParseFormat(flags.Format) if err != nil { - return Request{}, err + return Options{}, err } - if err := checkOutputDir(f.Dir); err != nil { - return Request{}, err + if err := checkOutputDir(flags.Dir); err != nil { + return Options{}, err } - profilePath, err := checkProfilePath(id, f.ProfilePath) + profilePath, err := checkProfilePath(browserName, flags.ProfilePath) if err != nil { - return Request{}, err + return Options{}, err } - password, err := keychainPassword(f, stdin) + password, err := keychainPassword(flags, stdin) if err != nil { - return Request{}, err + return Options{}, err } home, err := homeDir() if err != nil { - return Request{}, err + return Options{}, err } - return Request{ - Browser: id, + return Options{ + Browser: browserName, Categories: categories, Format: format, - Dir: f.Dir, - Zip: f.Zip, + Dir: flags.Dir, + Zip: flags.Zip, ProfilePath: profilePath, Home: home, KeychainPassword: password, }, nil } -func ValidateKeys(f Flags) (Request, error) { - id, err := parseBrowser(f.Browser) +func ValidateKeys(flags Flags) (Options, error) { + browserName, err := parseBrowser(flags.Browser) if err != nil { - return Request{}, err + return Options{}, err } - password, err := keychainPassword(f, os.Stdin) + password, err := keychainPassword(flags, os.Stdin) if err != nil { - return Request{}, err + return Options{}, err } home, err := homeDir() if err != nil { - return Request{}, err + return Options{}, err } - return Request{Browser: id, Home: home, KeychainPassword: password}, nil + return Options{Browser: browserName, Home: home, KeychainPassword: password}, nil } // ValidateArchive takes no keychain password: an archive copies files and reads no secret. -func ValidateArchive(f Flags) (Request, error) { - id, err := parseBrowser(f.Browser) +func ValidateArchive(flags Flags) (Options, error) { + browserName, err := parseBrowser(flags.Browser) if err != nil { - return Request{}, err + return Options{}, err } - categories, err := parseCategories(f.Categories) + categories, err := parseCategories(flags.Categories) if err != nil { - return Request{}, err + return Options{}, err } home, err := homeDir() if err != nil { - return Request{}, err + return Options{}, err } - return Request{Browser: id, Categories: categories, Home: home}, nil + return Options{Browser: browserName, Categories: categories, Home: home}, nil } -// ListRequest is what list reads: every browser and category, with the keychain left locked, so counting never prompts. -func ListRequest() (Request, error) { +// ListOptions is what list reads: every browser and category, with the keychain left locked, so counting never prompts. +func ListOptions() (Options, error) { home, err := homeDir() if err != nil { - return Request{}, err + return Options{}, err } - return Request{Browser: allBrowsers, Categories: category.All(), Home: home}, nil + return Options{Browser: allBrowsers, Categories: category.All(), Home: home}, nil } func homeDir() (string, error) { @@ -140,18 +140,18 @@ func homeDir() (string, error) { const allBrowsers = "all" -// parseBrowser accepts all or one of this OS's browser IDs; an ID from another OS's table has nothing to find here. -func parseBrowser(s string) (string, error) { - id := strings.ToLower(strings.TrimSpace(s)) - if id == "" || id == allBrowsers { +// parseBrowser accepts all or one of this OS's browser names; a name from another OS's table has nothing to find here. +func parseBrowser(value string) (string, error) { + name := strings.ToLower(strings.TrimSpace(value)) + if name == "" || name == allBrowsers { return allBrowsers, nil } - for _, def := range browser.Supported() { - if def.ID == id { - return id, nil + for _, supportedBrowser := range browser.Supported() { + if supportedBrowser.Name == name { + return name, nil } } - return "", fmt.Errorf("unknown browser %q, available: %s|%s", s, allBrowsers, strings.Join(browser.IDs(), "|")) + return "", fmt.Errorf("unknown browser %q, available: %s|%s", value, allBrowsers, strings.Join(browser.Names(), "|")) } // checkOutputDir creates nothing: -d, or its nearest existing ancestor, must be a directory we can create in. @@ -179,11 +179,11 @@ func checkOutputDir(dir string) error { } // checkProfilePath keeps -p only when one browser is named; with -b all it is ignored, as it always was, but now said. -func checkProfilePath(id, path string) (string, error) { +func checkProfilePath(browserName, path string) (string, error) { if path == "" { return "", nil } - if id == allBrowsers { + if browserName == allBrowsers { log.Warnf("-p needs a specific -b; ignoring %s", path) return "", nil } @@ -198,25 +198,25 @@ func checkProfilePath(id, path string) (string, error) { } // parseCategories keeps a repeated category once, or its records would be exported twice. -func parseCategories(s string) ([]category.Category, error) { - s = strings.TrimSpace(s) - if strings.EqualFold(s, "all") { +func parseCategories(value string) ([]category.Category, error) { + value = strings.TrimSpace(value) + if strings.EqualFold(value, "all") { return category.All(), nil } var categories []category.Category seen := make(map[category.Category]bool) - for _, name := range strings.Split(s, ",") { + for _, name := range strings.Split(value, ",") { name = strings.TrimSpace(strings.ToLower(name)) if name == "" { continue } - c, err := category.Parse(name) + dataCategory, err := category.Parse(name) if err != nil { return nil, fmt.Errorf("%w, available: all|%s", err, strings.Join(category.Names(), ",")) } - if !seen[c] { - seen[c] = true - categories = append(categories, c) + if !seen[dataCategory] { + seen[dataCategory] = true + categories = append(categories, dataCategory) } } if len(categories) == 0 { diff --git a/internal/app/app_test.go b/internal/app/app_test.go index eac2f9b..651b42f 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -18,28 +18,28 @@ import ( ) func TestValidate(t *testing.T) { - req, err := Validate(Flags{Browser: " Chrome ", Categories: "cookie, password,cookie", Format: "csv", Dir: "out", KeychainPassword: "pw"}) + options, err := Validate(Flags{Browser: " Chrome ", Categories: "cookie, password,cookie", Format: "csv", Dir: "out", KeychainPassword: "pw"}) require.NoError(t, err) - assert.Equal(t, "chrome", req.Browser) - assert.Equal(t, []category.Category{category.Cookie, category.Password}, req.Categories, "a repeated category runs once") - assert.Equal(t, export.CSV, req.Format) - assert.Equal(t, "out", req.Dir) - assert.NotEmpty(t, req.Home) - password, err := req.KeychainPassword(context.Background()) + assert.Equal(t, "chrome", options.Browser) + assert.Equal(t, []category.Category{category.Cookie, category.Password}, options.Categories, "a repeated category runs once") + assert.Equal(t, export.CSV, options.Format) + assert.Equal(t, "out", options.Dir) + assert.NotEmpty(t, options.Home) + password, err := options.KeychainPassword(context.Background()) require.NoError(t, err) assert.Equal(t, "pw", password) - req, err = Validate(Flags{Categories: "all", Format: "json"}) + options, err = Validate(Flags{Categories: "all", Format: "json"}) require.NoError(t, err) - assert.Equal(t, "all", req.Browser) - assert.Equal(t, category.All(), req.Categories) + assert.Equal(t, "all", options.Browser) + assert.Equal(t, category.All(), options.Categories) } func TestValidate_RejectsBadInput(t *testing.T) { file := filepath.Join(t.TempDir(), "file") require.NoError(t, os.WriteFile(file, nil, 0o600)) missing := filepath.Join(t.TempDir(), "missing") - for name, f := range map[string]Flags{ + for name, flags := range map[string]Flags{ "unknown category": {Categories: "cookie,bogus", Format: "json"}, "no category": {Categories: " , ", Format: "json"}, "unknown format": {Categories: "all", Format: "xml"}, @@ -51,18 +51,18 @@ func TestValidate_RejectsBadInput(t *testing.T) { "-p is a file": {Browser: "chrome", Categories: "all", Format: "json", ProfilePath: file}, "two password inputs": {Categories: "all", Format: "json", KeychainPassword: "pw", KeychainPasswordStdin: true}, } { - _, err := Validate(f) + _, err := Validate(flags) assert.Error(t, err, name) } } func otherOSBrowser(t *testing.T) string { t.Helper() - for _, id := range []string{"sogou", "safari"} { - def, ok := browser.Lookup(id) - require.True(t, ok, id) - if len(def.Platform().UserDataDirs) == 0 { - return id + for _, name := range []string{"sogou", "safari"} { + namedBrowser, ok := browser.Lookup(name) + require.True(t, ok, name) + if len(namedBrowser.Platform().UserDataDirs) == 0 { + return name } } t.Fatal("every candidate is supported here") @@ -71,9 +71,9 @@ func otherOSBrowser(t *testing.T) string { func TestValidate_CreatesNoOutputDir(t *testing.T) { root := t.TempDir() - req, err := Validate(Flags{Categories: "all", Format: "json", Dir: filepath.Join(root, "a", "b")}) + options, err := Validate(Flags{Categories: "all", Format: "json", Dir: filepath.Join(root, "a", "b")}) require.NoError(t, err) - assert.Equal(t, filepath.Join(root, "a", "b"), req.Dir) + assert.Equal(t, filepath.Join(root, "a", "b"), options.Dir) _, err = os.Stat(filepath.Join(root, "a")) assert.ErrorIs(t, err, fs.ErrNotExist) } @@ -90,11 +90,11 @@ func TestValidate_RejectsAnOutputDirThatCannotBeCreated(t *testing.T) { assert.Error(t, err) } -// -p without a named browser was always ignored; it is still not checked, only reported. +// TestValidate_IgnoresProfilePathForAllBrowsers keeps -p without a named browser ignored, as before; it is reported. func TestValidate_IgnoresProfilePathForAllBrowsers(t *testing.T) { - req, err := Validate(Flags{Browser: "all", Categories: "all", Format: "json", ProfilePath: filepath.Join(t.TempDir(), "missing")}) + options, err := Validate(Flags{Browser: "all", Categories: "all", Format: "json", ProfilePath: filepath.Join(t.TempDir(), "missing")}) require.NoError(t, err) - assert.Empty(t, req.ProfilePath) + assert.Empty(t, options.ProfilePath) } func TestValidate_KeychainPasswordInputs(t *testing.T) { @@ -110,21 +110,21 @@ func TestValidate_KeychainPasswordInputs(t *testing.T) { {name: "stdin without newline", flags: Flags{KeychainPasswordStdin: true}, stdin: "from-stdin", want: "from-stdin"}, {name: "none off a terminal", flags: Flags{}, stdin: "from-stdin\n", err: errNoPassword}, } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - r, w, err := os.Pipe() + for _, testCase := range tests { + testCase := testCase + t.Run(testCase.name, func(t *testing.T) { + pipeReader, pipeWriter, err := os.Pipe() require.NoError(t, err) - defer r.Close() - _, err = w.WriteString(tt.stdin) - require.NoError(t, errors.Join(err, w.Close())) + defer pipeReader.Close() + _, err = pipeWriter.WriteString(testCase.stdin) + require.NoError(t, errors.Join(err, pipeWriter.Close())) - tt.flags.Categories, tt.flags.Format = "all", "json" - req, err := validate(tt.flags, r) + testCase.flags.Categories, testCase.flags.Format = "all", "json" + options, err := validate(testCase.flags, pipeReader) require.NoError(t, err) - got, err := req.KeychainPassword(context.Background()) - require.ErrorIs(t, err, tt.err) - assert.Equal(t, tt.want, got) + got, err := options.KeychainPassword(context.Background()) + require.ErrorIs(t, err, testCase.err) + assert.Equal(t, testCase.want, got) }) } } diff --git a/internal/app/archive.go b/internal/app/archive.go index d1e6a49..78a900e 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -13,84 +13,84 @@ import ( // Archive also keeps Local State and each profile's marker, so a reader without the manifest still finds the profiles. // It returns how many files and directories were captured. -func Archive(ctx context.Context, d Discovery, req Request, dst string) (int, error) { +func Archive(ctx context.Context, discovery Discovery, options Options, archivePath string) (int, error) { var dirs []browser.UserDataDir - for _, dir := range d.Dirs { - if dir.Def.Base == browser.Chromium { + for _, dir := range discovery.Dirs { + if dir.Browser.Base == browser.Chromium { dirs = append(dirs, dir) } } - files := archiveFiles(NewPlan(Discovery{Dirs: dirs}, req), dirs) + files := archiveFiles(NewPlan(Discovery{Dirs: dirs}, options), dirs) - snap, err := snapshot.Temp() + snapshotDir, err := snapshot.Temp() if err != nil { return 0, err } - defer closeSnapshot(snap) - if err := snap.Capture(ctx, files); err != nil { + defer closeSnapshot(snapshotDir) + if err := snapshotDir.Capture(ctx, files); err != nil { return 0, err } - m, n := manifestOf(snap, dirs, files) - if n == 0 { + manifest, fileCount := manifestOf(snapshotDir, dirs, files) + if fileCount == 0 { return 0, errors.New("no decryption-relevant files found to archive") } - if err := snap.WriteManifest(m); err != nil { + if err := snapshotDir.WriteManifest(manifest); err != nil { return 0, err } - if err := snap.Zip(dst); err != nil { - return 0, fmt.Errorf("write archive %s: %w", dst, err) + if err := snapshotDir.Zip(archivePath); err != nil { + return 0, fmt.Errorf("write archive %s: %w", archivePath, err) } - return n, nil + return fileCount, nil } -func archiveFiles(p Plan, dirs []browser.UserDataDir) []snapshot.File { +func archiveFiles(plan Plan, dirs []browser.UserDataDir) []snapshot.File { var files []snapshot.File seen := make(map[snapshot.File]bool) - add := func(f snapshot.File) { - if !seen[f] { - seen[f] = true - files = append(files, f) + add := func(file snapshot.File) { + if !seen[file] { + seen[file] = true + files = append(files, file) } } for _, dir := range dirs { - for _, prof := range dir.Profiles { - for _, src := range chromium.ArchiveSources(dir) { - if f, ok, err := firstOnDisk(dir, prof, src); err == nil && ok { - add(f) + for _, profile := range dir.Profiles { + for _, fileSpec := range chromium.ArchiveFileSpecs(dir) { + if file, ok, err := firstOnDisk(dir, profile, fileSpec); err == nil && ok { + add(file) } } } - for _, f := range filesOf(p, dir.ID) { - add(f) + for _, file := range filesOf(plan, dir.ID) { + add(file) } } return files } // manifestOf lists each dir's files that reached the snapshot; one whose copy failed is reported and left out. -func manifestOf(snap *snapshot.Dir, dirs []browser.UserDataDir, files []snapshot.File) (snapshot.Manifest, int) { - m := snapshot.Manifest{Version: snapshot.ManifestVersion, Dirs: []snapshot.ManifestDir{}} - n := 0 +func manifestOf(snapshotDir *snapshot.Dir, dirs []browser.UserDataDir, files []snapshot.File) (snapshot.Manifest, int) { + manifest := snapshot.Manifest{Version: snapshot.ManifestVersion, Dirs: []snapshot.ManifestDir{}} + fileCount := 0 for _, dir := range dirs { - md := snapshot.ManifestDir{ID: string(dir.ID), Browser: dir.Def.ID, Base: dir.Def.Base.String()} - for _, p := range dir.Profiles { - md.Profiles = append(md.Profiles, snapshot.ManifestProfile{Name: p.Name, Dir: p.Dir}) + manifestEntry := snapshot.ManifestDir{ID: string(dir.ID), Browser: dir.Browser.Name, Base: dir.Browser.Base.String()} + for _, profile := range dir.Profiles { + manifestEntry.Profiles = append(manifestEntry.Profiles, snapshot.ManifestProfile{Name: profile.Name, Dir: profile.Dir}) } - captured := snap.Snapshot(string(dir.ID)) - for _, f := range files { - if f.DirID != string(dir.ID) { + captured := snapshotDir.Snapshot(string(dir.ID)) + for _, file := range files { + if file.UserDataDirID != string(dir.ID) { continue } - if _, err := captured.Path(f.Rel); err != nil { - log.Warnf("archive: acquire %s/%s: %v", f.DirID, f.Rel, err) + if _, err := captured.Path(file.RelativePath); err != nil { + log.Warnf("archive: acquire %s/%s: %v", file.UserDataDirID, file.RelativePath, err) continue } - md.Files = append(md.Files, f.Rel) - n++ + manifestEntry.Files = append(manifestEntry.Files, file.RelativePath) + fileCount++ } - if len(md.Files) > 0 { - m.Dirs = append(m.Dirs, md) + if len(manifestEntry.Files) > 0 { + manifest.Dirs = append(manifest.Dirs, manifestEntry) } } - return m, n + return manifest, fileCount } diff --git a/internal/app/archive_golden_test.go b/internal/app/archive_golden_test.go index 7100c97..0237e91 100644 --- a/internal/app/archive_golden_test.go +++ b/internal/app/archive_golden_test.go @@ -20,7 +20,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" ) -const archiveLayoutKey = "chrome" +const archiveLayoutBrowser = "chrome" var archiveLayoutProfileFiles = []string{ "Preferences", @@ -54,34 +54,34 @@ func archiveLayoutUserData(t *testing.T, root string) { t.Helper() files := append([]string{}, archiveLayoutExtraFiles...) for _, profile := range []string{"Default", "Profile 1"} { - for _, rel := range archiveLayoutProfileFiles { - files = append(files, profile+"/"+rel) + for _, relativePath := range archiveLayoutProfileFiles { + files = append(files, profile+"/"+relativePath) } } - for _, rel := range files { - abs := filepath.Join(root, filepath.FromSlash(rel)) - require.NoError(t, os.MkdirAll(filepath.Dir(abs), 0o755)) - require.NoError(t, os.WriteFile(abs, []byte(rel), 0o600)) + for _, relativePath := range files { + absolutePath := filepath.Join(root, filepath.FromSlash(relativePath)) + require.NoError(t, os.MkdirAll(filepath.Dir(absolutePath), 0o755)) + require.NoError(t, os.WriteFile(absolutePath, []byte(relativePath), 0o600)) } } func archiveLayoutEntryNames(t *testing.T, zipPath string) []string { t.Helper() - r, err := zip.OpenReader(zipPath) + zipReader, err := zip.OpenReader(zipPath) require.NoError(t, err) - defer r.Close() - names := make([]string, 0, len(r.File)) - for _, f := range r.File { - names = append(names, f.Name) + defer zipReader.Close() + names := make([]string, 0, len(zipReader.File)) + for _, zipFile := range zipReader.File { + names = append(names, zipFile.Name) } return names } func TestArchiveGolden(t *testing.T) { home := t.TempDir() - def, ok := browser.Lookup(archiveLayoutKey) + namedBrowser, ok := browser.Lookup(archiveLayoutBrowser) require.True(t, ok) - archiveLayoutUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0]))) + archiveLayoutUserData(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0]))) tests := []struct { name string @@ -91,18 +91,18 @@ func TestArchiveGolden(t *testing.T) { {name: "all", golden: "archive-all.golden", categories: "all"}, {name: "cookie", golden: "archive-cookie.golden", categories: "cookie"}, } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - req, err := app.ValidateArchive(app.Flags{Browser: archiveLayoutKey, Categories: tt.categories}) + for _, testCase := range tests { + testCase := testCase + t.Run(testCase.name, func(t *testing.T) { + options, err := app.ValidateArchive(app.Flags{Browser: archiveLayoutBrowser, Categories: testCase.categories}) require.NoError(t, err) - req.Home = home + options.Home = home out := filepath.Join(t.TempDir(), "browser-data.zip") - n, err := app.Archive(context.Background(), app.Discover(req), req, out) + fileCount, err := app.Archive(context.Background(), app.Discover(options), options, out) require.NoError(t, err) - golden.Assert(t, tt.golden, fmt.Sprintf("entries=%d\n", n)+golden.ZipListing(t, out)) + golden.Assert(t, testCase.golden, fmt.Sprintf("entries=%d\n", fileCount)+golden.ZipListing(t, out)) - prefix := archiveLayoutKey + "/" + prefix := archiveLayoutBrowser + "/" names := archiveLayoutEntryNames(t, out) assert.Contains(t, names, "manifest.json") for _, name := range names { @@ -121,19 +121,19 @@ func TestArchiveGolden(t *testing.T) { } } -// archive on one host and restore on another, through the pipeline, write what dump writes. +// TestArchiveRestoreRoundTrip archives on one host and restores on another, which must write what dump writes. func TestArchiveRestoreRoundTrip(t *testing.T) { home := t.TempDir() - for _, inst := range browsertest.ChromiumInstalls { - def, ok := browser.Lookup(inst.Key) - require.True(t, ok, inst.Key) - browsertest.ChromiumUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])), inst.Key) + for _, fixture := range browsertest.ChromiumInstalls { + namedBrowser, ok := browser.Lookup(fixture.Name) + require.True(t, ok, fixture.Name) + browsertest.ChromiumUserData(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])), fixture.Name) } - req, err := app.ValidateArchive(app.Flags{Browser: "all", Categories: "all"}) + options, err := app.ValidateArchive(app.Flags{Browser: "all", Categories: "all"}) require.NoError(t, err) - req.Home = home + options.Home = home archive := filepath.Join(t.TempDir(), "data.zip") - _, err = app.Archive(context.Background(), app.Discover(req), req, archive) + _, err = app.Archive(context.Background(), app.Discover(options), options, archive) require.NoError(t, err) require.Contains(t, archiveLayoutEntryNames(t, archive), "manifest.json") diff --git a/internal/app/discover.go b/internal/app/discover.go index f59f597..4be548c 100644 --- a/internal/app/discover.go +++ b/internal/app/discover.go @@ -16,23 +16,23 @@ type Discovery struct { } // Discover applies -p only when one browser is named. -func Discover(req Request) Discovery { - var d Discovery - for _, def := range browser.Supported() { - if req.Browser != allBrowsers && def.ID != req.Browser { +func Discover(options Options) Discovery { + var discovery Discovery + for _, supportedBrowser := range browser.Supported() { + if options.Browser != allBrowsers && supportedBrowser.Name != options.Browser { continue } - opts := browser.DiscoverOptions{Home: req.Home} - if req.Browser != allBrowsers { - opts.ProfilePath = req.ProfilePath + discoverOptions := browser.DiscoverOptions{Home: options.Home} + if options.Browser != allBrowsers { + discoverOptions.ProfilePath = options.ProfilePath } - dirs, err := discover(def, opts) - d.Dirs = append(d.Dirs, withData(dirs)...) + dirs, err := discover(supportedBrowser, discoverOptions) + discovery.Dirs = append(discovery.Dirs, withData(dirs)...) if err != nil { - d.Failed = append(d.Failed, dirFailure(browser.DirID(def.ID), err)) + discovery.Failed = append(discovery.Failed, dirFailure(browser.UserDataDirID(supportedBrowser.Name), err)) } } - return d + return discovery } // withData drops profiles holding no file any category reads, such as a bare Preferences, but keeps unreadable ones. @@ -41,9 +41,9 @@ func withData(dirs []browser.UserDataDir) []browser.UserDataDir { var out []browser.UserDataDir for _, dir := range dirs { var profiles []browser.Profile - for _, p := range dir.Profiles { - if hasData(dir, p, extractors(dir, p)) { - profiles = append(profiles, p) + for _, profile := range dir.Profiles { + if hasData(dir, profile, extractors(dir, profile)) { + profiles = append(profiles, profile) } } if len(profiles) > 0 { @@ -54,42 +54,42 @@ func withData(dirs []browser.UserDataDir) []browser.UserDataDir { return out } -func hasData(dir browser.UserDataDir, p browser.Profile, ex browser.Extractors) bool { - for _, x := range ex { - if len(x.Sources) == 0 { +func hasData(dir browser.UserDataDir, profile browser.Profile, extractors browser.Extractors) bool { + for _, extractor := range extractors { + if len(extractor.FileSpecs) == 0 { continue } - if _, ok, err := locate(dir, p, x.Sources); ok || err != nil { + if _, ok, err := locate(dir, profile, extractor.FileSpecs); ok || err != nil { return true } } return false } -// The base packages import browser, so the dispatch on Base lives here rather than in browser. -func discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { - switch def.Base { +// discover dispatches on Base here, not in browser, because the base packages import browser. +func discover(supportedBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { + switch supportedBrowser.Base { case browser.Chromium: - return chromium.Discover(def, opts) + return chromium.Discover(supportedBrowser, options) case browser.Firefox: - return firefox.Discover(def, opts) + return firefox.Discover(supportedBrowser, options) case browser.Safari: - return safari.Discover(def, opts) + return safari.Discover(supportedBrowser, options) default: - return nil, fmt.Errorf("%s: no base package", def.ID) + return nil, fmt.Errorf("%s: no base package", supportedBrowser.Name) } } // extractorsWith hands Safari the run's login keychain, which its default profile's password extractor reads. -func extractorsWith(kc safari.LoginKeychain) extractorsFunc { - return func(dir browser.UserDataDir, p browser.Profile) browser.Extractors { - switch dir.Def.Base { +func extractorsWith(keychain safari.LoginKeychain) extractorsFunc { + return func(dir browser.UserDataDir, profile browser.Profile) browser.Extractors { + switch dir.Browser.Base { case browser.Chromium: - return chromium.Extractors(dir, p) + return chromium.Extractors(dir, profile) case browser.Firefox: - return firefox.Extractors(dir, p) + return firefox.Extractors(dir, profile) case browser.Safari: - return safari.Extractors(dir, p, kc) + return safari.Extractors(dir, profile, keychain) default: return nil } diff --git a/internal/app/discover_test.go b/internal/app/discover_test.go index 26299a4..900990e 100644 --- a/internal/app/discover_test.go +++ b/internal/app/discover_test.go @@ -12,19 +12,19 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" ) -func installAt(t *testing.T, home, id string) string { +func installAt(t *testing.T, home, browserName string) string { t.Helper() - def := lookup(t, id) - require.NotEmpty(t, def.Platform().UserDataDirs, id) - path := filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])) + namedBrowser := lookup(t, browserName) + require.NotEmpty(t, namedBrowser.Platform().UserDataDirs, browserName) + path := filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])) touch(t, path, "Default", "Preferences") touch(t, path, "Default", "History") return path } -func dirIDs(d Discovery) []browser.DirID { - var ids []browser.DirID - for _, dir := range d.Dirs { +func userDataDirIDs(discovery Discovery) []browser.UserDataDirID { + var ids []browser.UserDataDirID + for _, dir := range discovery.Dirs { ids = append(ids, dir.ID) } return ids @@ -35,12 +35,12 @@ func TestDiscover(t *testing.T) { installAt(t, home, "edge") installAt(t, home, "chrome") - d := Discover(Request{Browser: "all", Home: home}) - assert.Equal(t, []browser.DirID{"chrome", "edge"}, dirIDs(d), "table order, which is output order") - assert.Empty(t, d.Failed) + discovery := Discover(Options{Browser: "all", Home: home}) + assert.Equal(t, []browser.UserDataDirID{"chrome", "edge"}, userDataDirIDs(discovery), "table order, which is output order") + assert.Empty(t, discovery.Failed) - d = Discover(Request{Browser: "edge", Home: home}) - assert.Equal(t, []browser.DirID{"edge"}, dirIDs(d)) + discovery = Discover(Options{Browser: "edge", Home: home}) + assert.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery)) } func TestDiscover_ProfilePathNeedsOneBrowser(t *testing.T) { @@ -50,16 +50,16 @@ func TestDiscover_ProfilePathNeedsOneBrowser(t *testing.T) { touch(t, custom, "Default", "Preferences") touch(t, custom, "Default", "History") - d := Discover(Request{Browser: "chrome", Home: home, ProfilePath: custom}) - require.Len(t, d.Dirs, 1) - assert.Equal(t, custom, d.Dirs[0].Path) + discovery := Discover(Options{Browser: "chrome", Home: home, ProfilePath: custom}) + require.Len(t, discovery.Dirs, 1) + assert.Equal(t, custom, discovery.Dirs[0].Path) - d = Discover(Request{Browser: "all", Home: home, ProfilePath: custom}) - require.Len(t, d.Dirs, 1) - assert.NotEqual(t, custom, d.Dirs[0].Path, "-p is ignored without a specific browser") + discovery = Discover(Options{Browser: "all", Home: home, ProfilePath: custom}) + require.Len(t, discovery.Dirs, 1) + assert.NotEqual(t, custom, discovery.Dirs[0].Path, "-p is ignored without a specific browser") } -// A profile created and never used holds only its Preferences marker, so it is not listed, archived, or keyed. +// TestDiscover_KeepsOnlyProfilesWithData drops a never-used profile, which holds only its Preferences marker. func TestDiscover_KeepsOnlyProfilesWithData(t *testing.T) { home := t.TempDir() chrome := installAt(t, home, "chrome") @@ -67,9 +67,9 @@ func TestDiscover_KeepsOnlyProfilesWithData(t *testing.T) { edge := installAt(t, home, "edge") require.NoError(t, os.Remove(filepath.Join(edge, "Default", "History"))) - d := Discover(Request{Browser: "all", Home: home}) - assert.Equal(t, []browser.DirID{"chrome"}, dirIDs(d)) - assert.Equal(t, []browser.Profile{{Name: "Default", Dir: "Default"}}, d.Dirs[0].Profiles) + discovery := Discover(Options{Browser: "all", Home: home}) + assert.Equal(t, []browser.UserDataDirID{"chrome"}, userDataDirIDs(discovery)) + assert.Equal(t, []browser.Profile{{Name: "Default", Dir: "Default"}}, discovery.Dirs[0].Profiles) } func TestDiscover_UnreadableDirIsReported(t *testing.T) { @@ -81,14 +81,14 @@ func TestDiscover_UnreadableDirIsReported(t *testing.T) { require.NoError(t, os.Chmod(path, 0o000)) defer func() { require.NoError(t, os.Chmod(path, 0o700)) }() - d := Discover(Request{Browser: "all", Home: home}) - assert.Empty(t, d.Dirs) - require.Len(t, d.Failed, 1) - assert.Equal(t, Extraction{DirID: "chrome"}, d.Failed[0].Extraction) - assert.Equal(t, OutcomeError, d.Failed[0].Outcome) + discovery := Discover(Options{Browser: "all", Home: home}) + assert.Empty(t, discovery.Dirs) + require.Len(t, discovery.Failed, 1) + assert.Equal(t, Extraction{UserDataDirID: "chrome"}, discovery.Failed[0].Extraction) + assert.Equal(t, OutcomeError, discovery.Failed[0].Outcome) } -// Dropping a profile whose files cannot be checked would hide the failure; the plan reports it instead. +// 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") lock(t, filepath.Join(dir.Path, "Default")) diff --git a/internal/app/execute.go b/internal/app/execute.go index 191b90e..e401fb8 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -25,28 +25,28 @@ type runKeychain interface { safari.LoginKeychain } -type keySource func(ctx context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error) +type masterKeyRetriever func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) // Execute handles one user data dir at a time, so at most one dir's copies are on disk. // Its error means the run could not finish; every other failure is a Result. -func Execute(ctx context.Context, p Plan, req Request) (Summary, error) { - kc := loginKeychain(req) - keys := dumpKeys(req.Keys) - if req.Keys == nil { - keys = machineKeys(kc) +func Execute(ctx context.Context, plan Plan, options Options) (Summary, error) { + keychain := loginKeychain(options) + keys := dumpKeys(options.Keys) + if options.Keys == nil { + keys = machineKeys(keychain) } - return execute(ctx, p, req, extractorsWith(kc), keys) + return execute(ctx, plan, options, extractorsWith(keychain), keys) } -func execute(ctx context.Context, p Plan, req Request, extractors extractorsFunc, keys keySource) (Summary, error) { - w, err := export.NewWriter(req.Dir, req.Format, req.Zip) +func execute(ctx context.Context, plan Plan, options Options, extractors extractorsFunc, keys masterKeyRetriever) (Summary, error) { + writer, err := export.NewWriter(options.Dir, options.Format, options.Zip) if err != nil { return Summary{}, err } - s, err := runner{w: w, extractors: extractors, keys: keys, announce: true}.run(ctx, p) - closeErr := w.Close() - announceOutput(w.Output()) - return s, errors.Join(err, closeErr) + summary, err := runner{writer: writer, extractors: extractors, keys: keys, announce: true}.run(ctx, plan) + closeErr := writer.Close() + announceOutput(writer.Output()) + return summary, errors.Join(err, closeErr) } func announceOutput(out export.Output) { @@ -55,8 +55,8 @@ func announceOutput(out export.Output) { } fmt.Fprintln(os.Stderr) log.Infof("Exported to %s/", out.Dir) - for _, f := range out.Files { - log.Infof(" %-24s %d entries", f.Name, f.Count) + for _, file := range out.Files { + log.Infof(" %-24s %d entries", file.Name, file.Count) } if out.Zip != "" { log.Infof("Compressed: %s/%s", out.Dir, out.Zip) @@ -64,12 +64,12 @@ func announceOutput(out export.Output) { } // Count runs the plan with no key and the keychain locked, counting records instead of exporting them. -func Count(ctx context.Context, p Plan, req Request) (Summary, error) { - return runner{w: discard{}, extractors: extractorsWith(loginKeychain(req)), keys: dumpKeys(nil)}.run(ctx, p) +func Count(ctx context.Context, plan Plan, options Options) (Summary, error) { + return runner{writer: discard{}, extractors: extractorsWith(loginKeychain(options)), keys: dumpKeys(nil)}.run(ctx, plan) } type recordWriter interface { - Write(c category.Category, records []record.Record) error + Write(dataCategory category.Category, records []record.Record) error } type discard struct{} @@ -78,19 +78,19 @@ func (discard) Write(category.Category, []record.Record) error { return nil } // runner is what every user data dir of one run shares; announce logs each dir as it starts. type runner struct { - w recordWriter + writer recordWriter extractors extractorsFunc - keys keySource + keys masterKeyRetriever announce bool } -func (r runner) run(ctx context.Context, p Plan) (Summary, error) { - results := append([]Result(nil), p.Skipped...) - for _, dir := range p.Dirs { +func (r runner) run(ctx context.Context, plan Plan) (Summary, error) { + results := append([]Result(nil), plan.Skipped...) + for _, dir := range plan.Dirs { if err := ctx.Err(); err != nil { return Summary{Results: results}, fmt.Errorf("run stopped: %w", err) } - dirResults, err := r.runDir(ctx, dir, p) + dirResults, err := r.runDir(ctx, dir, plan) results = append(results, dirResults...) if err != nil { return Summary{Results: results}, err @@ -99,84 +99,84 @@ func (r runner) run(ctx context.Context, p Plan) (Summary, error) { return Summary{Results: results}, nil } -func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, p Plan) ([]Result, error) { - extractions := extractionsOf(p, dir.ID) +func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, plan Plan) ([]Result, error) { + extractions := extractionsOf(plan, dir.ID) if len(extractions) == 0 { return nil, nil } if r.announce { - log.Infof("Extracting %s...", dir.Def.Name) + log.Infof("Extracting %s...", dir.Browser.DisplayName) } - d, err := snapshot.Temp() + snapshotDir, err := snapshot.Temp() if err != nil { return failAll(extractions, err), nil } - defer closeSnapshot(d) - if err := d.Capture(ctx, filesOf(p, dir.ID)); err != nil { + defer closeSnapshot(snapshotDir) + if err := snapshotDir.Capture(ctx, filesOf(plan, dir.ID)); err != nil { if ctx.Err() != nil { return nil, err } return failAll(extractions, err), nil } - snap := d.Snapshot(string(dir.ID)) + dirSnapshot := snapshotDir.Snapshot(string(dir.ID)) var ( - dk *dirKeys - masterKeys func(context.Context) masterkey.Set + dirKeyRetrieval *dirKeys + masterKeys func(context.Context) masterkey.Set ) - if dir.Def.Base == browser.Chromium { - dk = &dirKeys{retrieve: func(ctx context.Context) (masterkey.Set, error) { return r.keys(ctx, dir, snap) }} - masterKeys = dk.get + if dir.Browser.Base == browser.Chromium { + dirKeyRetrieval = &dirKeys{retrieve: func(ctx context.Context) (masterkey.Set, error) { return r.keys(ctx, dir, dirSnapshot) }} + masterKeys = dirKeyRetrieval.get } profiles := make(map[string]browser.Profile, len(dir.Profiles)) byProfile := make(map[string]browser.Extractors, len(dir.Profiles)) - for _, prof := range dir.Profiles { - profiles[prof.Name] = prof - byProfile[prof.Name] = r.extractors(dir, prof) + for _, profile := range dir.Profiles { + profiles[profile.Name] = profile + byProfile[profile.Name] = r.extractors(dir, profile) } results := make([]Result, 0, len(extractions)+1) - for _, e := range extractions { + for _, extraction := range extractions { if err := ctx.Err(); err != nil { return results, fmt.Errorf("run stopped: %w", err) } - x, ok := byProfile[e.Profile][e.Category] - if !ok || x.Extract == nil { - results = append(results, Result{Extraction: e, Outcome: OutcomeUnsupported}) + extractor, ok := byProfile[extraction.Profile][extraction.Category] + if !ok || extractor.Extract == nil { + results = append(results, Result{Extraction: extraction, Outcome: OutcomeUnsupported}) continue } - prof := profiles[e.Profile] - c := &collector{browser: dir.Def.Name, profile: prof.Name} - err := x.Extract(ctx, browser.NewProfileSnapshot(snap, prof, masterKeys), c) + profile := profiles[extraction.Profile] + recordCollector := &collector{browser: dir.Browser.DisplayName, profile: profile.Name} + err := extractor.Extract(ctx, browser.NewProfileSnapshot(dirSnapshot, profile, masterKeys), recordCollector) // Records emitted before an extraction failed are kept, as they always were. - if writeErr := r.w.Write(e.Category, c.records); writeErr != nil { + if writeErr := r.writer.Write(extraction.Category, recordCollector.records); writeErr != nil { return results, writeErr } - results = append(results, c.result(e, err)) + results = append(results, recordCollector.result(extraction, err)) } - if dk != nil && dk.err != nil { - results = append(results, dirFailure(dir.ID, fmt.Errorf("master key retrieval: %w", dk.err))) + if dirKeyRetrieval != nil && dirKeyRetrieval.err != nil { + results = append(results, dirFailure(dir.ID, fmt.Errorf("master key retrieval: %w", dirKeyRetrieval.err))) } return results, nil } -func extractionsOf(p Plan, id browser.DirID) []Extraction { +func extractionsOf(plan Plan, id browser.UserDataDirID) []Extraction { var out []Extraction - for _, e := range p.Extractions { - if e.DirID == id { - out = append(out, e) + for _, extraction := range plan.Extractions { + if extraction.UserDataDirID == id { + out = append(out, extraction) } } return out } -func filesOf(p Plan, id browser.DirID) []snapshot.File { +func filesOf(plan Plan, id browser.UserDataDirID) []snapshot.File { var out []snapshot.File - for _, f := range p.Files { - if f.DirID == string(id) { - out = append(out, f) + for _, file := range plan.Files { + if file.UserDataDirID == string(id) { + out = append(out, file) } } return out @@ -184,14 +184,14 @@ func filesOf(p Plan, id browser.DirID) []snapshot.File { func failAll(extractions []Extraction, err error) []Result { results := make([]Result, len(extractions)) - for i, e := range extractions { - results[i] = Result{Extraction: e, Outcome: OutcomeError, Err: err} + for i, extraction := range extractions { + results[i] = Result{Extraction: extraction, Outcome: OutcomeError, Err: err} } return results } -func closeSnapshot(d *snapshot.Dir) { - if err := d.Close(); err != nil { +func closeSnapshot(snapshotDir *snapshot.Dir) { + if err := snapshotDir.Close(); err != nil { log.Warnf("%v", err) } } @@ -203,9 +203,9 @@ type collector struct { firstFail error } -func (c *collector) Add(r record.Record) { - record.Stamp(r, c.browser, c.profile) - c.records = append(c.records, r) +func (c *collector) Add(row record.Record) { + row.SetBrowserAndProfile(c.browser, c.profile) + c.records = append(c.records, row) } func (c *collector) Fail(err error) { @@ -216,22 +216,22 @@ func (c *collector) Fail(err error) { log.Debugf("%s/%s: %v", c.browser, c.profile, err) } -// A source gone since planning is absent; failures with no record are an error, and beside records, partial. -func (c *collector) result(e Extraction, err error) Result { - r := Result{Extraction: e, Count: len(c.records), Failed: c.failed} +// result treats a file gone since planning as absent; failures alone are an error, and failures beside records partial. +func (c *collector) result(extraction Extraction, err error) Result { + result := Result{Extraction: extraction, Count: len(c.records), Failed: c.failed} switch { - case err != nil && errors.Is(err, fs.ErrNotExist) && r.Count == 0: - r.Outcome = OutcomeAbsent + case err != nil && errors.Is(err, fs.ErrNotExist) && result.Count == 0: + result.Outcome = OutcomeAbsent case err != nil: - r.Outcome, r.Err = OutcomeError, err - case r.Failed > 0 && r.Count == 0: - r.Outcome, r.Err = OutcomeError, c.firstFail - case r.Failed > 0: - r.Outcome = OutcomePartial + result.Outcome, result.Err = OutcomeError, err + case result.Failed > 0 && result.Count == 0: + result.Outcome, result.Err = OutcomeError, c.firstFail + case result.Failed > 0: + result.Outcome = OutcomePartial default: - r.Outcome = OutcomeOK + result.Outcome = OutcomeOK } - return r + return result } // dirKeys retrieves a dir's keys on first use, for all its profiles; Go 1.20 has no sync.OnceValues. @@ -248,18 +248,18 @@ func (k *dirKeys) get(ctx context.Context) masterkey.Set { } // machineKeys asks this machine's secret stores; on macOS that includes the run's login keychain. -func machineKeys(kc masterkey.LoginKeychain) keySource { - return func(ctx context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error) { - loc, err := chromium.KeyLocator(dir, snap) +func machineKeys(keychain masterkey.LoginKeychain) masterKeyRetriever { + return func(ctx context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) { + locator, err := chromium.KeyLocator(dir, dirSnapshot) if err != nil { return nil, err } - loc.Keychain = kc - return masterkey.RetrieveAll(ctx, loc) + locator.Keychain = keychain + return masterkey.RetrieveAll(ctx, locator) } } -func dumpKeys(keys map[browser.DirID]masterkey.Set) keySource { +func dumpKeys(keys map[browser.UserDataDirID]masterkey.Set) masterKeyRetriever { return func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) (masterkey.Set, error) { return keys[dir.ID], nil } diff --git a/internal/app/execute_test.go b/internal/app/execute_test.go index ee2e8a4..11e877e 100644 --- a/internal/app/execute_test.go +++ b/internal/app/execute_test.go @@ -20,31 +20,31 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -var history = browser.Source{Paths: []string{"History"}} +var history = browser.FileSpec{Paths: []string{"History"}} -type extractFunc func(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error +type extractFunc func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error // fakeBase reads History for every category, so a test needs one fixture file per profile. -func fakeBase(fns map[category.Category]extractFunc) extractorsFunc { +func fakeBase(extractFuncs map[category.Category]extractFunc) extractorsFunc { return func(browser.UserDataDir, browser.Profile) browser.Extractors { - ex := make(browser.Extractors, len(fns)) - for c, fn := range fns { - ex[c] = browser.Extractor{Sources: []browser.Source{history}, Extract: fn} + extractors := make(browser.Extractors, len(extractFuncs)) + for dataCategory, extract := range extractFuncs { + extractors[dataCategory] = browser.Extractor{FileSpecs: []browser.FileSpec{history}, Extract: extract} } - return ex + return extractors } } -func noKeys(t *testing.T) keySource { +func noKeys(t *testing.T) masterKeyRetriever { return func(context.Context, browser.UserDataDir, snapshot.Snapshot) (masterkey.Set, error) { t.Error("keys were retrieved") return nil, nil } } -func chromeDir(t *testing.T, id browser.DirID, profiles ...string) browser.UserDataDir { +func chromeDir(t *testing.T, id browser.UserDataDirID, profiles ...string) browser.UserDataDir { t.Helper() - dir := browser.UserDataDir{ID: id, Def: lookup(t, "chrome"), Path: t.TempDir()} + 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, Dir: name}) @@ -52,18 +52,18 @@ func chromeDir(t *testing.T, id browser.DirID, profiles ...string) browser.UserD return dir } -func run(t *testing.T, base extractorsFunc, keys keySource, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) { +func run(t *testing.T, base extractorsFunc, keys masterKeyRetriever, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) { t.Helper() - req := Request{Categories: categories, Dir: t.TempDir()} - summary, err := execute(context.Background(), newPlan(Discovery{Dirs: dirs}, req, base), req, base, keys) + options := Options{Categories: categories, Dir: t.TempDir()} + summary, err := execute(context.Background(), newPlan(Discovery{Dirs: dirs}, options, base), options, base, keys) require.NoError(t, err) - return summary, req.Dir + return summary, options.Dir } -func outcomes(s Summary) map[category.Category]Result { +func outcomes(summary Summary) map[category.Category]Result { out := make(map[category.Category]Result) - for _, r := range s.Results { - out[r.Category] = r + for _, result := range summary.Results { + out[result.Category] = result } return out } @@ -104,9 +104,9 @@ func TestExecute_Outcomes(t *testing.T) { assert.Equal(t, 1, got[category.Cookie].Failed) 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 source is ok, not absent") + assert.Equal(t, OutcomeOK, got[category.History].Outcome, "an empty file is ok, not absent") assert.Equal(t, OutcomeError, got[category.Bookmark].Outcome) - assert.Equal(t, OutcomeAbsent, got[category.Download].Outcome, "a source that vanished after planning") + assert.Equal(t, OutcomeAbsent, got[category.Download].Outcome, "a file that vanished after planning") assert.Equal(t, OutcomeError, got[category.Extension].Outcome) data, err := os.ReadFile(filepath.Join(out, "extension.json")) @@ -114,23 +114,23 @@ func TestExecute_Outcomes(t *testing.T) { 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 stamps the browser's display name") + assert.Contains(t, string(data), `"browser": "Chrome"`, "the collector sets the browser's display name") assert.Contains(t, string(data), `"profile": "Default"`) } func TestExecute_KeysAreRetrievedOncePerUserDataDir(t *testing.T) { - cookie := func(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { - out.Add(&record.Cookie{Value: string(ps.MasterKeys(ctx)[masterkey.V10])}) + cookie := func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + out.Add(&record.Cookie{Value: string(profileSnapshot.MasterKeys(ctx)[masterkey.V10])}) return nil } - login := func(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { - out.Add(&record.Login{Password: string(ps.MasterKeys(ctx)[masterkey.V10])}) + login := func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + out.Add(&record.Login{Password: string(profileSnapshot.MasterKeys(ctx)[masterkey.V10])}) return nil } calls := 0 - keys := func(_ context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error) { + keys := func(_ context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) { calls++ - _, err := snap.Path("Default/History") + _, err := dirSnapshot.Path("Default/History") require.NoError(t, err, "keys are read from the dir's own snapshot") return masterkey.Set{masterkey.V10: []byte(dir.ID)}, errors.New("v20: no ABE") } @@ -141,19 +141,19 @@ func TestExecute_KeysAreRetrievedOncePerUserDataDir(t *testing.T) { assert.Equal(t, 1, calls) last := summary.Results[len(summary.Results)-1] - assert.Equal(t, Extraction{DirID: "chrome"}, last.Extraction, "a retrieval error is reported once, for the dir") + assert.Equal(t, Extraction{UserDataDirID: "chrome"}, last.Extraction, "a retrieval error is reported once, for the dir") assert.Equal(t, OutcomeError, last.Outcome) require.ErrorContains(t, last.Err, "v20: no ABE") assert.Len(t, summary.Results, 5) } -// A run that only asks for data without secrets never retrieves a key, so it never prompts on macOS. +// TestExecute_HistoryNeverRetrievesKeys checks data without secrets never retrieves a key, so never prompts on macOS. func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) { path := t.TempDir() touch(t, path, "Local State") touch(t, path, "Default", "History") touch(t, path, "Default", "Network", "Cookies") - dir := browser.UserDataDir{ID: "chrome", Def: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}} + dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}} run(t, extractorsWith(nil), noKeys(t), []category.Category{category.History, category.Download}, dir) @@ -169,12 +169,12 @@ func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) { func TestExecute_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) { var captured []string base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, ps browser.ProfileSnapshot, _ browser.Collector) error { + category.History: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, _ 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 := ps.Path(history) + path, err := profileSnapshot.Path(history) require.NoError(t, err) captured = append(captured, path) return nil @@ -194,8 +194,8 @@ func TestExecute_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testi defer cancel() var copied []string base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, ps browser.ProfileSnapshot, _ browser.Collector) error { - path, err := ps.Path(history) + category.History: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, _ browser.Collector) error { + path, err := profileSnapshot.Path(history) require.NoError(t, err) copied = append(copied, path) cancel() @@ -206,10 +206,10 @@ func TestExecute_StopEndsTheRunBeforeTheNextExtractionAndRemovesTheCopy(t *testi return nil }, }) - req := Request{Categories: []category.Category{category.History, category.Download}, Dir: t.TempDir()} - d := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default")}} + options := Options{Categories: []category.Category{category.History, category.Download}, Dir: t.TempDir()} + discovery := Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default")}} - _, err := execute(ctx, newPlan(d, req, base), req, base, noKeys(t)) + _, err := execute(ctx, newPlan(discovery, options, base), options, base, noKeys(t)) require.ErrorIs(t, err, context.Canceled) require.Len(t, copied, 1, "the next user data dir is never captured") _, statErr := os.Stat(copied[0]) @@ -222,18 +222,18 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { } var copied string base := fakeBase(map[category.Category]extractFunc{ - category.History: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { - copied, _ = ps.Path(history) + category.History: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + copied, _ = profileSnapshot.Path(history) out.Add(&record.History{URL: "https://example.com"}) return nil }, }) - req := Request{Categories: []category.Category{category.History}, Dir: t.TempDir()} - require.NoError(t, os.Chmod(req.Dir, 0o500)) - defer func() { require.NoError(t, os.Chmod(req.Dir, 0o700)) }() + options := Options{Categories: []category.Category{category.History}, Dir: t.TempDir()} + require.NoError(t, os.Chmod(options.Dir, 0o500)) + defer func() { require.NoError(t, os.Chmod(options.Dir, 0o700)) }() - plan := newPlan(Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default")}}, req, base) - _, err := execute(context.Background(), plan, req, base, noKeys(t)) + plan := newPlan(Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default")}}, options, base) + _, err := execute(context.Background(), plan, options, base, noKeys(t)) require.Error(t, err) require.NotEmpty(t, copied) _, statErr := os.Stat(copied) @@ -242,7 +242,7 @@ func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) { func TestExecute_DumpKeys(t *testing.T) { want := masterkey.Set{masterkey.V10: []byte("dumped")} - keys := dumpKeys(map[browser.DirID]masterkey.Set{"chrome": want}) + keys := dumpKeys(map[browser.UserDataDirID]masterkey.Set{"chrome": want}) got, err := keys(context.Background(), browser.UserDataDir{ID: "chrome"}, snapshot.Snapshot{}) require.NoError(t, err) assert.Equal(t, want, got) diff --git a/internal/app/extract_golden_test.go b/internal/app/extract_golden_test.go index 0b64044..ea48fce 100644 --- a/internal/app/extract_golden_test.go +++ b/internal/app/extract_golden_test.go @@ -16,16 +16,16 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// The fixtures' keys are handed in, since no secret store holds them. +// TestExtractGolden hands in the fixtures' keys, since no secret store holds them. func TestExtractGolden(t *testing.T) { home := t.TempDir() - keys := make(map[browser.DirID]masterkey.Set) - for _, inst := range browsertest.ChromiumInstalls { - def, ok := browser.Lookup(inst.Key) - require.True(t, ok, inst.Key) - require.Equal(t, inst.Name, def.Name, "records are stamped with the table's display name") - browsertest.ChromiumUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])), inst.Key) - keys[browser.DirID(inst.Key)] = browsertest.ChromiumKeys + keys := make(map[browser.UserDataDirID]masterkey.Set) + for _, fixture := range browsertest.ChromiumInstalls { + namedBrowser, ok := browser.Lookup(fixture.Name) + require.True(t, ok, fixture.Name) + require.Equal(t, fixture.DisplayName, namedBrowser.DisplayName, "records carry the table's display name") + browsertest.ChromiumUserData(t, filepath.Join(home, filepath.FromSlash(namedBrowser.Platform().UserDataDirs[0])), fixture.Name) + keys[browser.UserDataDirID(fixture.Name)] = browsertest.ChromiumKeys } assertExtractGoldens(t, "extract", func(t *testing.T, format string) string { @@ -35,9 +35,9 @@ func TestExtractGolden(t *testing.T) { func TestExtractGoldenFirefox(t *testing.T) { home := t.TempDir() - def, ok := browser.Lookup("firefox") + firefoxBrowser, ok := browser.Lookup("firefox") require.True(t, ok) - browsertest.FirefoxUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0]))) + browsertest.FirefoxUserData(t, filepath.Join(home, filepath.FromSlash(firefoxBrowser.Platform().UserDataDirs[0]))) assertExtractGoldens(t, "extract-firefox", func(t *testing.T, format string) string { return extractGoldenRun(t, home, nil, format) @@ -56,15 +56,15 @@ func TestExtractGoldenSafari(t *testing.T) { }) } -func extractGoldenRun(t *testing.T, home string, keys map[browser.DirID]masterkey.Set, format string) string { +func extractGoldenRun(t *testing.T, home string, keys map[browser.UserDataDirID]masterkey.Set, format string) string { t.Helper() out := t.TempDir() - req, err := app.Validate(app.Flags{Browser: "all", Categories: "all", Format: format, Dir: out}) + options, err := app.Validate(app.Flags{Browser: "all", Categories: "all", Format: format, Dir: out}) require.NoError(t, err) - req.Home, req.Keys = home, keys + options.Home, options.Keys = home, keys - plan := app.NewPlan(app.Discover(req), req) - _, err = app.Execute(context.Background(), plan, req) + plan := app.NewPlan(app.Discover(options), options) + _, err = app.Execute(context.Background(), plan, options) require.NoError(t, err) return out } @@ -80,16 +80,16 @@ var extractGoldenFormats = []struct { func assertExtractGoldens(t *testing.T, prefix string, run func(t *testing.T, format string) string) { t.Helper() - for _, tt := range extractGoldenFormats { - tt := tt - t.Run(tt.format, func(t *testing.T) { - out := run(t, tt.format) + for _, testCase := range extractGoldenFormats { + testCase := testCase + t.Run(testCase.format, func(t *testing.T) { + out := run(t, testCase.format) got := golden.Bundle(t, out) - if tt.jsonFallback { + if testCase.jsonFallback { golden.AssertJSONFallback(t, out, run(t, "json")) got = golden.BundleFiles(t, out, "cookie.json") } - golden.Assert(t, prefix+"-"+tt.format+".golden", got) + golden.Assert(t, prefix+"-"+testCase.format+".golden", got) }) } } diff --git a/internal/app/keychain_darwin.go b/internal/app/keychain_darwin.go index b79a986..2c44a12 100644 --- a/internal/app/keychain_darwin.go +++ b/internal/app/keychain_darwin.go @@ -14,12 +14,12 @@ import ( ) // loginKeychain builds the run's one login keychain without opening it, so a run that never decrypts never prompts. -func loginKeychain(req Request) runKeychain { - path := filepath.Join(req.Home, "Library", "Keychains", "login.keychain-db") - if req.KeychainPassword == nil { +func loginKeychain(options Options) runKeychain { + path := filepath.Join(options.Home, "Library", "Keychains", "login.keychain-db") + if options.KeychainPassword == nil { return keychain.New(path, func(context.Context) (string, error) { return "", nil }) } - return &reportedKeychain{Keychain: keychain.New(path, keychain.PasswordFunc(req.KeychainPassword))} + return &reportedKeychain{Keychain: keychain.New(path, keychain.PasswordFunc(options.KeychainPassword))} } // reportedKeychain says once why the keychain stayed locked, since every consumer then reads metadata only, quietly. diff --git a/internal/app/keychain_other.go b/internal/app/keychain_other.go index 668adb4..a14998a 100644 --- a/internal/app/keychain_other.go +++ b/internal/app/keychain_other.go @@ -2,4 +2,4 @@ package app -func loginKeychain(Request) runKeychain { return nil } +func loginKeychain(Options) runKeychain { return nil } diff --git a/internal/app/keys.go b/internal/app/keys.go index a9e4e89..51aec26 100644 --- a/internal/app/keys.go +++ b/internal/app/keys.go @@ -13,14 +13,14 @@ import ( // DumpKeys 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, so a stopped run writes no keys.json. -func DumpKeys(ctx context.Context, d Discovery, req Request) (masterkey.Dump, error) { - return dumpKeysWith(ctx, d, machineKeys(loginKeychain(req))) +func DumpKeys(ctx context.Context, discovery Discovery, options Options) (masterkey.Dump, error) { + return dumpKeysWith(ctx, discovery, machineKeys(loginKeychain(options))) } -func dumpKeysWith(ctx context.Context, d Discovery, keys keySource) (masterkey.Dump, error) { +func dumpKeysWith(ctx context.Context, discovery Discovery, keys masterKeyRetriever) (masterkey.Dump, error) { dump := masterkey.NewDump() - for _, dir := range d.Dirs { - if dir.Def.Base != browser.Chromium { + for _, dir := range discovery.Dirs { + if dir.Browser.Base != browser.Chromium { continue } set, err := retrieveKeys(ctx, dir, keys) @@ -32,48 +32,48 @@ func dumpKeysWith(ctx context.Context, d Discovery, keys keySource) (masterkey.D if len(set) == 0 { status = "failed" } - log.Warnf("dump-keys: %s %s: %v", dir.Def.Name, status, err) + log.Warnf("dump-keys: %s %s: %v", dir.Browser.DisplayName, status, err) } if len(set) == 0 { continue } - v := masterkey.Vault{ - Browser: dir.Def.ID, - Kind: chromium.VaultKind(dir.Def), + vault := masterkey.Vault{ + Browser: dir.Browser.Name, + Kind: chromium.VaultKind(dir.Browser), UserDataDir: dir.Path, Profiles: profileNames(dir), Keys: set, } - if string(dir.ID) != dir.Def.ID { - v.ID = string(dir.ID) + if string(dir.ID) != dir.Browser.Name { + vault.ID = string(dir.ID) } - dump.Vaults = append(dump.Vaults, v) + dump.Vaults = append(dump.Vaults, vault) } return dump, nil } -func retrieveKeys(ctx context.Context, dir browser.UserDataDir, keys keySource) (masterkey.Set, error) { - d, err := snapshot.Temp() +func retrieveKeys(ctx context.Context, dir browser.UserDataDir, keys masterKeyRetriever) (masterkey.Set, error) { + snapshotDir, err := snapshot.Temp() if err != nil { return nil, err } - defer closeSnapshot(d) + defer closeSnapshot(snapshotDir) var files []snapshot.File - for _, src := range chromium.KeySources(dir) { - if f, ok, err := firstOnDisk(dir, browser.Profile{}, src); err == nil && ok { - files = append(files, f) + for _, fileSpec := range chromium.KeyFileSpecs(dir) { + if file, ok, err := firstOnDisk(dir, browser.Profile{}, fileSpec); err == nil && ok { + files = append(files, file) } } - if err := d.Capture(ctx, files); err != nil { + if err := snapshotDir.Capture(ctx, files); err != nil { return nil, err } - return keys(ctx, dir, d.Snapshot(string(dir.ID))) + return keys(ctx, dir, snapshotDir.Snapshot(string(dir.ID))) } func profileNames(dir browser.UserDataDir) []string { names := make([]string, 0, len(dir.Profiles)) - for _, p := range dir.Profiles { - names = append(names, p.Name) + for _, profile := range dir.Profiles { + names = append(names, profile.Name) } return names } diff --git a/internal/app/keys_test.go b/internal/app/keys_test.go index 9b62dbe..b1f82c4 100644 --- a/internal/app/keys_test.go +++ b/internal/app/keys_test.go @@ -13,9 +13,9 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -func dirOf(t *testing.T, id browser.DirID, defID string) browser.UserDataDir { +func dirOf(t *testing.T, userDataDirID browser.UserDataDirID, browserName string) browser.UserDataDir { t.Helper() - dir := browser.UserDataDir{ID: id, Def: lookup(t, defID), Path: t.TempDir()} + dir := browser.UserDataDir{ID: userDataDirID, Browser: lookup(t, browserName), Path: t.TempDir()} dir.Profiles = []browser.Profile{{Name: "Default", Dir: "Default"}} return dir } @@ -26,10 +26,10 @@ func TestDumpKeys(t *testing.T) { 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") - keys := func(_ context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error) { + keys := func(_ context.Context, dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Set, error) { switch dir.ID { case "chrome": - _, err := snap.Path("Local State") + _, err := dirSnapshot.Path("Local State") require.NoError(t, err, "key retrieval reads the captured Local State") case "vivaldi": return nil, errors.New("v10 failed") @@ -40,8 +40,8 @@ func TestDumpKeys(t *testing.T) { } return masterkey.Set{masterkey.V10: []byte(dir.ID)}, nil } - d := Discovery{Dirs: []browser.UserDataDir{chrome, firefox, arc2, opera, vivaldi, brave}} - dump, err := dumpKeysWith(context.Background(), d, keys) + discovery := Discovery{Dirs: []browser.UserDataDir{chrome, firefox, arc2, opera, vivaldi, brave}} + dump, err := dumpKeysWith(context.Background(), discovery, keys) require.NoError(t, err) assert.Equal(t, []masterkey.Vault{ @@ -70,7 +70,7 @@ func TestDumpKeys_StoppedRunReturnsNoDump(t *testing.T) { chrome, brave := chromeDir(t, "chrome", "Default"), dirOf(t, "brave", "brave") touch(t, chrome.Path, "Local State") keys := func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) (masterkey.Set, error) { - require.Equal(t, browser.DirID("chrome"), dir.ID, "keys were retrieved after the stop") + require.Equal(t, browser.UserDataDirID("chrome"), dir.ID, "keys were retrieved after the stop") cancel() return masterkey.Set{masterkey.V10: []byte("chrome")}, nil } diff --git a/internal/app/password.go b/internal/app/password.go index ccba285..039776c 100644 --- a/internal/app/password.go +++ b/internal/app/password.go @@ -15,14 +15,14 @@ import ( var errNoPassword = errors.New("macOS login password not given and stdin is not a terminal") // keychainPassword is read lazily: a flag, else a no-echo prompt on a terminal, else none (metadata only). -func keychainPassword(f Flags, stdin *os.File) (func(context.Context) (string, error), error) { +func keychainPassword(flags Flags, stdin *os.File) (func(context.Context) (string, error), error) { switch { - case f.KeychainPassword != "" && f.KeychainPasswordStdin: + case flags.KeychainPassword != "" && flags.KeychainPasswordStdin: return nil, errors.New("--keychain-pw and --keychain-pw-stdin cannot be used together") - case f.KeychainPassword != "": - password := f.KeychainPassword + case flags.KeychainPassword != "": + password := flags.KeychainPassword return func(context.Context) (string, error) { return password, nil }, nil - case f.KeychainPasswordStdin: + case flags.KeychainPasswordStdin: return func(ctx context.Context) (string, error) { return untilDone(ctx, func() (string, error) { return firstLine(stdin) }) }, nil @@ -33,8 +33,8 @@ func keychainPassword(f Flags, stdin *os.File) (func(context.Context) (string, e } } -func firstLine(r io.Reader) (string, error) { - line, err := bufio.NewReader(r).ReadString('\n') +func firstLine(reader io.Reader) (string, error) { + line, err := bufio.NewReader(reader).ReadString('\n') if err != nil && !errors.Is(err, io.EOF) { return "", fmt.Errorf("read the password from stdin: %w", err) } @@ -42,19 +42,19 @@ func firstLine(r io.Reader) (string, error) { } func prompt(ctx context.Context, stdin *os.File) (string, error) { - fd := int(stdin.Fd()) - state, err := term.GetState(fd) + fileDescriptor := int(stdin.Fd()) + state, err := term.GetState(fileDescriptor) if err != nil { return "", fmt.Errorf("read the password: %w", err) } fmt.Fprint(os.Stderr, "Enter macOS login password: ") password, err := untilDone(ctx, func() (string, error) { - p, err := term.ReadPassword(fd) - return string(p), err + entered, err := term.ReadPassword(fileDescriptor) + return string(entered), err }) if ctx.Err() != nil { // The abandoned read never turns the echo back on, and the stop notice has already ended the line. - return "", errors.Join(ctx.Err(), term.Restore(fd, state)) + return "", errors.Join(ctx.Err(), term.Restore(fileDescriptor, state)) } fmt.Fprintln(os.Stderr) if err != nil { @@ -75,8 +75,8 @@ func untilDone(ctx context.Context, read func() (string, error)) (string, error) answers <- answer{value, err} }() select { - case a := <-answers: - return a.value, a.err + case reply := <-answers: + return reply.value, reply.err case <-ctx.Done(): return "", ctx.Err() } diff --git a/internal/app/plan.go b/internal/app/plan.go index 3463fa5..c4a269b 100644 --- a/internal/app/plan.go +++ b/internal/app/plan.go @@ -13,9 +13,9 @@ import ( // Extraction is plain data, looked up again when it runs, so a Plan prints as it is and compares with DeepEqual. type Extraction struct { - DirID browser.DirID - Profile string // Profile.Name; "" in a result about a whole user data dir - Category category.Category // zero in a result about a whole user data dir + UserDataDirID browser.UserDataDirID + Profile string // Profile.Name; "" in a result about a whole user data dir + Category category.Category // zero in a result about a whole user data dir } // Plan lists extractions in output order, each file to capture once, and the requested extractions that cannot run. @@ -28,75 +28,77 @@ type Plan struct { type extractorsFunc func(browser.UserDataDir, browser.Profile) browser.Extractors -// NewPlan only stats files and reads only the extractors' sources, so it opens nothing and needs no keychain. -func NewPlan(d Discovery, req Request) Plan { - return newPlan(d, req, extractorsWith(nil)) +// NewPlan only stats the files the extractors' file specs name, so it opens nothing and needs no keychain. +func NewPlan(discovery Discovery, options Options) Plan { + return newPlan(discovery, options, extractorsWith(nil)) } -func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan { - p := Plan{Dirs: d.Dirs, Skipped: append([]Result(nil), d.Failed...)} +func newPlan(discovery Discovery, options Options, extractors extractorsFunc) Plan { + plan := Plan{Dirs: discovery.Dirs, Skipped: append([]Result(nil), discovery.Failed...)} captured := make(map[snapshot.File]bool) - for _, dir := range d.Dirs { - for _, prof := range dir.Profiles { - ex := extractors(dir, prof) - for _, c := range req.Categories { - e := Extraction{DirID: dir.ID, Profile: prof.Name, Category: c} - x, ok := ex[c] + for _, dir := range discovery.Dirs { + for _, profile := range dir.Profiles { + profileExtractors := extractors(dir, profile) + for _, dataCategory := range options.Categories { + extraction := Extraction{UserDataDirID: dir.ID, Profile: profile.Name, Category: dataCategory} + extractor, ok := profileExtractors[dataCategory] if !ok { - p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeUnsupported}) + plan.Skipped = append(plan.Skipped, Result{Extraction: extraction, Outcome: OutcomeUnsupported}) continue } - files, ok, err := locate(dir, prof, x.Sources) + files, ok, err := locate(dir, profile, extractor.FileSpecs) if err != nil { - p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeError, Err: err}) + plan.Skipped = append(plan.Skipped, Result{Extraction: extraction, Outcome: OutcomeError, Err: err}) continue } if !ok { - p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeAbsent}) + plan.Skipped = append(plan.Skipped, Result{Extraction: extraction, Outcome: OutcomeAbsent}) continue } - p.Extractions = append(p.Extractions, e) - for _, f := range files { - if !captured[f] { - captured[f] = true - p.Files = append(p.Files, f) + plan.Extractions = append(plan.Extractions, extraction) + for _, file := range files { + if !captured[file] { + captured[file] = true + plan.Files = append(plan.Files, file) } } } } } - return p + return plan } -// An extraction needs every required source and one of the profile's own: Local State alone never makes it present. +// locate needs every required file and one of the profile's own: Local State alone never makes an extraction present. // One that reads no file always runs, and a candidate that cannot be checked is an error, not absence. -func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool, error) { - if len(sources) == 0 { +func locate(dir browser.UserDataDir, profile browser.Profile, fileSpecs []browser.FileSpec) ([]snapshot.File, bool, error) { + if len(fileSpecs) == 0 { return nil, true, nil } var files []snapshot.File present := false - for _, src := range sources { - f, ok, err := firstOnDisk(dir, p, src) + for _, fileSpec := range fileSpecs { + file, ok, err := firstOnDisk(dir, profile, fileSpec) switch { case err != nil: return nil, false, err case ok: - files = append(files, f) - present = present || !src.Shared - case !src.Optional: + files = append(files, file) + present = present || !fileSpec.Shared + case !fileSpec.Optional: return nil, false, nil } } return files, present, nil } -func firstOnDisk(dir browser.UserDataDir, p browser.Profile, src browser.Source) (snapshot.File, bool, error) { - for _, rel := range src.Candidates(p) { - info, err := os.Stat(filepath.Join(dir.Path, filepath.FromSlash(rel))) +func firstOnDisk(dir browser.UserDataDir, profile browser.Profile, fileSpec browser.FileSpec) (snapshot.File, bool, error) { + for _, relativePath := range fileSpec.CandidatePaths(profile) { + info, err := os.Stat(filepath.Join(dir.Path, filepath.FromSlash(relativePath))) switch { - case err == nil && info.IsDir() == src.IsDir: - return snapshot.File{DirID: string(dir.ID), From: dir.Path, Rel: rel, IsDir: src.IsDir}, true, nil + case err == nil && info.IsDir() == fileSpec.IsDir: + return snapshot.File{ + UserDataDirID: string(dir.ID), UserDataDirPath: dir.Path, RelativePath: relativePath, IsDir: fileSpec.IsDir, + }, true, nil case err != nil && !errors.Is(err, fs.ErrNotExist): return snapshot.File{}, false, err } diff --git a/internal/app/plan_test.go b/internal/app/plan_test.go index e585085..b239e94 100644 --- a/internal/app/plan_test.go +++ b/internal/app/plan_test.go @@ -23,11 +23,11 @@ func touch(t *testing.T, parts ...string) { require.NoError(t, os.WriteFile(path, []byte("{}"), 0o600)) } -func lookup(t *testing.T, id string) browser.Def { +func lookup(t *testing.T, name string) browser.Browser { t.Helper() - def, ok := browser.Lookup(id) - require.True(t, ok, id) - return def + namedBrowser, ok := browser.Lookup(name) + require.True(t, ok, name) + return namedBrowser } func TestNewPlan(t *testing.T) { @@ -38,20 +38,22 @@ func TestNewPlan(t *testing.T) { touch(t, path, "Default", "History") touch(t, path, "Profile 1", "History") dir := browser.UserDataDir{ - ID: "chrome", Def: lookup(t, "chrome"), Path: path, + ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}, {Name: "Profile 1", Dir: "Profile 1"}}, } failed := dirFailure("edge", errors.New("permission denied")) - req := Request{Categories: []category.Category{category.Password, category.Cookie, category.History, category.Download, category.CreditCard}} + options := Options{Categories: []category.Category{category.Password, category.Cookie, category.History, category.Download, category.CreditCard}} - got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}, Failed: []Result{failed}}, req) + got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}, Failed: []Result{failed}}, options) - file := func(rel string) snapshot.File { return snapshot.File{DirID: "chrome", From: path, Rel: rel} } - extraction := func(profile string, c category.Category) Extraction { - return Extraction{DirID: "chrome", Profile: profile, Category: c} + file := func(relativePath string) snapshot.File { + return snapshot.File{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: relativePath} } - skipped := func(profile string, c category.Category, o Outcome) Result { - return Result{Extraction: extraction(profile, c), Outcome: o} + extraction := func(profile string, dataCategory category.Category) Extraction { + return Extraction{UserDataDirID: "chrome", Profile: profile, Category: dataCategory} + } + skipped := func(profile string, dataCategory category.Category, outcome Outcome) Result { + return Result{Extraction: extraction(profile, dataCategory), Outcome: outcome} } assert.Equal(t, Plan{ Dirs: []browser.UserDataDir{dir}, @@ -79,41 +81,41 @@ func TestNewPlan(t *testing.T) { func TestNewPlan_PicksTheFirstCandidateOnDisk(t *testing.T) { path := t.TempDir() touch(t, path, "Default", "Cookies") - dir := browser.UserDataDir{ID: "chrome", Def: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}} + dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}} - got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.Cookie}}) - assert.Equal(t, []snapshot.File{{DirID: "chrome", From: path, Rel: "Default/Cookies"}}, got.Files) + got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.Cookie}}) + assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Cookies"}}, got.Files) } func TestNewPlan_FlatLayoutProfile(t *testing.T) { path := t.TempDir() touch(t, path, "History") - dir := browser.UserDataDir{ID: "opera", Def: lookup(t, "opera"), Path: path, Profiles: []browser.Profile{{Name: "Opera Stable"}}} + dir := browser.UserDataDir{ID: "opera", Browser: lookup(t, "opera"), Path: path, Profiles: []browser.Profile{{Name: "Opera Stable"}}} - got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.History}}) - assert.Equal(t, []snapshot.File{{DirID: "opera", From: path, Rel: "History"}}, got.Files) - assert.Equal(t, []Extraction{{DirID: "opera", Profile: "Opera Stable", Category: category.History}}, got.Extractions) + got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.History}}) + assert.Equal(t, []snapshot.File{{UserDataDirID: "opera", UserDataDirPath: path, RelativePath: "History"}}, got.Files) + assert.Equal(t, []Extraction{{UserDataDirID: "opera", Profile: "Opera Stable", Category: category.History}}, got.Extractions) } func TestNewPlan_UnsupportedCategory(t *testing.T) { dir := browser.UserDataDir{ID: "x", Path: t.TempDir(), Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}} none := func(browser.UserDataDir, browser.Profile) browser.Extractors { return browser.Extractors{} } - got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.CreditCard}}, none) - assert.Equal(t, []Result{{Extraction: Extraction{DirID: "x", Profile: "Default", Category: category.CreditCard}, Outcome: OutcomeUnsupported}}, + got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.CreditCard}}, none) + assert.Equal(t, []Result{{Extraction: Extraction{UserDataDirID: "x", Profile: "Default", Category: category.CreditCard}, Outcome: OutcomeUnsupported}}, got.Skipped) assert.Empty(t, got.Extractions) } -// Safari's passwords come from the keychain: an extractor that reads no file is never absent. -func TestNewPlan_ExtractorWithoutSourcesRuns(t *testing.T) { +// TestNewPlan_ExtractorWithoutFileSpecsRuns covers Safari's passwords: read from the keychain, they are never absent. +func TestNewPlan_ExtractorWithoutFileSpecsRuns(t *testing.T) { dir := browser.UserDataDir{ID: "safari", Path: t.TempDir(), Profiles: []browser.Profile{{Name: "default", Dir: "Safari"}}} keychainOnly := func(browser.UserDataDir, browser.Profile) browser.Extractors { return browser.Extractors{category.Password: {}} } - got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.Password}}, keychainOnly) - assert.Equal(t, []Extraction{{DirID: "safari", Profile: "default", Category: category.Password}}, got.Extractions) + got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.Password}}, keychainOnly) + assert.Equal(t, []Extraction{{UserDataDirID: "safari", Profile: "default", Category: category.Password}}, got.Extractions) assert.Empty(t, got.Files) assert.Empty(t, got.Skipped) } @@ -131,12 +133,12 @@ func lock(t *testing.T, dir string) { t.Cleanup(func() { assert.NoError(t, os.Chmod(dir, 0o700)) }) } -func TestNewPlan_UnreadableSourceIsAnError(t *testing.T) { +func TestNewPlan_UnreadableFileIsAnError(t *testing.T) { dir := chromeDir(t, "chrome", "Default") lock(t, filepath.Join(dir.Path, "Default")) base := fakeBase(map[category.Category]extractFunc{category.History: nil}) - got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.History}}, base) + got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Options{Categories: []category.Category{category.History}}, base) require.Len(t, got.Skipped, 1) assert.Equal(t, OutcomeError, got.Skipped[0].Outcome) diff --git a/internal/app/report.go b/internal/app/report.go index 33d9318..93d980e 100644 --- a/internal/app/report.go +++ b/internal/app/report.go @@ -6,29 +6,29 @@ import ( "text/tabwriter" ) -// The summary is not part of the output contract and never changes the exit status. -func Report(w io.Writer, s Summary) error { - tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) - fmt.Fprintln(tw, "Browser\tProfile\tCategory\tResult\tRecords\tDetail") - for _, r := range s.Results { +// Report prints a summary that is not part of the output contract and never changes the exit status. +func Report(writer io.Writer, summary Summary) error { + table := tabwriter.NewWriter(writer, 0, 0, 2, ' ', 0) + fmt.Fprintln(table, "Browser\tProfile\tCategory\tResult\tRecords\tDetail") + for _, result := range summary.Results { profile, cat := "-", "-" - if r.Profile != "" { - profile = r.Profile + if result.Profile != "" { + profile = result.Profile } - if r.Category != 0 { - cat = r.Category.String() + if result.Category != 0 { + cat = result.Category.String() } - fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%d\t%s\n", r.DirID, profile, cat, r.Outcome, r.Count, detail(r)) + fmt.Fprintf(table, "%s\t%s\t%s\t%s\t%d\t%s\n", result.UserDataDirID, profile, cat, result.Outcome, result.Count, detail(result)) } - return tw.Flush() + return table.Flush() } -func detail(r Result) string { +func detail(result Result) string { switch { - case r.Err != nil: - return r.Err.Error() - case r.Failed > 0: - return fmt.Sprintf("%d not recovered", r.Failed) + case result.Err != nil: + return result.Err.Error() + case result.Failed > 0: + return fmt.Sprintf("%d not recovered", result.Failed) default: return "" } diff --git a/internal/app/report_test.go b/internal/app/report_test.go index a4daa4c..c924ac3 100644 --- a/internal/app/report_test.go +++ b/internal/app/report_test.go @@ -13,15 +13,15 @@ import ( ) func TestReport(t *testing.T) { - cookie := Extraction{DirID: "chrome", Profile: "Default", Category: category.Cookie} - var buf bytes.Buffer - require.NoError(t, Report(&buf, Summary{Results: []Result{ + cookie := Extraction{UserDataDirID: "chrome", Profile: "Default", Category: category.Cookie} + var buffer bytes.Buffer + require.NoError(t, Report(&buffer, Summary{Results: []Result{ {Extraction: cookie, Outcome: OutcomePartial, Count: 224, Failed: 4}, dirFailure("arc-2", errors.New("permission denied")), - {Extraction: Extraction{DirID: "edge", Profile: "Default", Category: category.Password}}, + {Extraction: Extraction{UserDataDirID: "edge", Profile: "Default", Category: category.Password}}, }})) - lines := strings.Split(strings.TrimSpace(buf.String()), "\n") + lines := strings.Split(strings.TrimSpace(buffer.String()), "\n") require.Len(t, lines, 4) assert.Equal(t, []string{"chrome", "Default", "cookie", "partial", "224", "4", "not", "recovered"}, strings.Fields(lines[1])) assert.Equal(t, []string{"arc-2", "-", "-", "error", "0", "permission", "denied"}, strings.Fields(lines[2])) diff --git a/internal/app/restore.go b/internal/app/restore.go index 302b3ee..5244217 100644 --- a/internal/app/restore.go +++ b/internal/app/restore.go @@ -30,40 +30,40 @@ type RestoreFlags struct { // ValidateRestore checks restore's flags and reads its keys before any data is opened. A restore's browsers are the // dump's vaults, not this OS's table, so -b is checked against them. -func ValidateRestore(f RestoreFlags) (Request, masterkey.Dump, error) { - if f.Keys == "" { - return Request{}, masterkey.Dump{}, errors.New("requires --keys (or - for stdin)") +func ValidateRestore(flags RestoreFlags) (Options, masterkey.Dump, error) { + if flags.Keys == "" { + return Options{}, masterkey.Dump{}, errors.New("requires --keys (or - for stdin)") } - if (f.DataDir == "") == (f.DataZip == "") { - return Request{}, masterkey.Dump{}, errors.New("exactly one of --data-dir or --data-zip is required") + if (flags.DataDir == "") == (flags.DataZip == "") { + return Options{}, masterkey.Dump{}, errors.New("exactly one of --data-dir or --data-zip is required") } - categories, err := parseCategories(f.Categories) + categories, err := parseCategories(flags.Categories) if err != nil { - return Request{}, masterkey.Dump{}, err + return Options{}, masterkey.Dump{}, err } - format, err := export.ParseFormat(f.Format) + format, err := export.ParseFormat(flags.Format) if err != nil { - return Request{}, masterkey.Dump{}, err + return Options{}, masterkey.Dump{}, err } - if err := checkOutputDir(f.Dir); err != nil { - return Request{}, masterkey.Dump{}, err + if err := checkOutputDir(flags.Dir); err != nil { + return Options{}, masterkey.Dump{}, err } - if err := checkRestoreData(f.DataDir, f.DataZip); err != nil { - return Request{}, masterkey.Dump{}, err + if err := checkRestoreData(flags.DataDir, flags.DataZip); err != nil { + return Options{}, masterkey.Dump{}, err } - dump, err := readKeys(f.Keys) + dump, err := readKeys(flags.Keys) if err != nil { - return Request{}, masterkey.Dump{}, err + return Options{}, masterkey.Dump{}, err } - filter := strings.ToLower(strings.TrimSpace(f.Browser)) + filter := strings.ToLower(strings.TrimSpace(flags.Browser)) if filter == "" { filter = allBrowsers } if filter != allBrowsers && len(vaultsOf(dump, filter)) == 0 { - return Request{}, masterkey.Dump{}, fmt.Errorf("no vault for browser %q in keys (have: %s)", filter, vaultKeys(dump.Vaults)) + return Options{}, masterkey.Dump{}, fmt.Errorf("no vault for browser %q in keys (have: %s)", filter, vaultKeys(dump.Vaults)) } - req := Request{Browser: filter, Categories: categories, Format: format, Dir: f.Dir, Zip: f.Zip} - return req, dump, nil + options := Options{Browser: filter, Categories: categories, Format: format, Dir: flags.Dir, Zip: flags.Zip} + return options, dump, nil } func checkRestoreData(dataDir, dataZip string) error { @@ -80,16 +80,16 @@ func checkRestoreData(dataDir, dataZip string) error { } func readKeys(path string) (masterkey.Dump, error) { - var r io.Reader = os.Stdin + var reader io.Reader = os.Stdin if path != "-" { - f, err := os.Open(path) + file, err := os.Open(path) if err != nil { return masterkey.Dump{}, fmt.Errorf("open keys file %q: %w", path, err) } - defer f.Close() - r = f + defer file.Close() + reader = file } - dump, err := masterkey.ReadJSON(r) + dump, err := masterkey.ReadJSON(reader) if err != nil { return masterkey.Dump{}, fmt.Errorf("read keys file %q: %w", path, err) } @@ -98,78 +98,84 @@ func readKeys(path string) (masterkey.Dump, error) { // RestoreDiscovery rebuilds the user data dirs in data, and their keys from dump: from the manifest when data has one, // else by today's rules, where the vaults' keys name subdirectories or data is one browser's User Data. -func RestoreDiscovery(data *snapshot.Dir, dump masterkey.Dump, req Request) (Discovery, map[browser.DirID]masterkey.Set, error) { - vaults := vaultsOf(dump, req.Browser) - m, ok, err := data.ReadManifest() +func RestoreDiscovery( + data *snapshot.Dir, dump masterkey.Dump, options Options, +) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) { + vaults := vaultsOf(dump, options.Browser) + manifest, ok, err := data.ReadManifest() if err != nil { return Discovery{}, nil, err } if ok { - d, keys := fromManifest(data.Path(), m, vaults, req.Browser) - return d, keys, nil + discovery, keys := fromManifest(data.Path(), manifest, vaults, options.Browser) + return discovery, keys, nil } return fromLayout(data.Path(), vaults) } -func fromManifest(root string, m snapshot.Manifest, vaults []masterkey.Vault, filter string) (Discovery, map[browser.DirID]masterkey.Set) { - var d Discovery - keys := make(map[browser.DirID]masterkey.Set) - for _, md := range m.Dirs { - if filter != allBrowsers && md.Browser != filter { +func fromManifest( + root string, manifest snapshot.Manifest, vaults []masterkey.Vault, filter string, +) (Discovery, map[browser.UserDataDirID]masterkey.Set) { + var discovery Discovery + keys := make(map[browser.UserDataDirID]masterkey.Set) + for _, manifestEntry := range manifest.Dirs { + if filter != allBrowsers && manifestEntry.Browser != filter { continue } - v, ok := vaultOf(vaults, md) + vault, ok := vaultOf(vaults, manifestEntry) if !ok { - log.Warnf("restore: %s has no keys, skipping", md.ID) + log.Warnf("restore: %s has no keys, skipping", manifestEntry.ID) continue } - dir, err := manifestDir(root, md, v) + dir, err := manifestDir(root, manifestEntry, vault) if err != nil { - log.Warnf("restore: %s: %v", md.ID, err) + log.Warnf("restore: %s: %v", manifestEntry.ID, err) continue } - d.Dirs = append(d.Dirs, dir) - keys[dir.ID] = v.Keys + discovery.Dirs = append(discovery.Dirs, dir) + keys[dir.ID] = vault.Keys } - return d, keys + return discovery, keys } -// vaultOf finds md's keys: the vault carrying its ID, or for a browser's first dir the vault of that browser. -func vaultOf(vaults []masterkey.Vault, md snapshot.ManifestDir) (masterkey.Vault, bool) { - for _, v := range vaults { - if vaultDirID(v) == browser.DirID(md.ID) { - return v, true +// vaultOf finds an entry's keys: the vault carrying its ID, or for a browser's first dir the vault of that browser. +func vaultOf(vaults []masterkey.Vault, manifestEntry snapshot.ManifestDir) (masterkey.Vault, bool) { + for _, vault := range vaults { + if vaultUserDataDirID(vault) == browser.UserDataDirID(manifestEntry.ID) { + return vault, true } } return masterkey.Vault{}, false } // manifestDir trusts no path in the manifest that would leave its own directory of the archive. -func manifestDir(root string, md snapshot.ManifestDir, v masterkey.Vault) (browser.UserDataDir, error) { - if md.Base != browser.Chromium.String() { - return browser.UserDataDir{}, fmt.Errorf("base %q is not restorable", md.Base) +func manifestDir(root string, manifestEntry snapshot.ManifestDir, vault masterkey.Vault) (browser.UserDataDir, error) { + if manifestEntry.Base != browser.Chromium.String() { + return browser.UserDataDir{}, fmt.Errorf("base %q is not restorable", manifestEntry.Base) } - if !isPathElement(md.ID) { - return browser.UserDataDir{}, fmt.Errorf("id %q is not a directory name", md.ID) + if !isPathElement(manifestEntry.ID) { + return browser.UserDataDir{}, fmt.Errorf("id %q is not a directory name", manifestEntry.ID) } - def, err := vaultDef(v) + restoredBrowser, err := vaultBrowser(vault) if err != nil { return browser.UserDataDir{}, err } - dir := browser.UserDataDir{ID: browser.DirID(md.ID), Def: def, Path: filepath.Join(root, md.ID)} - for _, p := range md.Profiles { - if p.Dir != "" && !filepath.IsLocal(filepath.FromSlash(p.Dir)) { - return browser.UserDataDir{}, fmt.Errorf("profile dir %q is outside the archive", p.Dir) + dir := browser.UserDataDir{ + ID: browser.UserDataDirID(manifestEntry.ID), Browser: restoredBrowser, Path: filepath.Join(root, manifestEntry.ID), + } + for _, manifestProfile := range manifestEntry.Profiles { + if manifestProfile.Dir != "" && !filepath.IsLocal(filepath.FromSlash(manifestProfile.Dir)) { + return browser.UserDataDir{}, fmt.Errorf("profile dir %q is outside the archive", manifestProfile.Dir) } - dir.Profiles = append(dir.Profiles, browser.Profile{Name: p.Name, Dir: p.Dir}) + dir.Profiles = append(dir.Profiles, browser.Profile{Name: manifestProfile.Name, Dir: manifestProfile.Dir}) } return dir, nil } -func fromLayout(root string, vaults []masterkey.Vault) (Discovery, map[browser.DirID]masterkey.Set, error) { +func fromLayout(root string, vaults []masterkey.Vault) (Discovery, map[browser.UserDataDirID]masterkey.Set, error) { archived := false - for _, v := range vaults { - if dirExists(filepath.Join(root, string(vaultDirID(v)))) { + for _, vault := range vaults { + if dirExists(filepath.Join(root, string(vaultUserDataDirID(vault)))) { archived = true break } @@ -179,11 +185,11 @@ func fromLayout(root string, vaults []masterkey.Vault) (Discovery, map[browser.D "point it at the archive root, or use -b for one browser's User Data (have: %s)", root, len(vaults), vaultKeys(vaults)) } - var d Discovery - keys := make(map[browser.DirID]masterkey.Set) - for _, v := range vaults { - id := vaultDirID(v) - if _, dup := keys[id]; dup { + var discovery Discovery + keys := make(map[browser.UserDataDirID]masterkey.Set) + for _, vault := range vaults { + id := vaultUserDataDirID(vault) + if _, duplicate := keys[id]; duplicate { log.Warnf("restore: keys hold %s twice, restoring the first", id) continue } @@ -191,27 +197,27 @@ func fromLayout(root string, vaults []masterkey.Vault) (Discovery, map[browser.D if archived { path = filepath.Join(root, string(id)) if !dirExists(path) { - log.Warnf("restore: %s has no data under %s, skipping", v.Browser, path) + log.Warnf("restore: %s has no data under %s, skipping", vault.Browser, path) continue } } - dir, err := layoutDir(v, id, path) + dir, err := layoutDir(vault, id, path) if err != nil { - log.Warnf("restore: %s: %v", v.Browser, err) + log.Warnf("restore: %s: %v", vault.Browser, err) continue } - d.Dirs = append(d.Dirs, dir) - keys[id] = v.Keys + discovery.Dirs = append(discovery.Dirs, dir) + keys[id] = vault.Keys } - return d, keys, nil + return discovery, keys, nil } -func layoutDir(v masterkey.Vault, id browser.DirID, path string) (browser.UserDataDir, error) { - def, err := vaultDef(v) +func layoutDir(vault masterkey.Vault, id browser.UserDataDirID, path string) (browser.UserDataDir, error) { + restoredBrowser, err := vaultBrowser(vault) if err != nil { return browser.UserDataDir{}, err } - dir, err := chromium.DiscoverAt(def, id, path) + dir, err := chromium.DiscoverAt(restoredBrowser, id, path) if err != nil { return browser.UserDataDir{}, fmt.Errorf("read %s: %w", path, err) } @@ -222,33 +228,33 @@ func layoutDir(v masterkey.Vault, id browser.DirID, path string) (browser.UserDa return found[0], nil } -// vaultDef finds a vault's browser in the whole table, so a fork this OS lacks still restores. A key this build does -// not know restores as it always did: the vault's kind picks the on-disk format, and the key is stamped as the browser. -func vaultDef(v masterkey.Vault) (browser.Def, error) { - key := strings.ToLower(v.Browser) - if def, ok := browser.Lookup(key); ok && def.Base == browser.Chromium { - return def, nil +// vaultBrowser searches the whole table, so a fork this OS lacks still restores. A browser this build does not know +// restores as it always did: the vault's kind picks the on-disk format, and its name stands in as the browser. +func vaultBrowser(vault masterkey.Vault) (browser.Browser, error) { + name := strings.ToLower(vault.Browser) + if namedBrowser, ok := browser.Lookup(name); ok && namedBrowser.Base == browser.Chromium { + return namedBrowser, nil } - id, err := chromium.FormatID(v.Kind, key) + formatName, err := chromium.FormatName(vault.Kind, name) if err != nil { - return browser.Def{}, err + return browser.Browser{}, err } - return browser.Def{ID: id, Name: v.Browser, Base: browser.Chromium}, nil + return browser.Browser{Name: formatName, DisplayName: vault.Browser, Base: browser.Chromium}, nil } -// vaultDirID is the vault's directory in an archive: its ID for a second user data dir, else its browser key. -func vaultDirID(v masterkey.Vault) browser.DirID { - if v.ID != "" { - return browser.DirID(v.ID) +// 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 { + if vault.ID != "" { + return browser.UserDataDirID(vault.ID) } - return browser.DirID(strings.ToLower(v.Browser)) + return browser.UserDataDirID(strings.ToLower(vault.Browser)) } func vaultsOf(dump masterkey.Dump, filter string) []masterkey.Vault { var out []masterkey.Vault - for _, v := range dump.Vaults { - if filter == allBrowsers || strings.EqualFold(v.Browser, filter) { - out = append(out, v) + for _, vault := range dump.Vaults { + if filter == allBrowsers || strings.EqualFold(vault.Browser, filter) { + out = append(out, vault) } } return out @@ -256,8 +262,8 @@ func vaultsOf(dump masterkey.Dump, filter string) []masterkey.Vault { func vaultKeys(vaults []masterkey.Vault) string { keys := make([]string, 0, len(vaults)) - for _, v := range vaults { - keys = append(keys, strings.ToLower(v.Browser)) + for _, vault := range vaults { + keys = append(keys, strings.ToLower(vault.Browser)) } return strings.Join(keys, ", ") } diff --git a/internal/app/restore_golden_test.go b/internal/app/restore_golden_test.go index 173f245..2b2f954 100644 --- a/internal/app/restore_golden_test.go +++ b/internal/app/restore_golden_test.go @@ -19,7 +19,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// Restore writes what dump writes: the extract golden, stamped with each browser's display name. +// TestRestoreGolden checks that restore writes what dump writes: the extract golden, with each browser's display name. func TestRestoreGolden(t *testing.T) { data := t.TempDir() browsertest.ChromiumInstallations(t, data) @@ -61,8 +61,8 @@ func TestRestoreGolden(t *testing.T) { func chromiumFixtureKeysFile(t *testing.T) string { t.Helper() profiles := make([]string, 0, len(browsertest.ChromiumProfiles)) - for _, p := range browsertest.ChromiumProfiles { - profiles = append(profiles, p.Dir) + for _, fixtureProfile := range browsertest.ChromiumProfiles { + profiles = append(profiles, fixtureProfile.Dir) } dump := masterkey.Dump{ // A literal rather than DumpVersion: keys files written by today's dumpkeys must keep restoring. @@ -71,44 +71,44 @@ func chromiumFixtureKeysFile(t *testing.T) string { Host: masterkey.Host{OS: "windows", Arch: "amd64"}, Vaults: []masterkey.Vault{}, } - for _, inst := range browsertest.ChromiumInstalls { + for _, fixture := range browsertest.ChromiumInstalls { dump.Vaults = append(dump.Vaults, masterkey.Vault{ - Browser: inst.Key, + Browser: fixture.Name, Kind: "chromium", Profiles: profiles, Keys: browsertest.ChromiumKeys, }) } - var buf bytes.Buffer - require.NoError(t, dump.WriteJSON(&buf)) + var buffer bytes.Buffer + require.NoError(t, dump.WriteJSON(&buffer)) path := filepath.Join(t.TempDir(), "keys.json") - require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) + require.NoError(t, os.WriteFile(path, buffer.Bytes(), 0o600)) return path } -func restoreGolden(t *testing.T, f app.RestoreFlags) string { +func restoreGolden(t *testing.T, flags app.RestoreFlags) string { t.Helper() - if f.Categories == "" { - f.Categories = "all" + if flags.Categories == "" { + flags.Categories = "all" } - if f.Format == "" { - f.Format = "json" + if flags.Format == "" { + flags.Format = "json" } - req, dump, err := app.ValidateRestore(f) + options, dump, err := app.ValidateRestore(flags) require.NoError(t, err) - data := snapshot.Open(f.DataDir) - if f.DataZip != "" { - data, err = snapshot.Unzip(f.DataZip) + data := snapshot.Open(flags.DataDir) + if flags.DataZip != "" { + data, err = snapshot.Unzip(flags.DataZip) require.NoError(t, err) } defer data.Close() - d, keys, err := app.RestoreDiscovery(data, dump, req) + discovery, keys, err := app.RestoreDiscovery(data, dump, options) require.NoError(t, err) - req.Keys = keys - _, err = app.Execute(context.Background(), app.NewPlan(d, req), req) + options.Keys = keys + _, err = app.Execute(context.Background(), app.NewPlan(discovery, options), options) require.NoError(t, err) - return f.Dir + return flags.Dir } diff --git a/internal/app/restore_test.go b/internal/app/restore_test.go index d536a37..711df9e 100644 --- a/internal/app/restore_test.go +++ b/internal/app/restore_test.go @@ -18,45 +18,45 @@ func keysFile(t *testing.T, vaults ...masterkey.Vault) string { t.Helper() dump := masterkey.NewDump() dump.Vaults = append(dump.Vaults, vaults...) - var buf bytes.Buffer - require.NoError(t, dump.WriteJSON(&buf)) + var buffer bytes.Buffer + require.NoError(t, dump.WriteJSON(&buffer)) path := filepath.Join(t.TempDir(), "keys.json") - require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) + require.NoError(t, os.WriteFile(path, buffer.Bytes(), 0o600)) return path } -func vault(browserKey string) masterkey.Vault { - return masterkey.Vault{Browser: browserKey, Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte(browserKey)}} +func testVault(browserName string) masterkey.Vault { + return masterkey.Vault{Browser: browserName, Kind: "chromium", Keys: masterkey.Set{masterkey.V10: []byte(browserName)}} } -func layoutProfile(t *testing.T, root, rel string) { +func layoutProfile(t *testing.T, root, relativePath string) { t.Helper() - touch(t, root, filepath.FromSlash(rel), "Default", "Preferences") - touch(t, root, filepath.FromSlash(rel), "Default", "History") + touch(t, root, filepath.FromSlash(relativePath), "Default", "Preferences") + touch(t, root, filepath.FromSlash(relativePath), "Default", "History") } func TestValidateRestore_RejectsBadInput(t *testing.T) { - keys := keysFile(t, vault("chrome")) + keys := keysFile(t, testVault("chrome")) data := t.TempDir() base := RestoreFlags{Keys: keys, DataDir: data, Categories: "all", Format: "json", Dir: t.TempDir()} - for name, edit := range map[string]func(f *RestoreFlags){ - "no keys": func(f *RestoreFlags) { f.Keys = "" }, - "unreadable keys": func(f *RestoreFlags) { f.Keys = filepath.Join(data, "missing.json") }, - "no data": func(f *RestoreFlags) { f.DataDir = "" }, - "both data inputs": func(f *RestoreFlags) { f.DataZip = filepath.Join(data, "data.zip") }, - "missing data dir": func(f *RestoreFlags) { f.DataDir = filepath.Join(data, "missing") }, - "browser not in it": func(f *RestoreFlags) { f.Browser = "edge" }, - "unknown format": func(f *RestoreFlags) { f.Format = "xml" }, + for name, edit := range map[string]func(flags *RestoreFlags){ + "no keys": func(flags *RestoreFlags) { flags.Keys = "" }, + "unreadable keys": func(flags *RestoreFlags) { flags.Keys = filepath.Join(data, "missing.json") }, + "no data": func(flags *RestoreFlags) { flags.DataDir = "" }, + "both data inputs": func(flags *RestoreFlags) { flags.DataZip = filepath.Join(data, "data.zip") }, + "missing data dir": func(flags *RestoreFlags) { flags.DataDir = filepath.Join(data, "missing") }, + "browser not in it": func(flags *RestoreFlags) { flags.Browser = "edge" }, + "unknown format": func(flags *RestoreFlags) { flags.Format = "xml" }, } { - f := base - edit(&f) - _, _, err := ValidateRestore(f) + flags := base + edit(&flags) + _, _, err := ValidateRestore(flags) require.Error(t, err, name) } - req, dump, err := ValidateRestore(RestoreFlags{Keys: keys, DataDir: data, Browser: "Chrome", Categories: "all", Format: "json", Dir: t.TempDir()}) + options, dump, err := ValidateRestore(RestoreFlags{Keys: keys, DataDir: data, Browser: "Chrome", Categories: "all", Format: "json", Dir: t.TempDir()}) require.NoError(t, err) - assert.Equal(t, "chrome", req.Browser) + assert.Equal(t, "chrome", options.Browser) assert.Len(t, dump.Vaults, 1) } @@ -69,36 +69,36 @@ func TestRestoreDiscovery_FromManifest(t *testing.T) { {ID: "../outside", Browser: "chrome", Base: "chromium"}, {ID: "edge", Browser: "edge", Base: "chromium", Profiles: []snapshot.ManifestProfile{{Name: "Default", Dir: "../../etc"}}}, }})) - arc2 := vault("arc") + arc2 := testVault("arc") arc2.ID = "arc-2" - dump := masterkey.Dump{Vaults: []masterkey.Vault{vault("chrome"), vault("arc"), arc2, vault("edge")}} + dump := masterkey.Dump{Vaults: []masterkey.Vault{testVault("chrome"), testVault("arc"), arc2, testVault("edge")}} - d, keys, err := RestoreDiscovery(data, dump, Request{Browser: "all"}) + discovery, keys, err := RestoreDiscovery(data, dump, Options{Browser: "all"}) require.NoError(t, err) - assert.Equal(t, []browser.DirID{"chrome", "arc-2"}, dirIDs(d), "a manifest path that leaves its directory is refused") - assert.Equal(t, "Chrome", d.Dirs[0].Def.Name, "restore stamps the display name, as dump does") - assert.Equal(t, filepath.Join(root, "arc-2"), d.Dirs[1].Path) - assert.Equal(t, []browser.Profile{{Name: "Work", Dir: "Profile 1"}}, d.Dirs[1].Profiles) + assert.Equal(t, []browser.UserDataDirID{"chrome", "arc-2"}, userDataDirIDs(discovery), "a manifest path that leaves its directory is refused") + assert.Equal(t, "Chrome", discovery.Dirs[0].Browser.DisplayName, "restore sets the display name, as dump does") + assert.Equal(t, filepath.Join(root, "arc-2"), discovery.Dirs[1].Path) + assert.Equal(t, []browser.Profile{{Name: "Work", Dir: "Profile 1"}}, discovery.Dirs[1].Profiles) assert.Equal(t, masterkey.Set{masterkey.V10: []byte("arc")}, keys["arc-2"]) - d, _, err = RestoreDiscovery(data, dump, Request{Browser: "arc"}) + discovery, _, err = RestoreDiscovery(data, dump, Options{Browser: "arc"}) require.NoError(t, err) - assert.Equal(t, []browser.DirID{"arc-2"}, dirIDs(d)) + assert.Equal(t, []browser.UserDataDirID{"arc-2"}, userDataDirIDs(discovery)) } func TestRestoreDiscovery_FromLayout(t *testing.T) { root := t.TempDir() layoutProfile(t, root, "chrome") layoutProfile(t, root, "nightly") - nightly := vault("Nightly") + nightly := testVault("Nightly") nightly.Kind = "chromium-yandex" - dump := masterkey.Dump{Vaults: []masterkey.Vault{vault("chrome"), nightly, vault("chrome"), vault("edge")}} + dump := masterkey.Dump{Vaults: []masterkey.Vault{testVault("chrome"), nightly, testVault("chrome"), testVault("edge")}} - d, keys, err := RestoreDiscovery(snapshot.Open(root), dump, Request{Browser: "all"}) + discovery, keys, err := RestoreDiscovery(snapshot.Open(root), dump, Options{Browser: "all"}) require.NoError(t, err) - assert.Equal(t, []browser.DirID{"chrome", "nightly"}, dirIDs(d), "a repeated vault restores once, one without data not at all") + assert.Equal(t, []browser.UserDataDirID{"chrome", "nightly"}, userDataDirIDs(discovery), "a repeated vault restores once, one without data not at all") assert.Len(t, keys, 2) - assert.Equal(t, browser.Def{ID: "yandex", Name: "Nightly", Base: browser.Chromium}, d.Dirs[1].Def, + assert.Equal(t, browser.Browser{Name: "yandex", DisplayName: "Nightly", Base: browser.Chromium}, discovery.Dirs[1].Browser, "a key this build does not know keeps its kind's format and its own name") } @@ -106,13 +106,13 @@ func TestRestoreDiscovery_OneUserDataNeedsOneVault(t *testing.T) { root := t.TempDir() touch(t, root, "Default", "Preferences") touch(t, root, "Default", "History") - dump := masterkey.Dump{Vaults: []masterkey.Vault{vault("chrome"), vault("edge")}} + dump := masterkey.Dump{Vaults: []masterkey.Vault{testVault("chrome"), testVault("edge")}} - _, _, err := RestoreDiscovery(snapshot.Open(root), dump, Request{Browser: "all"}) + _, _, err := RestoreDiscovery(snapshot.Open(root), dump, Options{Browser: "all"}) require.Error(t, err) - d, _, err := RestoreDiscovery(snapshot.Open(root), dump, Request{Browser: "edge"}) + discovery, _, err := RestoreDiscovery(snapshot.Open(root), dump, Options{Browser: "edge"}) require.NoError(t, err) - require.Equal(t, []browser.DirID{"edge"}, dirIDs(d)) - assert.Equal(t, root, d.Dirs[0].Path) + require.Equal(t, []browser.UserDataDirID{"edge"}, userDataDirIDs(discovery)) + assert.Equal(t, root, discovery.Dirs[0].Path) } diff --git a/internal/app/result.go b/internal/app/result.go index 9526e3d..43d7f02 100644 --- a/internal/app/result.go +++ b/internal/app/result.go @@ -44,6 +44,6 @@ type Summary struct { Results []Result } -func dirFailure(id browser.DirID, err error) Result { - return Result{Extraction: Extraction{DirID: id}, Outcome: OutcomeError, Err: err} +func dirFailure(id browser.UserDataDirID, err error) Result { + return Result{Extraction: Extraction{UserDataDirID: id}, Outcome: OutcomeError, Err: err} } diff --git a/internal/browser/browser.go b/internal/browser/browser.go index 9807368..4cc0cf7 100644 --- a/internal/browser/browser.go +++ b/internal/browser/browser.go @@ -2,16 +2,17 @@ package browser import ( + "fmt" "sort" "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// Def is one browser HBD knows. ID is the -b value and the keys.json vault key; Name is stamped on every record. -type Def struct { - ID string - Name string - Base Base +// Browser is one browser HBD knows. Name is the -b value and the keys.json vault key; DisplayName goes on every record. +type Browser struct { + Name string + DisplayName string + Base Base Darwin Platform Linux Platform @@ -41,7 +42,7 @@ func (b Base) String() string { } } -// A Platform without UserDataDirs means the browser is not supported on that OS. +// Platform is one OS's half of a Browser; one without UserDataDirs means the browser is not supported there. type Platform struct { UserDataDirs []string // slash-separated, relative to the home directory; globs allowed KeychainLabel string // macOS Keychain account / Linux Secret Service label; "" = none @@ -51,33 +52,41 @@ type Platform struct { } // Supported returns the browsers of the running OS, in table order. -func Supported() []Def { - var out []Def - for _, d := range defs { - if len(d.Platform().UserDataDirs) > 0 { - out = append(out, d) +func Supported() []Browser { + var out []Browser + for _, browser := range browsers { + if len(browser.Platform().UserDataDirs) > 0 { + out = append(out, browser) } } return out } -// IDs are this OS's browser IDs, sorted as the -b help has always listed them. -func IDs() []string { - defs := Supported() - ids := make([]string, len(defs)) - for i, d := range defs { - ids[i] = d.ID +// Names are this OS's browser names, sorted as the -b help has always listed them. +func Names() []string { + supported := Supported() + names := make([]string, len(supported)) + for i, browser := range supported { + names[i] = browser.Name } - sort.Strings(ids) - return ids + sort.Strings(names) + return names } -// Lookup finds a browser by ID in the whole table, whatever the running OS, so restore resolves another host's vaults. -func Lookup(id string) (Def, bool) { - for _, d := range defs { - if d.ID == id { - return d, true +// UserDataDirID numbers by path order among a browser's user data dirs, so IDs stay the same from run to run. +func (b Browser) UserDataDirID(index int) UserDataDirID { + if index == 0 { + return UserDataDirID(b.Name) + } + return UserDataDirID(fmt.Sprintf("%s-%d", b.Name, index+1)) +} + +// Lookup finds a browser by name in the whole table, whatever the OS, so restore resolves another host's vaults. +func Lookup(name string) (Browser, bool) { + for _, browser := range browsers { + if browser.Name == name { + return browser, true } } - return Def{}, false + return Browser{}, false } diff --git a/internal/browser/browser_test.go b/internal/browser/browser_test.go index c3dc459..b46dfb2 100644 --- a/internal/browser/browser_test.go +++ b/internal/browser/browser_test.go @@ -14,23 +14,23 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -var platformOf = map[string]func(Def) Platform{ - "darwin": func(d Def) Platform { return d.Darwin }, - "linux": func(d Def) Platform { return d.Linux }, - "windows": func(d Def) Platform { return d.Windows }, +var platformOf = map[string]func(Browser) Platform{ + "darwin": func(browser Browser) Platform { return browser.Darwin }, + "linux": func(browser Browser) Platform { return browser.Linux }, + "windows": func(browser Browser) Platform { return browser.Windows }, } -func idsOn(platform func(Def) Platform) []string { - var ids []string - for _, d := range defs { - if len(platform(d).UserDataDirs) > 0 { - ids = append(ids, d.ID) +func namesOn(platform func(Browser) Platform) []string { + var names []string + for _, browser := range browsers { + if len(platform(browser).UserDataDirs) > 0 { + names = append(names, browser.Name) } } - return ids + return names } -// Discovery order is output order: reordering the table reorders the records in every output file. +// TestTableOrderPerOS pins discovery order, which is output order: reordering the table reorders every output file. func TestTableOrderPerOS(t *testing.T) { want := map[string][]string{ "darwin": { @@ -44,22 +44,22 @@ func TestTableOrderPerOS(t *testing.T) { }, } for goos, platform := range platformOf { - assert.Equal(t, want[goos], idsOn(platform), goos) + assert.Equal(t, want[goos], namesOn(platform), goos) } } func TestSupported_ListsThisOSRowsInTableOrder(t *testing.T) { - var ids []string - for _, d := range Supported() { - ids = append(ids, d.ID) + var names []string + for _, browser := range Supported() { + names = append(names, browser.Name) } - assert.Equal(t, idsOn(Def.Platform), ids) + assert.Equal(t, namesOn(Browser.Platform), names) } func TestLookup_FindsEveryRowWhateverTheOS(t *testing.T) { - for _, want := range defs { - got, ok := Lookup(want.ID) - require.True(t, ok, want.ID) + for _, want := range browsers { + got, ok := Lookup(want.Name) + require.True(t, ok, want.Name) assert.Equal(t, want, got) } _, ok := Lookup("netscape") @@ -68,38 +68,38 @@ func TestLookup_FindsEveryRowWhateverTheOS(t *testing.T) { func TestTableRows(t *testing.T) { seen := make(map[string]bool) - for _, d := range defs { - assert.NotEmpty(t, d.ID) - assert.Falsef(t, seen[d.ID], "duplicate ID %q", d.ID) - seen[d.ID] = true - assert.NotEmpty(t, d.Name, d.ID) - assert.Contains(t, []Base{Chromium, Firefox, Safari}, d.Base, d.ID) + for _, browser := range browsers { + assert.NotEmpty(t, browser.Name) + assert.Falsef(t, seen[browser.Name], "duplicate name %q", browser.Name) + seen[browser.Name] = true + assert.NotEmpty(t, browser.DisplayName, browser.Name) + assert.Contains(t, []Base{Chromium, Firefox, Safari}, browser.Base, browser.Name) for goos, platform := range platformOf { - for _, dir := range platform(d).UserDataDirs { + for _, dir := range platform(browser).UserDataDirs { assert.Truef(t, dir != "" && !path.IsAbs(dir) && !strings.Contains(dir, `\`), - "%s %s: user data dir %q must be slash-separated and relative to the home dir", d.ID, goos, dir) + "%s %s: user data dir %q must be slash-separated and relative to the home dir", browser.Name, goos, dir) } } - w := d.Windows - if w.ABE == masterkey.ABENone { - assert.Emptyf(t, w.Exe, "%s: an executable is only used by ABE", d.ID) - assert.Emptyf(t, w.ExeFallbacks, "%s: executable fallbacks are only used by ABE", d.ID) + windows := browser.Windows + if windows.ABE == masterkey.ABENone { + assert.Emptyf(t, windows.Exe, "%s: an executable is only used by ABE", browser.Name) + assert.Emptyf(t, windows.ExeFallbacks, "%s: executable fallbacks are only used by ABE", browser.Name) continue } - assert.Equal(t, Chromium, d.Base, d.ID) - assert.NotEmpty(t, w.Exe, d.ID) - for _, fallback := range w.ExeFallbacks { - assert.Truef(t, strings.HasSuffix(strings.ToLower(fallback), `\`+strings.ToLower(w.Exe)), - "%s: fallback %q does not name %s", d.ID, fallback, w.Exe) + assert.Equal(t, Chromium, browser.Base, browser.Name) + assert.NotEmpty(t, windows.Exe, browser.Name) + for _, fallback := range windows.ExeFallbacks { + assert.Truef(t, strings.HasSuffix(strings.ToLower(fallback), `\`+strings.ToLower(windows.Exe)), + "%s: fallback %q does not name %s", browser.Name, fallback, windows.Exe) } } } -// The payload finds a browser by its executable, so every Go ABE row needs a C row; the C table may list more. +// TestABERowsMatchPayloadTable needs a C row for every Go ABE row, since the payload finds a browser by its executable. func TestABERowsMatchPayloadTable(t *testing.T) { - src, err := os.ReadFile("../abe/native/com_iid.c") + comIIDTable, err := os.ReadFile("../abe/native/com_iid.c") require.NoError(t, err) kinds := map[string]masterkey.ABEKind{ @@ -108,30 +108,30 @@ func TestABERowsMatchPayloadTable(t *testing.T) { "BROWSER_AVAST": masterkey.ABEAvast, } payload := make(map[string]masterkey.ABEKind) - for _, m := range regexp.MustCompile(`"([^"]+\.exe)",\s*(BROWSER_\w+)`).FindAllStringSubmatch(string(src), -1) { - kind, ok := kinds[m[2]] - require.Truef(t, ok, "unknown payload browser kind %s", m[2]) - exe := strings.ToLower(m[1]) - if _, dup := payload[exe]; !dup { + for _, match := range regexp.MustCompile(`"([^"]+\.exe)",\s*(BROWSER_\w+)`).FindAllStringSubmatch(string(comIIDTable), -1) { + kind, ok := kinds[match[2]] + require.Truef(t, ok, "unknown payload browser kind %s", match[2]) + exe := strings.ToLower(match[1]) + if _, duplicate := payload[exe]; !duplicate { payload[exe] = kind } } require.NotEmpty(t, payload, "no rows parsed from com_iid.c") - for _, d := range defs { - w := d.Windows - if w.ABE == masterkey.ABENone { + for _, browser := range browsers { + platform := browser.Windows + if platform.ABE == masterkey.ABENone { continue } - kind, ok := payload[strings.ToLower(w.Exe)] - if assert.Truef(t, ok, "%s: com_iid.c has no row for %s", d.ID, w.Exe) { - assert.Equalf(t, w.ABE, kind, "%s: com_iid.c dispatches %s as another ABE kind", d.ID, w.Exe) + kind, ok := payload[strings.ToLower(platform.Exe)] + if assert.Truef(t, ok, "%s: com_iid.c has no row for %s", browser.Name, platform.Exe) { + assert.Equalf(t, platform.ABE, kind, "%s: com_iid.c dispatches %s as another ABE kind", browser.Name, platform.Exe) } } } -func TestIDs_AreSupportedSorted(t *testing.T) { - ids := IDs() - assert.True(t, sort.StringsAreSorted(ids), "the -b help has always listed them sorted") - assert.ElementsMatch(t, idsOn(Def.Platform), ids) +func TestNames_AreSupportedSorted(t *testing.T) { + names := Names() + assert.True(t, sort.StringsAreSorted(names), "the -b help has always listed them sorted") + assert.ElementsMatch(t, namesOn(Browser.Platform), names) } diff --git a/internal/browser/browsertest/browsertest.go b/internal/browser/browsertest/browsertest.go index 0a2a751..617d887 100644 --- a/internal/browser/browsertest/browsertest.go +++ b/internal/browser/browsertest/browsertest.go @@ -16,14 +16,14 @@ func fixtureWrite(t *testing.T, path, content string) { require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) } -func fixtureSQLite(t *testing.T, path string, stmts ...string) { +func fixtureSQLite(t *testing.T, path string, statements ...string) { t.Helper() require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) require.NoError(t, err) - defer db.Close() - for _, stmt := range stmts { - _, err = db.Exec(stmt) + defer database.Close() + for _, statement := range statements { + _, err = database.Exec(statement) require.NoError(t, err) } } diff --git a/internal/browser/browsertest/chromium.go b/internal/browser/browsertest/chromium.go index c41791c..3bf4909 100644 --- a/internal/browser/browsertest/chromium.go +++ b/internal/browser/browsertest/chromium.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "fmt" "path/filepath" + "runtime" "sort" "strings" "testing" @@ -19,18 +20,18 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// Only GCM-sealed values (v10 under a 32-byte key, v20) decrypt identically on every OS. +// ChromiumKeys hold only GCM keys (v10 under a 32-byte key, v20), whose values decrypt identically on every OS. var ChromiumKeys = masterkey.Set{ masterkey.V10: []byte("0123456789abcdef0123456789abcdef"), masterkey.V20: []byte("0123456789abcdef"), } var ChromiumInstalls = []struct { - Key string - Name string + Name string + DisplayName string }{ - {Key: "chrome", Name: "Chrome"}, - {Key: "edge", Name: "Microsoft Edge"}, + {Name: "chrome", DisplayName: "Chrome"}, + {Name: "edge", DisplayName: "Microsoft Edge"}, } var ChromiumProfiles = []struct { @@ -45,28 +46,28 @@ var ChromiumProfiles = []struct { func ChromiumInstallations(t *testing.T, root string) { t.Helper() - for _, inst := range ChromiumInstalls { - ChromiumUserData(t, filepath.Join(root, inst.Key), inst.Key) + for _, fixture := range ChromiumInstalls { + ChromiumUserData(t, filepath.Join(root, fixture.Name), fixture.Name) } } -func ChromiumUserData(t *testing.T, userDataDir, browserKey string) { +func ChromiumUserData(t *testing.T, userDataDir, browserName string) { t.Helper() fixtureWrite(t, filepath.Join(userDataDir, "Local State"), "{}") - for _, p := range ChromiumProfiles { - site := p.label + "." + browserKey + ".test" - chromiumFixtureProfile(t, filepath.Join(userDataDir, p.Dir), site, p.start, p.accountLogins) + for _, fixtureProfile := range ChromiumProfiles { + site := fixtureProfile.label + "." + browserName + ".test" + chromiumFixtureProfile(t, filepath.Join(userDataDir, fixtureProfile.Dir), site, fixtureProfile.start, fixtureProfile.accountLogins) } } func chromiumFixtureProfile(t *testing.T, dir, site string, start time.Time, accountLogins bool) { t.Helper() - at := func(offset time.Duration) int64 { return chromiumFixtureMicros(start.Add(offset)) } + chromiumTimeAt := func(offset time.Duration) int64 { return chromiumFixtureMicros(start.Add(offset)) } link := func(host, path string) string { return "https://" + host + "." + site + path } - v10 := func(plaintext string) string { + sealV10 := func(plaintext string) string { return chromiumFixtureSeal(t, "v10", ChromiumKeys[masterkey.V10], plaintext) } - v20 := func(plaintext string) string { + sealV20 := func(plaintext string) string { return chromiumFixtureSeal(t, "v20", ChromiumKeys[masterkey.V20], plaintext) } // Chrome 130+ seals SHA256(host_key) ahead of the cookie value, which extraction must strip again. @@ -80,40 +81,40 @@ func chromiumFixtureProfile(t *testing.T, dir, site string, start time.Time, acc fixtureSQLite(t, filepath.Join(dir, "Login Data"), chromiumFixtureLoginsSchema, chromiumFixtureInsertLogin(link("accounts", "/"), link("accounts", "/login"), "alice", - v10("correct-horse-battery-staple"), at(time.Hour)), - chromiumFixtureInsertLogin(link("shop", "/"), link("shop", "/signin"), "alice@"+site, v10(`pa,ss"word`), at(2*time.Hour)), + sealV10("correct-horse-battery-staple"), chromiumTimeAt(time.Hour)), + chromiumFixtureInsertLogin(link("shop", "/"), link("shop", "/signin"), "alice@"+site, sealV10(`pa,ss"word`), chromiumTimeAt(2*time.Hour)), ) if accountLogins { fixtureSQLite(t, filepath.Join(dir, "Login Data For Account"), chromiumFixtureLoginsSchema, - chromiumFixtureInsertLogin(link("sync", "/"), link("sync", "/auth"), "alice", v10("synced-secret"), at(90*time.Minute)), + chromiumFixtureInsertLogin(link("sync", "/"), link("sync", "/auth"), "alice", sealV10("synced-secret"), chromiumTimeAt(90*time.Minute)), ) } domain, www, app := "."+site, "www."+site, "app."+site fixtureSQLite(t, filepath.Join(dir, "Network", "Cookies"), chromiumFixtureCookiesSchema, - chromiumFixtureInsertCookie("SID", domain, "/", v20(hostBound(domain, "sid-"+site)), - at(10*time.Minute+123456*time.Microsecond), at(365*day), 1, 1, 1), - chromiumFixtureInsertCookie("prefs", www, "/settings", v10("theme=dark"), at(20*time.Minute), at(30*day), 0, 0, 2), - chromiumFixtureInsertCookie("tracker", domain, "/", v20(hostBound(domain, "opt-out")), at(30*time.Minute), at(730*day), 1, 0, 0), - chromiumFixtureInsertCookie("session", app, "/", v20("ephemeral"), at(40*time.Minute), 0, 1, 1, -1), + chromiumFixtureInsertCookie("SID", domain, "/", sealV20(hostBound(domain, "sid-"+site)), + chromiumTimeAt(10*time.Minute+123456*time.Microsecond), chromiumTimeAt(365*day), 1, 1, 1), + chromiumFixtureInsertCookie("prefs", www, "/settings", sealV10("theme=dark"), chromiumTimeAt(20*time.Minute), chromiumTimeAt(30*day), 0, 0, 2), + chromiumFixtureInsertCookie("tracker", domain, "/", sealV20(hostBound(domain, "opt-out")), chromiumTimeAt(30*time.Minute), chromiumTimeAt(730*day), 1, 0, 0), + chromiumFixtureInsertCookie("session", app, "/", sealV20("ephemeral"), chromiumTimeAt(40*time.Minute), 0, 1, 1, -1), ) fixtureSQLite(t, filepath.Join(dir, "History"), chromiumFixtureURLsSchema, chromiumFixtureDownloadsSchema, - chromiumFixtureInsertURL(link("www", "/"), "Home", 42, at(3*time.Hour)), - chromiumFixtureInsertURL(link("docs", "/guide?q=go&lang=en"), `Guide, "quoted" & bold`, 7, at(4*time.Hour)), - chromiumFixtureInsertURL(link("news", "/ja"), "ニュース", 3, at(5*time.Hour)), + chromiumFixtureInsertURL(link("www", "/"), "Home", 42, chromiumTimeAt(3*time.Hour)), + chromiumFixtureInsertURL(link("docs", "/guide?q=go&lang=en"), `Guide, "quoted" & bold`, 7, chromiumTimeAt(4*time.Hour)), + chromiumFixtureInsertURL(link("news", "/ja"), "ニュース", 3, chromiumTimeAt(5*time.Hour)), chromiumFixtureInsertDownload(`C:\Users\alice\Downloads\report.pdf`, link("files", "/report.pdf"), "application/pdf", - 52344, at(6*time.Hour), at(6*time.Hour+3*time.Second)), + 52344, chromiumTimeAt(6*time.Hour), chromiumTimeAt(6*time.Hour+3*time.Second)), chromiumFixtureInsertDownload("/home/alice/Downloads/archive.tar.gz", link("files", "/archive.tar.gz"), "application/gzip", - 1048576, at(7*time.Hour), 0), + 1048576, chromiumTimeAt(7*time.Hour), 0), ) fixtureWrite(t, filepath.Join(dir, "Bookmarks"), - fmt.Sprintf(chromiumFixtureBookmarks, site, at(0), at(8*time.Hour), at(9*time.Hour), at(10*time.Hour))) + fmt.Sprintf(chromiumFixtureBookmarks, site, chromiumTimeAt(0), chromiumTimeAt(8*time.Hour), chromiumTimeAt(9*time.Hour), chromiumTimeAt(10*time.Hour))) fixtureSQLite(t, filepath.Join(dir, "Web Data"), chromiumFixtureCreditCardsSchema, - chromiumFixtureInsertCreditCard("Alice Example", 4, 2031, v10("4111111111111111"), "Travel", "billing-home"), - chromiumFixtureInsertCreditCard("Bob Example", 11, 2029, v10("5500005555555559"), "", ""), + chromiumFixtureInsertCreditCard("Alice Example", 4, 2031, sealV10("4111111111111111"), "Travel", "billing-home"), + chromiumFixtureInsertCreditCard("Bob Example", 11, 2029, sealV10("5500005555555559"), "", ""), ) fixtureWrite(t, filepath.Join(dir, "Secure Preferences"), chromiumFixtureSecurePreferences) @@ -149,37 +150,49 @@ func chromiumFixtureSeal(t *testing.T, version string, key []byte, plaintext str return hex.EncodeToString(append(append([]byte(version), nonce...), sealed...)) } -func chromiumFixtureMicros(ts time.Time) int64 { +func chromiumFixtureMicros(timestamp time.Time) int64 { const unixToChromiumEpochMicros = 11_644_473_600_000_000 - return ts.UnixMicro() + unixToChromiumEpochMicros + return timestamp.UnixMicro() + unixToChromiumEpochMicros } -func chromiumFixtureLatin1(s string) string { return "\x01" + s } +func chromiumFixtureLatin1(text string) string { return "\x01" + text } -func chromiumFixtureUTF16(s string) string { return "\x00" + chromiumFixtureUTF16Raw(s) } +func chromiumFixtureUTF16(text string) string { return "\x00" + chromiumFixtureUTF16Raw(text) } -func chromiumFixtureUTF16Raw(s string) string { - units := utf16.Encode([]rune(s)) - b := make([]byte, 2*len(units)) - for i, u := range units { - binary.LittleEndian.PutUint16(b[2*i:], u) +func chromiumFixtureUTF16Raw(text string) string { + units := utf16.Encode([]rune(text)) + encoded := make([]byte, 2*len(units)) + for i, unit := range units { + binary.LittleEndian.PutUint16(encoded[2*i:], unit) } - return string(b) + return string(encoded) } func chromiumFixtureLevelDB(t *testing.T, dir string, entries map[string]string) { t.Helper() keys := make([]string, 0, len(entries)) - for k := range entries { - keys = append(keys, k) + for key := range entries { + keys = append(keys, key) } sort.Strings(keys) - db, err := leveldb.OpenFile(dir, nil) - require.NoError(t, err) - for _, k := range keys { - require.NoError(t, db.Put([]byte(k), []byte(entries[k]), nil)) + database := OpenLevelDB(t, dir) + for _, key := range keys { + require.NoError(t, database.Put([]byte(key), []byte(entries[key]), nil)) + } + require.NoError(t, database.Close()) +} + +// OpenLevelDB retries on Windows, where a just-written file can stay locked by a scanner and fail OpenFile. +func OpenLevelDB(t *testing.T, dir string) *leveldb.DB { + t.Helper() + for attempt := 1; ; attempt++ { + database, err := leveldb.OpenFile(dir, nil) + if err == nil || runtime.GOOS != "windows" || attempt == 5 { + require.NoError(t, err) + return database + } + time.Sleep(time.Duration(attempt) * 100 * time.Millisecond) } - require.NoError(t, db.Close()) } func chromiumFixtureInsertLogin(originURL, actionURL, username, pwdHex string, dateCreated int64) string { diff --git a/internal/browser/browsertest/firefox.go b/internal/browser/browsertest/firefox.go index 5758a36..e4e1725 100644 --- a/internal/browser/browsertest/firefox.go +++ b/internal/browser/browsertest/firefox.go @@ -14,7 +14,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/crypto" ) -// home's logins open only with its second key candidate and work's with its only one, so the golden covers both paths. +// firefoxFixtureProfiles cover both key paths: home opens with its second key candidate, work with its only one. var firefoxFixtureProfiles = []struct { dir string label string @@ -48,8 +48,8 @@ func FirefoxUserData(t *testing.T, profilesDir string) { t.Helper() fixtureWrite(t, filepath.Join(profilesDir, "profiles.ini"), "[General]\nStartWithLastProfile=1\n") fixtureWrite(t, filepath.Join(profilesDir, "Crash Reports", "InstallTime20240101000000"), "1704067200") - for _, p := range firefoxFixtureProfiles { - firefoxFixtureProfile(t, filepath.Join(profilesDir, p.dir), p.label+".firefox.test", p.start, p.globalSalt, p.keys) + for _, fixtureProfile := range firefoxFixtureProfiles { + firefoxFixtureProfile(t, filepath.Join(profilesDir, fixtureProfile.dir), fixtureProfile.label+".firefox.test", fixtureProfile.start, fixtureProfile.globalSalt, fixtureProfile.keys) } } @@ -61,17 +61,17 @@ func firefoxFixtureProfile(t *testing.T, dir, site string, start time.Time, glob link := func(host, path string) string { return "https://" + host + "." + site + path } day := 24 * time.Hour - key4 := []string{ + key4Statements := []string{ firefoxFixtureMetaDataSchema, firefoxFixtureNSSPrivateSchema, fmt.Sprintf(`INSERT INTO metaData (id, item1, item2) VALUES ('password', x'%x', x'%x')`, globalSalt, firefoxFixturePBES2Seal(t, globalSalt, site+"/password-check", []byte("password-check"))), } for i, key := range keys { - key4 = append(key4, fmt.Sprintf(`INSERT INTO nssPrivate (id, a11, a102) VALUES (%d, x'%x', x'%x')`, + key4Statements = append(key4Statements, fmt.Sprintf(`INSERT INTO nssPrivate (id, a11, a102) VALUES (%d, x'%x', x'%x')`, i+1, firefoxFixturePBES2Seal(t, globalSalt, fmt.Sprintf("%s/key-%d", site, i), key), firefoxFixtureKeyID)) } - fixtureSQLite(t, filepath.Join(dir, "key4.db"), key4...) + fixtureSQLite(t, filepath.Join(dir, "key4.db"), key4Statements...) loginKey := keys[len(keys)-1] seal := func(field, plaintext string) string { @@ -135,7 +135,7 @@ func firefoxFixtureProfile(t *testing.T, dir, site string, start time.Time, glob ) } -// The template goes through the decoder's own parser and Encrypt, so only the ASN.1 layout is spelled out here. +// firefoxFixtureSeal goes through the decoder's own parser and Encrypt, so only the ASN.1 layout is spelled out here. func firefoxFixtureSeal(t *testing.T, marshal func() ([]byte, error), ciphertext *[]byte, key, plaintext []byte) []byte { t.Helper() template, err := marshal() @@ -209,12 +209,12 @@ func firefoxFixtureLoginSeal(t *testing.T, key []byte, seed, plaintext string) s return base64.StdEncoding.EncodeToString(sealed) } -func firefoxFixtureBytes(seed string, n int) []byte { +func firefoxFixtureBytes(seed string, length int) []byte { sum := sha256.Sum256([]byte(seed)) - return sum[:n] + return sum[:length] } -// webappsstore2 stores the host reversed, so a domain and its subdomains share a key prefix. +// firefoxFixtureOriginKey reverses the host, as webappsstore2 does, so a domain and its subdomains share a key prefix. func firefoxFixtureOriginKey(scheme, host string, port int) string { reversed := []byte(host) for i, j := 0, len(reversed)-1; i < j; i, j = i+1, j-1 { @@ -223,11 +223,11 @@ func firefoxFixtureOriginKey(scheme, host string, port int) string { return fmt.Sprintf("%s.:%s:%d", reversed, scheme, port) } -func firefoxFixtureText(s string) string { - if s == "" { +func firefoxFixtureText(text string) string { + if text == "" { return "NULL" } - return "'" + s + "'" + return "'" + text + "'" } func firefoxFixtureInsertCookie(name, value, host, path string, expiry, creationTime int64, secure, httpOnly, sameSite int) string { @@ -251,10 +251,10 @@ func firefoxFixtureInsertPlace(id int, url, title string, visitCount int, lastVi ) } -func firefoxFixtureInsertBookmark(id, bookmarkType, fk, parent, position int, title, guid string, dateAdded int64) string { +func firefoxFixtureInsertBookmark(id, bookmarkType, foreignKey, parent, position int, title, guid string, dateAdded int64) string { fkValue := "NULL" - if fk != 0 { - fkValue = fmt.Sprint(fk) + if foreignKey != 0 { + fkValue = fmt.Sprint(foreignKey) } return fmt.Sprintf( `INSERT INTO moz_bookmarks (id, type, fk, parent, position, title, dateAdded, lastModified, guid) diff --git a/internal/browser/browsertest/safari.go b/internal/browser/browsertest/safari.go index 955c254..ec0e33e 100644 --- a/internal/browser/browsertest/safari.go +++ b/internal/browser/browsertest/safari.go @@ -25,8 +25,8 @@ var safariFixtureStart = time.Date(2024, 3, 1, 9, 0, 0, 0, time.UTC) func SafariLibrary(t *testing.T, library string) { t.Helper() - at := safariFixtureStart.Add - visit := func(offset time.Duration) float64 { return safariFixtureCoreData(at(offset)) } + timeAt := safariFixtureStart.Add + visit := func(offset time.Duration) float64 { return safariFixtureCoreData(timeAt(offset)) } day := 24 * time.Hour legacyHome := filepath.Join(library, "Safari") container := filepath.Join(library, "Containers", "com.apple.Safari", "Data", "Library") @@ -66,21 +66,21 @@ func SafariLibrary(t *testing.T, library string) { []safariFixtureCookie{ { domain: ".home.safari.test", name: "SID", path: "/", value: "sid-home.safari.test", flags: 0x5, - expires: at(365 * day), created: at(10*time.Minute + 750*time.Millisecond), + expires: timeAt(365 * day), created: timeAt(10*time.Minute + 750*time.Millisecond), }, { domain: "www.home.safari.test", name: "prefs", path: "/settings", value: "theme=dark", - expires: at(30 * day), created: at(20 * time.Minute), + expires: timeAt(30 * day), created: timeAt(20 * time.Minute), }, }, []safariFixtureCookie{ { domain: ".home.safari.test", name: "tracker", path: "/", value: "opt-out", flags: 0x1, - expires: at(730 * day), created: at(30 * time.Minute), + expires: timeAt(730 * day), created: timeAt(30 * time.Minute), }, { domain: "app.home.safari.test", name: "csrf", path: "/", value: "token-123", flags: 0x4, - expires: at(day), created: at(40 * time.Minute), + expires: timeAt(day), created: timeAt(40 * time.Minute), }, }, ))) @@ -88,18 +88,18 @@ func SafariLibrary(t *testing.T, library string) { fixtureWrite(t, filepath.Join(library, "Cookies", "Cookies.binarycookies"), string(safariFixtureCookieFile(t, []safariFixtureCookie{{ domain: "old.home.safari.test", name: "legacy", path: "/", value: "stale", - expires: at(day), created: at(time.Minute), + expires: timeAt(day), created: timeAt(time.Minute), }}, ))) fixtureWrite(t, filepath.Join(workStore, "Cookies", "Cookies.binarycookies"), string(safariFixtureCookieFile(t, []safariFixtureCookie{ { domain: ".work.safari.test", name: "SSO", path: "/", value: "sso-work.safari.test", flags: 0x5, - expires: at(7 * day), created: at(6 * time.Hour), + expires: timeAt(7 * day), created: timeAt(6 * time.Hour), }, { domain: "wiki.work.safari.test", name: "lang", path: "/", value: "en", - expires: at(90 * day), created: at(7 * time.Hour), + expires: timeAt(90 * day), created: timeAt(7 * time.Hour), }, }, ))) @@ -129,18 +129,18 @@ func SafariLibrary(t *testing.T, library string) { safariFixturePlist(t, filepath.Join(container, "Safari", "WebExtensions", "Extensions.plist"), safariFixtureWebExtensions) } -func safariFixtureCoreData(ts time.Time) float64 { +func safariFixtureCoreData(timestamp time.Time) float64 { const unixToCoreDataSeconds = 978_307_200 - return float64(ts.UnixMilli())/1000 - unixToCoreDataSeconds + return float64(timestamp.UnixMilli())/1000 - unixToCoreDataSeconds } -// Safari writes binary plists; the fixtures keep XML so they read like plutil's XML output. +// safariFixturePlist writes XML, though Safari writes binary plists, so the fixtures read like plutil's XML output. func safariFixturePlist(t *testing.T, path, body string) { t.Helper() - var v any - _, err := plist.Unmarshal([]byte(``+body+``), &v) + var value any + _, err := plist.Unmarshal([]byte(``+body+``), &value) require.NoError(t, err) - data, err := plist.Marshal(v, plist.BinaryFormat) + data, err := plist.Marshal(value, plist.BinaryFormat) require.NoError(t, err) fixtureWrite(t, path, string(data)) } @@ -166,7 +166,7 @@ type safariFixtureCookieHeader struct { Created float64 } -// Each argument is one page of the jar. +// safariFixtureCookieFile takes one page of the jar per argument. func safariFixtureCookieFile(t *testing.T, pages ...[]safariFixtureCookie) []byte { t.Helper() encoded := make([][]byte, len(pages)) @@ -184,47 +184,47 @@ func safariFixtureCookieFile(t *testing.T, pages ...[]safariFixtureCookie) []byt func safariFixtureCookiePage(t *testing.T, cookies []safariFixtureCookie) []byte { t.Helper() records := make([][]byte, len(cookies)) - for i, c := range cookies { - records[i] = safariFixtureCookieRecord(t, c) + for i, cookie := range cookies { + records[i] = safariFixtureCookieRecord(t, cookie) } page := binary.LittleEndian.AppendUint32([]byte{0x00, 0x00, 0x01, 0x00}, uint32(len(cookies))) offset := 4 + 4 + 4*len(cookies) + 4 - for _, r := range records { + for _, encodedRecord := range records { page = binary.LittleEndian.AppendUint32(page, uint32(offset)) - offset += len(r) + offset += len(encodedRecord) } page = append(page, 0x00, 0x00, 0x00, 0x00) - for _, r := range records { - page = append(page, r...) + for _, encodedRecord := range records { + page = append(page, encodedRecord...) } return page } -func safariFixtureCookieRecord(t *testing.T, c safariFixtureCookie) []byte { +func safariFixtureCookieRecord(t *testing.T, cookie safariFixtureCookie) []byte { t.Helper() header := safariFixtureCookieHeader{ - Flags: c.flags, - Expires: safariFixtureCoreData(c.expires), - Created: safariFixtureCoreData(c.created), + Flags: cookie.flags, + Expires: safariFixtureCoreData(cookie.expires), + Created: safariFixtureCoreData(cookie.created), } headerSize := uint32(binary.Size(header)) var strs []byte - for _, f := range []struct { + for _, field := range []struct { offset *uint32 value string }{ - {&header.DomainOffset, c.domain}, - {&header.NameOffset, c.name}, - {&header.PathOffset, c.path}, - {&header.ValueOffset, c.value}, + {&header.DomainOffset, cookie.domain}, + {&header.NameOffset, cookie.name}, + {&header.PathOffset, cookie.path}, + {&header.ValueOffset, cookie.value}, } { - *f.offset = headerSize + uint32(len(strs)) - strs = append(append(strs, f.value...), 0x00) + *field.offset = headerSize + uint32(len(strs)) + strs = append(append(strs, field.value...), 0x00) } header.Size = headerSize + uint32(len(strs)) - var b bytes.Buffer - require.NoError(t, binary.Write(&b, binary.LittleEndian, header)) - return append(b.Bytes(), strs...) + var buffer bytes.Buffer + require.NoError(t, binary.Write(&buffer, binary.LittleEndian, header)) + return append(buffer.Bytes(), strs...) } type safariFixtureEndpoint struct { @@ -232,7 +232,7 @@ type safariFixtureEndpoint struct { port uint16 } -// Top and frame differ for third-party storage; an origin without localStorage items keeps only its origin file. +// safariFixtureOrigin takes top and frame, which differ for third-party storage; without items, one origin file stays. func safariFixtureOrigin(t *testing.T, root string, top, frame safariFixtureEndpoint, items ...[2]string) { t.Helper() dir := filepath.Join(root, safariFixtureHash(top), safariFixtureHash(frame)) @@ -240,37 +240,37 @@ func safariFixtureOrigin(t *testing.T, root string, top, frame safariFixtureEndp if len(items) == 0 { return } - stmts := []string{safariFixtureItemTableSchema} + statements := []string{safariFixtureItemTableSchema} for _, item := range items { - stmts = append(stmts, fmt.Sprintf(`INSERT INTO ItemTable (key, value) VALUES ('%s', x'%x')`, item[0], safariFixtureUTF16(item[1]))) + statements = append(statements, fmt.Sprintf(`INSERT INTO ItemTable (key, value) VALUES ('%s', x'%x')`, item[0], safariFixtureUTF16(item[1]))) } - fixtureSQLite(t, filepath.Join(dir, "LocalStorage", "localstorage.sqlite3"), stmts...) + fixtureSQLite(t, filepath.Join(dir, "LocalStorage", "localstorage.sqlite3"), statements...) } -func safariFixtureHash(e safariFixtureEndpoint) string { - sum := sha256.Sum256([]byte(fmt.Sprintf("%s://%s:%d", e.scheme, e.host, e.port))) +func safariFixtureHash(endpoint safariFixtureEndpoint) string { + sum := sha256.Sum256([]byte(fmt.Sprintf("%s://%s:%d", endpoint.scheme, endpoint.host, endpoint.port))) return hex.EncodeToString(sum[:]) } -func safariFixtureOriginBlock(e safariFixtureEndpoint) []byte { +func safariFixtureOriginBlock(endpoint safariFixtureEndpoint) []byte { const latin1, defaultPort, explicitPort = 0x01, 0x00, 0x01 - var b []byte - for _, s := range []string{e.scheme, e.host} { - b = binary.LittleEndian.AppendUint32(b, uint32(len(s))) - b = append(append(b, latin1), s...) + var block []byte + for _, part := range []string{endpoint.scheme, endpoint.host} { + block = binary.LittleEndian.AppendUint32(block, uint32(len(part))) + block = append(append(block, latin1), part...) } - if e.port == 0 { - return append(b, defaultPort) + if endpoint.port == 0 { + return append(block, defaultPort) } - return binary.LittleEndian.AppendUint16(append(b, explicitPort), e.port) + return binary.LittleEndian.AppendUint16(append(block, explicitPort), endpoint.port) } -func safariFixtureUTF16(s string) []byte { - var b []byte - for _, u := range utf16.Encode([]rune(s)) { - b = binary.LittleEndian.AppendUint16(b, u) +func safariFixtureUTF16(text string) []byte { + var encoded []byte + for _, unit := range utf16.Encode([]rune(text)) { + encoded = binary.LittleEndian.AppendUint16(encoded, unit) } - return b + return encoded } func safariFixtureInsertHistoryItem(id int, url string, visitCount int) string { diff --git a/internal/browser/chromium/chromium.go b/internal/browser/chromium/chromium.go index 7ac7044..4468269 100644 --- a/internal/browser/chromium/chromium.go +++ b/internal/browser/chromium/chromium.go @@ -13,19 +13,19 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// Sogou and QQ write Preferences_02; a marker keeps dirs like Crashpad and ShaderCache from passing as profiles. +// profileMarkers add Preferences_02 for Sogou and QQ; a marker keeps dirs like Crashpad from passing as profiles. var profileMarkers = []string{"Preferences", "Preferences_02"} -// A user data dir that does not exist yields nothing; any other failure is returned beside whatever was found. -func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { - if dir, ok := profileAt(def, opts.ProfilePath); ok { +// 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 { return []browser.UserDataDir{dir}, nil } - paths, err := userDataDirPaths(def, opts) + paths, err := userDataDirPaths(chromiumBrowser, options) errs := []error{err} var dirs []browser.UserDataDir for i, path := range paths { - dir := browser.UserDataDir{ID: dirID(def, i), Def: def, Path: path} + dir := browser.UserDataDir{ID: chromiumBrowser.UserDataDirID(i), Browser: chromiumBrowser, Path: path} profiles, err := discoverProfiles(dir) if errors.Is(err, fs.ErrNotExist) { continue @@ -41,8 +41,8 @@ func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserData } // DiscoverAt reads the profiles of a user data dir the table does not name, such as a copy restore was given. -func DiscoverAt(def browser.Def, id browser.DirID, path string) (browser.UserDataDir, error) { - dir := browser.UserDataDir{ID: id, Def: def, Path: path} +func DiscoverAt(chromiumBrowser browser.Browser, id browser.UserDataDirID, path string) (browser.UserDataDir, error) { + dir := browser.UserDataDir{ID: id, Browser: chromiumBrowser, Path: path} profiles, err := discoverProfiles(dir) if err != nil { return dir, err @@ -51,34 +51,34 @@ func DiscoverAt(def browser.Def, id browser.DirID, path string) (browser.UserDat return dir, nil } -// -p is the path chrome://version shows: a profile dir without Local State selects that profile of its parent. -func profileAt(def browser.Def, path string) (browser.UserDataDir, bool) { - if path == "" || !isProfileDir(path) || hasAnySource(path, localState.Paths) { +// 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) { + if path == "" || !isProfileDir(path) || hasAnyFile(path, localState.Paths) { return browser.UserDataDir{}, false } clean := filepath.Clean(path) name := filepath.Base(clean) return browser.UserDataDir{ - ID: dirID(def, 0), - Def: def, + ID: chromiumBrowser.UserDataDirID(0), + Browser: chromiumBrowser, Path: filepath.Dir(clean), Profiles: []browser.Profile{{Name: name, Dir: name}}, }, true } -// Every glob match is kept, for both of a machine's Arc packages; "/" joins keep the paths keys.json has recorded. -func userDataDirPaths(def browser.Def, opts browser.DiscoverOptions) ([]string, error) { - if opts.ProfilePath != "" { - return []string{opts.ProfilePath}, nil +// userDataDirPaths keeps every glob match, for both Arc packages; "/" joins keep the paths keys.json recorded. +func userDataDirPaths(chromiumBrowser browser.Browser, options browser.DiscoverOptions) ([]string, error) { + if options.ProfilePath != "" { + return []string{options.ProfilePath}, nil } var ( paths []string errs []error ) - for _, rel := range def.Platform().UserDataDirs { - matches, err := filepath.Glob(opts.Home + "/" + rel) + for _, relativePath := range chromiumBrowser.Platform().UserDataDirs { + matches, err := filepath.Glob(options.Home + "/" + relativePath) if err != nil { - errs = append(errs, fmt.Errorf("user data dir %q: %w", rel, err)) + errs = append(errs, fmt.Errorf("user data dir %q: %w", relativePath, err)) continue } paths = append(paths, matches...) @@ -86,14 +86,6 @@ func userDataDirPaths(def browser.Def, opts browser.DiscoverOptions) ([]string, return paths, errors.Join(errs...) } -// dirID numbers by path order among the matches, so IDs stay the same from run to run. -func dirID(def browser.Def, i int) browser.DirID { - if i == 0 { - return browser.DirID(def.ID) - } - return browser.DirID(fmt.Sprintf("%s-%d", def.ID, i+1)) -} - func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { entries, err := os.ReadDir(dir.Path) if err != nil { @@ -101,25 +93,25 @@ func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { } var profiles []browser.Profile - for _, e := range entries { - if e.IsDir() && !isSkippedDir(e.Name()) && isProfileDir(filepath.Join(dir.Path, e.Name())) { - profiles = append(profiles, browser.Profile{Name: e.Name(), Dir: e.Name()}) + for _, entry := range entries { + if entry.IsDir() && !isSkippedDir(entry.Name()) && isProfileDir(filepath.Join(dir.Path, entry.Name())) { + profiles = append(profiles, browser.Profile{Name: entry.Name(), Dir: entry.Name()}) } } if len(profiles) > 0 { return profiles, nil } - // Flat layout (older Opera): check the root before subdirs, so a stray source-bearing subdir can't hide it. - sources := profileSourcePaths(dir) - if hasAnySource(dir.Path, sources) { + // Flat layout (older Opera): check the root before subdirs, so a stray subdir holding profile files can't hide it. + profileFiles := profileFilePaths(dir) + if hasAnyFile(dir.Path, profileFiles) { return []browser.Profile{{Name: filepath.Base(dir.Path)}}, nil } - // Restored or copied trees may omit the marker, which no category reads, so any source-bearing subdir is a profile. - for _, e := range entries { - if e.IsDir() && !isSkippedDir(e.Name()) && hasAnySource(filepath.Join(dir.Path, e.Name()), sources) { - profiles = append(profiles, browser.Profile{Name: e.Name(), Dir: e.Name()}) + // Copied or restored trees may lack the marker, which no category reads, so a subdir with profile files is one too. + for _, entry := range entries { + if entry.IsDir() && !isSkippedDir(entry.Name()) && hasAnyFile(filepath.Join(dir.Path, entry.Name()), profileFiles) { + profiles = append(profiles, browser.Profile{Name: entry.Name(), Dir: entry.Name()}) } } return profiles, nil @@ -142,51 +134,53 @@ func isSkippedDir(name string) bool { return false } -func profileSourcePaths(dir browser.UserDataDir) []string { +func profileFilePaths(dir browser.UserDataDir) []string { var paths []string - for _, e := range Extractors(dir, browser.Profile{}) { - for _, src := range e.Sources { - if !src.Shared { - paths = append(paths, src.Paths...) + for _, extractor := range Extractors(dir, browser.Profile{}) { + for _, fileSpec := range extractor.FileSpecs { + if !fileSpec.Shared { + paths = append(paths, fileSpec.Paths...) } } } return paths } -func hasAnySource(dir string, paths []string) bool { - for _, rel := range paths { - if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(rel))); err == nil { +func hasAnyFile(dir string, paths []string) bool { + for _, relativePath := range paths { + if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(relativePath))); err == nil { return true } } return false } -// On macOS the caller adds the run's login keychain to the Locator. -func KeyLocator(dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Locator, error) { - p := dir.Def.Platform() - loc := masterkey.Locator{KeychainLabel: p.KeychainLabel, Exe: p.Exe, ExeFallbacks: p.ExeFallbacks, ABE: p.ABE} - path, err := snap.Path(localState.Paths[0]) +// KeyLocator leaves the run's login keychain to the caller, which adds it to the Locator on macOS. +func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Locator, error) { + platform := dir.Browser.Platform() + locator := masterkey.Locator{ + KeychainLabel: platform.KeychainLabel, Exe: platform.Exe, ExeFallbacks: platform.ExeFallbacks, ABE: platform.ABE, + } + path, err := dirSnapshot.Path(localState.Paths[0]) switch { case err == nil: - loc.LocalState = path + locator.LocalState = path case !errors.Is(err, fs.ErrNotExist): - return loc, fmt.Errorf("local state: %w", err) + return locator, fmt.Errorf("local state: %w", err) } - return loc, nil + return locator, nil } -// KeySources are the files KeyLocator reads from a snapshot. -func KeySources(_ browser.UserDataDir) []browser.Source { - return []browser.Source{localState} +// KeyFileSpecs are the files KeyLocator reads from a snapshot. +func KeyFileSpecs(_ browser.UserDataDir) []browser.FileSpec { + return []browser.FileSpec{localState} } -// ArchiveSources add Local State and each profile's marker, so a reader without the manifest finds every profile. -func ArchiveSources(_ browser.UserDataDir) []browser.Source { - sources := []browser.Source{localState} +// ArchiveFileSpecs add Local State and each profile's marker, so a reader without the manifest finds every profile. +func ArchiveFileSpecs(_ browser.UserDataDir) []browser.FileSpec { + fileSpecs := []browser.FileSpec{localState} for _, marker := range profileMarkers { - sources = append(sources, browser.Source{Paths: []string{marker}, Optional: true}) + fileSpecs = append(fileSpecs, browser.FileSpec{Paths: []string{marker}, Optional: true}) } - return sources + return fileSpecs } diff --git a/internal/browser/chromium/chromium_test.go b/internal/browser/chromium/chromium_test.go index ac6bd51..09c6cff 100644 --- a/internal/browser/chromium/chromium_test.go +++ b/internal/browser/chromium/chromium_test.go @@ -17,9 +17,9 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -func testDef(id string, userDataDirs ...string) browser.Def { - p := browser.Platform{UserDataDirs: userDataDirs, KeychainLabel: "Test Safe Storage"} - return browser.Def{ID: id, Name: id, Base: browser.Chromium, Darwin: p, Linux: p, Windows: p} +func testBrowser(name string, userDataDirs ...string) browser.Browser { + platform := browser.Platform{UserDataDirs: userDataDirs, KeychainLabel: "Test Safe Storage"} + return browser.Browser{Name: name, DisplayName: name, Base: browser.Chromium, Darwin: platform, Linux: platform, Windows: platform} } func touch(t *testing.T, parts ...string) { @@ -32,10 +32,10 @@ func touch(t *testing.T, parts ...string) { func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot { t.Helper() root := t.TempDir() - for rel, src := range files { - dir := filepath.Join(root, "chrome", filepath.Dir(filepath.FromSlash(rel))) + for relativePath, fixturePath := range files { + dir := filepath.Join(root, "chrome", filepath.Dir(filepath.FromSlash(relativePath))) require.NoError(t, os.MkdirAll(dir, 0o700)) - installFile(t, dir, src, filepath.Base(rel)) + installFile(t, dir, fixturePath, filepath.Base(relativePath)) } return snapshot.Open(root).Snapshot("chrome") } @@ -48,10 +48,10 @@ func TestDiscover_FindsMarkedProfiles(t *testing.T) { touch(t, home, "ud", "QQ", "Preferences_02") require.NoError(t, os.MkdirAll(filepath.Join(home, "ud", "Crashpad"), 0o700)) - dirs, err := Discover(testDef("chrome", "ud"), browser.DiscoverOptions{Home: home}) + dirs, err := Discover(testBrowser("chrome", "ud"), browser.DiscoverOptions{Home: home}) require.NoError(t, err) require.Len(t, dirs, 1) - assert.Equal(t, browser.DirID("chrome"), dirs[0].ID) + assert.Equal(t, browser.UserDataDirID("chrome"), dirs[0].ID) assert.Equal(t, home+"/ud", dirs[0].Path, "joined with a slash, as keys.json has always recorded it") assert.Equal(t, []browser.Profile{ {Name: "Default", Dir: "Default"}, @@ -60,27 +60,27 @@ func TestDiscover_FindsMarkedProfiles(t *testing.T) { }, dirs[0].Profiles) } -// Two Arc packages are two user data dirs; their IDs follow path order, so they are the same on every run. +// TestDiscover_EveryGlobMatchIsItsOwnUserDataDir treats two Arc packages as two user data dirs, numbered by path order. func TestDiscover_EveryGlobMatchIsItsOwnUserDataDir(t *testing.T) { home := t.TempDir() touch(t, home, "Packages", "Arc_b", "User Data", "Default", "Preferences") touch(t, home, "Packages", "Arc_a", "User Data", "Default", "Preferences") - dirs, err := Discover(testDef("arc", "Packages/Arc_*/User Data"), browser.DiscoverOptions{Home: home}) + dirs, err := Discover(testBrowser("arc", "Packages/Arc_*/User Data"), browser.DiscoverOptions{Home: home}) require.NoError(t, err) require.Len(t, dirs, 2) - assert.Equal(t, browser.DirID("arc"), dirs[0].ID) + assert.Equal(t, browser.UserDataDirID("arc"), dirs[0].ID) assert.Equal(t, filepath.Join(home, "Packages", "Arc_a", "User Data"), dirs[0].Path) - assert.Equal(t, browser.DirID("arc-2"), dirs[1].ID) + assert.Equal(t, browser.UserDataDirID("arc-2"), dirs[1].ID) assert.Equal(t, filepath.Join(home, "Packages", "Arc_b", "User Data"), dirs[1].Path) - assert.Equal(t, "arc", dirs[1].Def.ID, "the browser stays arc; only the directory is numbered") + assert.Equal(t, "arc", dirs[1].Browser.Name, "the browser stays arc; only the directory is numbered") } func TestDiscover_FlatLayoutIsOneProfile(t *testing.T) { home := t.TempDir() touch(t, home, "Opera Stable", "Login Data") - dirs, err := Discover(testDef("opera", "Opera Stable"), browser.DiscoverOptions{Home: home}) + dirs, err := Discover(testBrowser("opera", "Opera Stable"), browser.DiscoverOptions{Home: home}) require.NoError(t, err) require.Len(t, dirs, 1) assert.Equal(t, []browser.Profile{{Name: "Opera Stable"}}, dirs[0].Profiles) @@ -91,36 +91,36 @@ func TestDiscover_CopiedTreeWithoutMarkers(t *testing.T) { touch(t, home, "ud", "Default", "History") require.NoError(t, os.MkdirAll(filepath.Join(home, "ud", "Crashpad"), 0o700)) - dirs, err := Discover(testDef("chrome", "ud"), browser.DiscoverOptions{Home: home}) + dirs, err := Discover(testBrowser("chrome", "ud"), browser.DiscoverOptions{Home: home}) require.NoError(t, err) require.Len(t, dirs, 1) assert.Equal(t, []browser.Profile{{Name: "Default", Dir: "Default"}}, dirs[0].Profiles) } func TestDiscover_MissingUserDataDirYieldsNothing(t *testing.T) { - dirs, err := Discover(testDef("chrome", "ud"), browser.DiscoverOptions{Home: t.TempDir()}) + dirs, err := Discover(testBrowser("chrome", "ud"), browser.DiscoverOptions{Home: t.TempDir()}) require.NoError(t, err) assert.Empty(t, dirs) } -// A user data dir that exists but cannot be read must not look like a browser that is not installed. +// TestDiscover_UnreadableUserDataDirIsAnError keeps an unreadable dir from looking like a browser not installed. func TestDiscover_UnreadableUserDataDirIsAnError(t *testing.T) { if runtime.GOOS == "windows" || os.Geteuid() == 0 { t.Skip("directory permissions do not deny reads here") } home := t.TempDir() touch(t, home, "ud", "Default", "Preferences") - ud := filepath.Join(home, "ud") - require.NoError(t, os.Chmod(ud, 0o000)) - defer func() { require.NoError(t, os.Chmod(ud, 0o700)) }() + userDataDir := filepath.Join(home, "ud") + require.NoError(t, os.Chmod(userDataDir, 0o000)) + defer func() { require.NoError(t, os.Chmod(userDataDir, 0o700)) }() - dirs, err := Discover(testDef("chrome", "ud"), browser.DiscoverOptions{Home: home}) + dirs, err := Discover(testBrowser("chrome", "ud"), browser.DiscoverOptions{Home: home}) require.Error(t, err) assert.Empty(t, dirs) } func TestDiscover_MalformedGlobIsAnError(t *testing.T) { - _, err := Discover(testDef("chrome", "ud["), browser.DiscoverOptions{Home: t.TempDir()}) + _, err := Discover(testBrowser("chrome", "ud["), browser.DiscoverOptions{Home: t.TempDir()}) require.Error(t, err) } @@ -128,37 +128,37 @@ func TestDiscover_ProfilePathReplacesTheTable(t *testing.T) { custom := t.TempDir() touch(t, custom, "Default", "Preferences") - dirs, err := Discover(testDef("chrome", "ud"), browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: custom}) + dirs, err := Discover(testBrowser("chrome", "ud"), browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: custom}) require.NoError(t, err) require.Len(t, dirs, 1) assert.Equal(t, custom, dirs[0].Path) } -// Before, a profile directory became the whole user data dir, so the Local State one level up was never found. +// TestDiscover_ProfilePathAtAProfileSelectsOnlyIt guards a fixed bug: a profile dir was taken for its user data dir. func TestDiscover_ProfilePathAtAProfileSelectsOnlyIt(t *testing.T) { userData := t.TempDir() touch(t, userData, "Local State") touch(t, userData, "Default", "Preferences") touch(t, userData, "Profile 1", "Preferences") - opts := browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: filepath.Join(userData, "Profile 1") + string(filepath.Separator)} - dirs, err := Discover(testDef("chrome", "ud"), opts) + options := browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: filepath.Join(userData, "Profile 1") + string(filepath.Separator)} + dirs, err := Discover(testBrowser("chrome", "ud"), options) require.NoError(t, err) want := browser.UserDataDir{ - ID: "chrome", Def: testDef("chrome", "ud"), Path: userData, + ID: "chrome", Browser: testBrowser("chrome", "ud"), Path: userData, Profiles: []browser.Profile{{Name: "Profile 1", Dir: "Profile 1"}}, } assert.Equal(t, []browser.UserDataDir{want}, dirs) } -// A flat layout keeps Local State beside its Preferences: it is a user data dir, as before. +// TestDiscover_ProfilePathAtAFlatUserDataDir keeps a flat layout, Local State beside Preferences, a user data dir. func TestDiscover_ProfilePathAtAFlatUserDataDir(t *testing.T) { flat := t.TempDir() touch(t, flat, "Local State") touch(t, flat, "Preferences") touch(t, flat, "History") - dirs, err := Discover(testDef("opera", "ud"), browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: flat}) + dirs, err := Discover(testBrowser("opera", "ud"), browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: flat}) require.NoError(t, err) require.Len(t, dirs, 1) assert.Equal(t, flat, dirs[0].Path) @@ -166,48 +166,48 @@ func TestDiscover_ProfilePathAtAFlatUserDataDir(t *testing.T) { } func TestExtractors_CoverEveryCategory(t *testing.T) { - ex := Extractors(browser.UserDataDir{Def: testDef("chrome")}, browser.Profile{}) - for _, c := range category.All() { - e, ok := ex[c] - if assert.Truef(t, ok, "no extractor for %s", c) { - assert.NotNil(t, e.Extract, c) - assert.NotEmpty(t, e.Sources, c) + extractors := Extractors(browser.UserDataDir{Browser: testBrowser("chrome")}, browser.Profile{}) + 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.FileSpecs, dataCategory) } } } func TestOverrides_KeysAreChromiumBrowsers(t *testing.T) { - for id := range overrides { - def, ok := browser.Lookup(id) - if assert.Truef(t, ok, "override %q names no browser", id) { - assert.Equalf(t, browser.Chromium, def.Base, "override %q is not a Chromium browser", id) + for name := range overrides { + 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) } } } -// A vault's kind must lead a reader back to the same fork's files, or a restore would parse them as plain Chromium. +// TestVaultKind_RoundTripsEveryFork checks a kind leads back to its fork, or restore would parse it as plain Chromium. func TestVaultKind_RoundTripsEveryFork(t *testing.T) { assert.Len(t, kinds, len(overrides)) - for id := range overrides { - kind := VaultKind(browser.Def{ID: id}) - require.NotEqualf(t, kindChromium, kind, "override %q has no keys.json kind", id) - formatID, err := FormatID(kind, "unknown") + for name := range overrides { + kind := VaultKind(browser.Browser{Name: name}) + require.NotEqualf(t, kindChromium, kind, "override %q has no keys.json kind", name) + forkFormatName, err := FormatName(kind, "unknown") require.NoError(t, err) - assert.Equalf(t, categoriesOf(overrides[id]), categoriesOf(overrides[formatID]), "kind %s of %q", kind, id) + assert.Equalf(t, categoriesOf(overrides[name]), categoriesOf(overrides[forkFormatName]), "kind %s of %q", kind, name) } - assert.Equal(t, kindChromium, VaultKind(browser.Def{ID: "chrome"})) - formatID, err := FormatID(kindChromium, "unknown") + assert.Equal(t, kindChromium, VaultKind(browser.Browser{Name: "chrome"})) + plainFormatName, err := FormatName(kindChromium, "unknown") require.NoError(t, err) - assert.Equal(t, "unknown", formatID) - _, err = FormatID("bogus", "unknown") + assert.Equal(t, "unknown", plainFormatName) + _, err = FormatName("bogus", "unknown") assert.Error(t, err) } -func categoriesOf(ex browser.Extractors) []category.Category { +func categoriesOf(extractors browser.Extractors) []category.Category { var out []category.Category - for _, c := range category.All() { - if _, ok := ex[c]; ok { - out = append(out, c) + for _, dataCategory := range category.All() { + if _, ok := extractors[dataCategory]; ok { + out = append(out, dataCategory) } } return out @@ -216,31 +216,31 @@ func categoriesOf(ex browser.Extractors) []category.Category { func TestExtractors_OverridesFollowTheBrowserNotTheDirectory(t *testing.T) { yandex, ok := browser.Lookup("yandex") require.True(t, ok) - ex := Extractors(browser.UserDataDir{ID: "yandex-2", Def: yandex}, browser.Profile{}) - assert.Equal(t, []string{"Ya Passman Data"}, ex[category.Password].Sources[0].Paths) - assert.Equal(t, []string{"Ya Credit Cards"}, ex[category.CreditCard].Sources[0].Paths) + extractors := Extractors(browser.UserDataDir{ID: "yandex-2", Browser: yandex}, browser.Profile{}) + assert.Equal(t, []string{"Ya Passman Data"}, extractors[category.Password].FileSpecs[0].Paths) + assert.Equal(t, []string{"Ya Credit Cards"}, extractors[category.CreditCard].FileSpecs[0].Paths) } func TestExtractors_OperaReadsOpsettings(t *testing.T) { - prefs := createTestJSON(t, "Secure Preferences", `{ + preferencesPath := createTestJSON(t, "Secure Preferences", `{ "extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Opera Ext", "version": "1.0"}}}} }`) - ps := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"Default/Secure Preferences": prefs}), + profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"Default/Secure Preferences": preferencesPath}), browser.Profile{Name: "Default", Dir: "Default"}, nil) - for _, id := range []string{"opera", "opera-gx", "vought"} { - def, ok := browser.Lookup(id) - require.True(t, ok, id) + 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{Def: def}, ps.Profile)[category.Extension].Extract(context.Background(), ps, &out), id) + require.NoError(t, Extractors(browser.UserDataDir{Browser: chromiumBrowser}, profileSnapshot.Profile)[category.Extension].Extract(context.Background(), profileSnapshot, &out), name) got := collected[record.Extension](t, &out) - require.Len(t, got, 1, id) - assert.Equal(t, "Opera Ext", got[0].Name, id) + 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{Def: chrome}, ps.Profile)[category.Extension].Extract(context.Background(), ps, &testCollector{}) + err := Extractors(browser.UserDataDir{Browser: chrome}, profileSnapshot.Profile)[category.Extension].Extract(context.Background(), profileSnapshot, &testCollector{}) require.Error(t, err, "Chrome has no opsettings fallback") } @@ -248,13 +248,13 @@ func TestExtractPasswordStores_LocalBeforeAccount(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)) - ps := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ + profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ "Default/Login Data": local, "Default/Login Data For Account": account, }), browser.Profile{Name: "Default", Dir: "Default"}, nil) var out testCollector - require.NoError(t, extractPasswordStores(context.Background(), ps, &out)) + require.NoError(t, extractPasswordStores(context.Background(), profileSnapshot, &out)) got := collected[record.Login](t, &out) require.Len(t, got, 2) assert.Equal(t, "local-user", got[0].Username) @@ -266,11 +266,11 @@ func TestExtractPasswordStores_LocalBeforeAccount(t *testing.T) { func TestExtractPasswordStores_AccountOnly(t *testing.T) { account := createTestDB(t, "Login Data For Account", loginsSchema, insertLogin("https://account.example", "", "account-user", "", 13360000000000000)) - ps := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"Default/Login Data For Account": account}), + profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"Default/Login Data For Account": account}), browser.Profile{Name: "Default", Dir: "Default"}, nil) var out testCollector - require.NoError(t, extractPasswordStores(context.Background(), ps, &out)) + require.NoError(t, extractPasswordStores(context.Background(), profileSnapshot, &out)) got := collected[record.Login](t, &out) require.Len(t, got, 1) assert.Equal(t, record.StoreAccount, got[0].Store) @@ -280,54 +280,54 @@ func TestExtractPasswordStores_OneBrokenDatabaseKeepsTheOther(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)) - ps := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ + profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ "Default/Login Data": broken, "Default/Login Data For Account": account, }), browser.Profile{Name: "Default", Dir: "Default"}, nil) var out testCollector - require.Error(t, extractPasswordStores(context.Background(), ps, &out)) + require.Error(t, extractPasswordStores(context.Background(), profileSnapshot, &out)) assert.Len(t, collected[record.Login](t, &out), 1) } -// One snapshot serves every profile of a user data dir; each profile must read its own files from it. +// TestExtractors_EachProfileReadsItsOwnFiles reads one snapshot shared by every profile; each must get its own files. func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) { - snap := snapshotOf(t, map[string]string{ + dirSnapshot := snapshotOf(t, map[string]string{ "Default/History": createTestDB(t, "History", urlsSchema, insertURL("https://home.example", "Home", 1, 13350000000000000)), "Profile 1/History": createTestDB(t, "History", urlsSchema, insertURL("https://work.example", "Work", 1, 13350000000000000)), }) - dir := browser.UserDataDir{Def: testDef("chrome")} + dir := browser.UserDataDir{Browser: testBrowser("chrome")} want := map[string]string{"Default": "Home", "Profile 1": "Work"} - for _, p := range []browser.Profile{{Name: "Default", Dir: "Default"}, {Name: "Profile 1", Dir: "Profile 1"}} { + for _, profile := range []browser.Profile{{Name: "Default", Dir: "Default"}, {Name: "Profile 1", Dir: "Profile 1"}} { var out testCollector - require.NoError(t, Extractors(dir, p)[category.History].Extract(context.Background(), browser.NewProfileSnapshot(snap, p, nil), &out)) + require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewProfileSnapshot(dirSnapshot, profile, nil), &out)) got := collected[record.History](t, &out) - require.Len(t, got, 1, p.Name) - assert.Equal(t, want[p.Name], got[0].Title, p.Name) + require.Len(t, got, 1, profile.Name) + assert.Equal(t, want[profile.Name], got[0].Title, profile.Name) } } func TestKeyLocator(t *testing.T) { - p := browser.Platform{KeychainLabel: "Test Safe Storage", Exe: "chrome.exe", ABE: masterkey.ABEChromeBase} - dir := browser.UserDataDir{ID: "chrome", Def: browser.Def{ID: "chrome", Base: browser.Chromium, Darwin: p, Linux: p, Windows: p}} + platform := browser.Platform{KeychainLabel: "Test Safe Storage", Exe: "chrome.exe", ABE: masterkey.ABEChromeBase} + dir := browser.UserDataDir{ID: "chrome", Browser: browser.Browser{Name: "chrome", Base: browser.Chromium, Darwin: platform, Linux: platform, Windows: platform}} - snap := snapshotOf(t, map[string]string{"Local State": createTestJSON(t, "Local State", "{}")}) - loc, err := KeyLocator(dir, snap) + dirSnapshot := snapshotOf(t, map[string]string{"Local State": createTestJSON(t, "Local State", "{}")}) + locator, err := KeyLocator(dir, dirSnapshot) require.NoError(t, err) - assert.NotEmpty(t, loc.LocalState) - assert.Equal(t, "Test Safe Storage", loc.KeychainLabel) - assert.Equal(t, "chrome.exe", loc.Exe) - assert.Equal(t, masterkey.ABEChromeBase, loc.ABE) + assert.NotEmpty(t, locator.LocalState) + assert.Equal(t, "Test Safe Storage", locator.KeychainLabel) + assert.Equal(t, "chrome.exe", locator.Exe) + assert.Equal(t, masterkey.ABEChromeBase, locator.ABE) - loc, err = KeyLocator(dir, snapshotOf(t, nil)) + locator, err = KeyLocator(dir, snapshotOf(t, nil)) require.NoError(t, err, "a user data dir without Local State still has keys on macOS and Linux") - assert.Empty(t, loc.LocalState) + assert.Empty(t, locator.LocalState) } -func TestArchiveSources(t *testing.T) { - assert.Equal(t, []browser.Source{ +func TestArchiveFileSpecs(t *testing.T) { + assert.Equal(t, []browser.FileSpec{ localState, {Paths: []string{"Preferences"}, Optional: true}, {Paths: []string{"Preferences_02"}, Optional: true}, - }, ArchiveSources(browser.UserDataDir{})) + }, ArchiveFileSpecs(browser.UserDataDir{})) } diff --git a/internal/browser/chromium/cipher.go b/internal/browser/chromium/cipher.go index 2ce1016..b119706 100644 --- a/internal/browser/chromium/cipher.go +++ b/internal/browser/chromium/cipher.go @@ -18,7 +18,7 @@ const ( cipherV20 cipherVersion = "v20" - // Recognized only to report a known gap: v12 is not implemented yet. + // cipherV12 is recognized only to report a known gap: v12 is not implemented yet. cipherV12 cipherVersion = "v12" cipherDPAPI cipherVersion = "dpapi" @@ -51,7 +51,7 @@ const gcmNonceSize = 12 var chromiumCBCIV = bytes.Repeat([]byte{0x20}, aes.BlockSize) -// Chromium's decrypt-only fallback for data a KWallet race corrupted in Chrome ~89 (crbug.com/40055416). +// kEmptyKey is Chromium's decrypt-only fallback for data a KWallet race corrupted in Chrome ~89 (crbug.com/40055416). var kEmptyKey = crypto.PBKDF2Key([]byte(""), []byte("saltysalt"), 1, 16, sha1.New) func decryptGCM(key, ciphertext []byte) ([]byte, error) { diff --git a/internal/browser/chromium/cipher_test.go b/internal/browser/chromium/cipher_test.go index e527d90..56f8d06 100644 --- a/internal/browser/chromium/cipher_test.go +++ b/internal/browser/chromium/cipher_test.go @@ -26,9 +26,9 @@ func TestDetectVersion(t *testing.T) { {"nil input", nil, cipherDPAPI}, {"unknown prefix", []byte("xyz_data"), cipherDPAPI}, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.want, detectVersion(tt.ciphertext)) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + assert.Equal(t, testCase.want, detectVersion(testCase.ciphertext)) }) } } @@ -55,16 +55,16 @@ func TestDecryptGCM_CrossPlatform(t *testing.T) { func TestDecryptCBC_CrossPlatform(t *testing.T) { plaintext := []byte("posix_v10_value") - enc, err := crypto.AESCBCEncrypt(cbcKey, chromiumCBCIV, plaintext) + encrypted, err := crypto.AESCBCEncrypt(cbcKey, chromiumCBCIV, plaintext) require.NoError(t, err) - ciphertext := append([]byte("v10"), enc...) + ciphertext := append([]byte("v10"), encrypted...) got, err := decryptCBC(cbcKey, ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) } -// Pins the derived kEmptyKey to the reference bytes in Chromium's os_crypt_linux.cc. +// TestKEmptyKey_MatchesChromium pins the derived kEmptyKey to the reference bytes in Chromium's os_crypt_linux.cc. func TestKEmptyKey_MatchesChromium(t *testing.T) { want := []byte{ 0xd0, 0xd0, 0xec, 0x9c, 0x7d, 0x77, 0xd4, 0x3a, diff --git a/internal/browser/chromium/decrypt.go b/internal/browser/chromium/decrypt.go index 10c0e72..e0461b5 100644 --- a/internal/browser/chromium/decrypt.go +++ b/internal/browser/chromium/decrypt.go @@ -6,7 +6,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// A profile can mix versions, so a missing key fails only the values sealed under that version. +// decryptValue fails only the values sealed under a version whose key is missing, since a profile can mix versions. func decryptValue(masterKeys masterkey.Set, ciphertext []byte) ([]byte, error) { if len(ciphertext) == 0 { return nil, nil diff --git a/internal/browser/chromium/decrypt_mixed_test.go b/internal/browser/chromium/decrypt_mixed_test.go index 76e0251..e0a3020 100644 --- a/internal/browser/chromium/decrypt_mixed_test.go +++ b/internal/browser/chromium/decrypt_mixed_test.go @@ -11,40 +11,40 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// Regression for #578: a profile mixing cipher versions must route each value to its own version's key. +// TestDecryptValue_MixedTier guards #578: each value in a mixed-version profile routes to its own version's key. func TestDecryptValue_MixedTier(t *testing.T) { - k10 := bytes.Repeat([]byte{0x10}, 16) // V10 slot key (wrong for v20 payload) - k11 := bytes.Repeat([]byte{0x11}, 16) // V11 slot key (wrong for v20 payload) - k20 := bytes.Repeat([]byte{0x20}, 16) // V20 slot key (correct for v20 payload) + v10Key := bytes.Repeat([]byte{0x10}, 16) // V10 slot key (wrong for v20 payload) + v11Key := bytes.Repeat([]byte{0x11}, 16) // V11 slot key (wrong for v20 payload) + v20Key := bytes.Repeat([]byte{0x20}, 16) // V20 slot key (correct for v20 payload) plaintext := []byte("cookie-value-encrypted-with-k20") nonce := []byte("v20_nonce_12") // 12-byte AES-GCM nonce - gcmEnc, err := crypto.AESGCMEncrypt(k20, nonce, plaintext) + gcmEnc, err := crypto.AESGCMEncrypt(v20Key, nonce, plaintext) require.NoError(t, err) v20Ciphertext := append([]byte("v20"), append(nonce, gcmEnc...)...) t.Run("all tiers populated: v20 picks V20, decrypts", func(t *testing.T) { - got, err := decryptValue(masterkey.Set{masterkey.V10: k10, masterkey.V11: k11, masterkey.V20: k20}, v20Ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V10: v10Key, masterkey.V11: v11Key, masterkey.V20: v20Key}, v20Ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) }) t.Run("V20 holds wrong key: v20 still picks V20 slot (not V10/V11), errors", func(t *testing.T) { // Wrong keys in the V20 slot must fail even when another slot holds the right one: routing is by prefix. - _, err := decryptValue(masterkey.Set{masterkey.V10: k20, masterkey.V11: k20, masterkey.V20: k10}, v20Ciphertext) + _, err := decryptValue(masterkey.Set{masterkey.V10: v20Key, masterkey.V11: v20Key, masterkey.V20: v10Key}, v20Ciphertext) require.Error(t, err) }) t.Run("only V20 populated: v20 still decrypts", func(t *testing.T) { // Missing V10 and V11 keys must not block v20 values. - got, err := decryptValue(masterkey.Set{masterkey.V20: k20}, v20Ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V20: v20Key}, v20Ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) }) t.Run("V20 slot unpopulated: v20 errors (no key to use)", func(t *testing.T) { - _, err := decryptValue(masterkey.Set{masterkey.V10: k10, masterkey.V11: k11}, v20Ciphertext) + _, err := decryptValue(masterkey.Set{masterkey.V10: v10Key, masterkey.V11: v11Key}, v20Ciphertext) require.Error(t, err) }) } diff --git a/internal/browser/chromium/decrypt_test.go b/internal/browser/chromium/decrypt_test.go index 61b6785..d6e4ceb 100644 --- a/internal/browser/chromium/decrypt_test.go +++ b/internal/browser/chromium/decrypt_test.go @@ -38,17 +38,17 @@ func TestDecryptValue_V10(t *testing.T) { }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := decryptValue(masterkey.Set{masterkey.V10: tt.key}, v10Ciphertext) - if tt.wantErrMsg != "" { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + got, err := decryptValue(masterkey.Set{masterkey.V10: testCase.key}, v10Ciphertext) + if testCase.wantErrMsg != "" { require.Error(t, err) - assert.Contains(t, err.Error(), tt.wantErrMsg) + assert.Contains(t, err.Error(), testCase.wantErrMsg) assert.Nil(t, got) return } require.NoError(t, err) - assert.Equal(t, tt.want, got) + assert.Equal(t, testCase.want, got) }) } } @@ -66,39 +66,39 @@ func TestDecryptValue_V11(t *testing.T) { assert.Equal(t, plaintext, got) } -// Linux analog of #578: v10 and v11 values in one profile must each route to their own key. +// TestDecryptValue_V10_V11_SlotSeparation is #578 on Linux: v10 and v11 values each route to their own key. func TestDecryptValue_V10_V11_SlotSeparation(t *testing.T) { - k10 := bytes.Repeat([]byte{0x10}, 16) // V10 slot key (peanuts-derived kV10Key) - k11 := bytes.Repeat([]byte{0x11}, 16) // V11 slot key (keyring-derived kV11Key) + v10Key := bytes.Repeat([]byte{0x10}, 16) // V10 slot key (peanuts-derived kV10Key) + v11Key := bytes.Repeat([]byte{0x11}, 16) // V11 slot key (keyring-derived kV11Key) iv := bytes.Repeat([]byte{0x20}, 16) // matches crypto.chromiumCBCIV on darwin/linux v10plain := []byte("password-from-v10-era") v11plain := []byte("password-from-v11-era") - v10Enc, err := crypto.AESCBCEncrypt(k10, iv, v10plain) + v10Enc, err := crypto.AESCBCEncrypt(v10Key, iv, v10plain) require.NoError(t, err) v10Ciphertext := append([]byte("v10"), v10Enc...) - v11Enc, err := crypto.AESCBCEncrypt(k11, iv, v11plain) + v11Enc, err := crypto.AESCBCEncrypt(v11Key, iv, v11plain) require.NoError(t, err) v11Ciphertext := append([]byte("v11"), v11Enc...) - mk := masterkey.Set{masterkey.V10: k10, masterkey.V11: k11} + masterKeys := masterkey.Set{masterkey.V10: v10Key, masterkey.V11: v11Key} t.Run("v10 ciphertext decrypts via V10 slot", func(t *testing.T) { - got, err := decryptValue(mk, v10Ciphertext) + got, err := decryptValue(masterKeys, v10Ciphertext) require.NoError(t, err) assert.Equal(t, v10plain, got) }) t.Run("v11 ciphertext decrypts via V11 slot", func(t *testing.T) { - got, err := decryptValue(mk, v11Ciphertext) + got, err := decryptValue(masterKeys, v11Ciphertext) require.NoError(t, err) assert.Equal(t, v11plain, got) }) t.Run("swapped keys fail both directions", func(t *testing.T) { - swapped := masterkey.Set{masterkey.V10: k11, masterkey.V11: k10} + swapped := masterkey.Set{masterkey.V10: v11Key, masterkey.V11: v10Key} _, err := decryptValue(swapped, v10Ciphertext) require.Error(t, err, "v10 with V11's key must fail") _, err = decryptValue(swapped, v11Ciphertext) diff --git a/internal/browser/chromium/decrypt_v20_test.go b/internal/browser/chromium/decrypt_v20_test.go index c191684..1505bd2 100644 --- a/internal/browser/chromium/decrypt_v20_test.go +++ b/internal/browser/chromium/decrypt_v20_test.go @@ -10,7 +10,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/masterkey" ) -// v20's format is the same on every OS, so CI on Linux and macOS guards its routing too. +// TestDecryptValue_V20 runs on every OS, since v20's format is the same everywhere, so all CI guards its routing. func TestDecryptValue_V20(t *testing.T) { plaintext := []byte("v20_test_value") nonce := []byte("v20_nonce_12") // 12-byte AES-GCM nonce @@ -32,17 +32,17 @@ func TestDecryptValue_V20_ShortCiphertext(t *testing.T) { require.Error(t, err) } -// A v10 value sealed with a 32-byte key, as on Windows, decrypts on any host: the cross-OS guarantee. +// TestDecryptValue_V10_CrossHostGCM decrypts a v10 value sealed with a 32-byte key, as on Windows, on any host. func TestDecryptValue_V10_CrossHostGCM(t *testing.T) { - key32 := []byte("0123456789abcdef0123456789abcdef") // 32 bytes + aesKey := []byte("0123456789abcdef0123456789abcdef") // 32 bytes plaintext := []byte("v10_cross_host") nonce := []byte("v10_nonce_12") // 12-byte AES-GCM nonce - gcm, err := crypto.AESGCMEncrypt(key32, nonce, plaintext) + gcm, err := crypto.AESGCMEncrypt(aesKey, nonce, plaintext) require.NoError(t, err) ciphertext := append([]byte("v10"), append(nonce, gcm...)...) - got, err := decryptValue(masterkey.Set{masterkey.V10: key32}, ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V10: aesKey}, ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) } diff --git a/internal/browser/chromium/decrypt_windows_test.go b/internal/browser/chromium/decrypt_windows_test.go index 8f3f038..63eb01a 100644 --- a/internal/browser/chromium/decrypt_windows_test.go +++ b/internal/browser/chromium/decrypt_windows_test.go @@ -35,12 +35,12 @@ func encryptWithDPAPI(plaintext []byte) ([]byte, error) { pbData *byte } - r, _, err := protectDataProc.Call( + returned, _, err := protectDataProc.Call( uintptr(unsafe.Pointer(&inBlob)), 0, 0, 0, 0, 0, uintptr(unsafe.Pointer(&outBlob)), ) - if r == 0 { + if returned == 0 { return nil, fmt.Errorf("CryptProtectData failed: %w", err) } defer localFreeProc.Call(uintptr(unsafe.Pointer(outBlob.pbData))) @@ -53,17 +53,17 @@ func encryptWithDPAPI(plaintext []byte) ([]byte, error) { func TestDecryptValue_V10_Windows(t *testing.T) { // Windows v10 keys are 32 bytes, which routes them to GCM. - key32 := []byte("0123456789abcdef0123456789abcdef") + aesKey := []byte("0123456789abcdef0123456789abcdef") plaintext := []byte("test_secret_value") nonce := []byte("123456789012") // 12-byte nonce - gcmEncrypted, err := crypto.AESGCMEncrypt(key32, nonce, plaintext) + gcmEncrypted, err := crypto.AESGCMEncrypt(aesKey, nonce, plaintext) require.NoError(t, err) // v10 format on Windows: "v10" + nonce(12) + encrypted ciphertext := append([]byte("v10"), append(nonce, gcmEncrypted...)...) - got, err := decryptValue(masterkey.Set{masterkey.V10: key32}, ciphertext) + got, err := decryptValue(masterkey.Set{masterkey.V10: aesKey}, ciphertext) require.NoError(t, err) assert.Equal(t, plaintext, got) } diff --git a/internal/browser/chromium/extract_cookie.go b/internal/browser/chromium/extract_cookie.go index 5fb88fc..d7ebbe9 100644 --- a/internal/browser/chromium/extract_cookie.go +++ b/internal/browser/chromium/extract_cookie.go @@ -71,7 +71,7 @@ func extractCookies(masterKeys masterkey.Set, path string, out browser.Collector return nil } -// Chrome 130+ prepends SHA256(host_key) to the value; a value whose prefix does not match is returned unchanged. +// stripCookieHash removes the SHA256(host_key) Chrome 130+ prepends; a value without that prefix is returned as is. func stripCookieHash(value []byte, hostKey string) []byte { if len(value) < sha256.Size { return value diff --git a/internal/browser/chromium/extract_cookie_test.go b/internal/browser/chromium/extract_cookie_test.go index 27672d1..7b47450 100644 --- a/internal/browser/chromium/extract_cookie_test.go +++ b/internal/browser/chromium/extract_cookie_test.go @@ -86,10 +86,10 @@ func TestStripCookieHash(t *testing.T) { }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := stripCookieHash(tt.value, tt.hostKey) - assert.Equal(t, tt.want, string(got)) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + got := stripCookieHash(testCase.value, testCase.hostKey) + assert.Equal(t, testCase.want, string(got)) }) } } diff --git a/internal/browser/chromium/extract_creditcard_test.go b/internal/browser/chromium/extract_creditcard_test.go index a5e0ab1..28d338e 100644 --- a/internal/browser/chromium/extract_creditcard_test.go +++ b/internal/browser/chromium/extract_creditcard_test.go @@ -74,23 +74,23 @@ func TestExtractYandexCreditCards(t *testing.T) { require.Len(t, got, 2) byGUID := map[string]int{} - for i, c := range got { - byGUID[c.GUID] = i + for i, card := range got { + byGUID[card.GUID] = i } - c1 := got[byGUID["card-1"]] - assert.Equal(t, "Alice Smith", c1.Name) - assert.Equal(t, "Personal Visa", c1.NickName) - assert.Equal(t, "2030", c1.ExpYear) - assert.Equal(t, "06", c1.ExpMonth) - assert.Equal(t, "4111111111111111", c1.Number) - assert.Equal(t, "123", c1.CVC) - assert.Equal(t, "main card", c1.Comment) + firstCard := got[byGUID["card-1"]] + assert.Equal(t, "Alice Smith", firstCard.Name) + assert.Equal(t, "Personal Visa", firstCard.NickName) + assert.Equal(t, "2030", firstCard.ExpYear) + assert.Equal(t, "06", firstCard.ExpMonth) + assert.Equal(t, "4111111111111111", firstCard.Number) + assert.Equal(t, "123", firstCard.CVC) + assert.Equal(t, "main card", firstCard.Comment) - c2 := got[byGUID["card-2"]] - assert.Equal(t, "5555555555554444", c2.Number) - assert.Equal(t, "456", c2.CVC) - assert.Empty(t, c2.Comment) + secondCard := got[byGUID["card-2"]] + assert.Equal(t, "5555555555554444", secondCard.Number) + assert.Equal(t, "456", secondCard.CVC) + assert.Empty(t, secondCard.Comment) } func TestExtractYandexCreditCards_WrongMasterKey(t *testing.T) { diff --git a/internal/browser/chromium/extract_extension.go b/internal/browser/chromium/extract_extension.go index 6243b80..184a331 100644 --- a/internal/browser/chromium/extract_extension.go +++ b/internal/browser/chromium/extract_extension.go @@ -20,7 +20,7 @@ func extractExtensions(path string, out browser.Collector) error { return extractExtensionsWithKeys(path, defaultExtensionKeys, out) } -// Browser variants keep extension settings under other JSON paths, such as Opera's extensions.opsettings. +// extractExtensionsWithKeys takes the JSON paths, because variants such as Opera keep extension settings elsewhere. func extractExtensionsWithKeys(path string, keys []string, out browser.Collector) error { data, err := os.ReadFile(path) if err != nil { @@ -39,15 +39,15 @@ func extractExtensionsWithKeys(path string, keys []string, out browser.Collector } var extensions []record.Extension - settings.ForEach(func(id, ext gjson.Result) bool { + settings.ForEach(func(id, extension gjson.Result) bool { // Skip system/component extensions // https://source.chromium.org/chromium/chromium/src/+/main:extensions/common/mojom/manifest.mojom - location := ext.Get("location").Int() + location := extension.Get("location").Int() if location == 5 || location == 10 { return true } - manifest := ext.Get("manifest") + manifest := extension.Get("manifest") if !manifest.Exists() { return true } @@ -58,7 +58,7 @@ func extractExtensionsWithKeys(path string, keys []string, out browser.Collector Description: manifest.Get("description").String(), Version: manifest.Get("version").String(), HomepageURL: manifest.Get("homepage_url").String(), - Enabled: isExtensionEnabled(ext), + Enabled: isExtensionEnabled(extension), }) return true }) @@ -67,13 +67,13 @@ func extractExtensionsWithKeys(path string, keys []string, out browser.Collector return nil } -// Modern Chrome sets disable_reasons (empty means enabled); older Chrome sets state, where 1 means enabled. -func isExtensionEnabled(ext gjson.Result) bool { - reasons := ext.Get("disable_reasons") +// isExtensionEnabled reads disable_reasons (empty means enabled), or in older Chrome state (1 means enabled). +func isExtensionEnabled(extension gjson.Result) bool { + reasons := extension.Get("disable_reasons") if reasons.Exists() { return reasons.IsArray() && len(reasons.Array()) == 0 } - return ext.Get("state").Int() == 1 + return extension.Get("state").Int() == 1 } func extractOperaExtensions(path string, out browser.Collector) error { diff --git a/internal/browser/chromium/extract_extension_test.go b/internal/browser/chromium/extract_extension_test.go index 5491d31..ae6144e 100644 --- a/internal/browser/chromium/extract_extension_test.go +++ b/internal/browser/chromium/extract_extension_test.go @@ -54,11 +54,11 @@ func TestExtractExtensions(t *testing.T) { // gjson.ForEach walks a map, so the order may vary. ids := map[string]bool{} - for _, ext := range got { - ids[ext.ID] = true - assert.NotEmpty(t, ext.Name) - assert.NotEmpty(t, ext.Version) - assert.NotEmpty(t, ext.Description) + for _, extension := range got { + ids[extension.ID] = true + assert.NotEmpty(t, extension.Name) + assert.NotEmpty(t, extension.Version) + assert.NotEmpty(t, extension.Description) } assert.True(t, ids["abc123"]) assert.True(t, ids["def456"]) diff --git a/internal/browser/chromium/extract_password.go b/internal/browser/chromium/extract_password.go index 0402b2a..ef6698c 100644 --- a/internal/browser/chromium/extract_password.go +++ b/internal/browser/chromium/extract_password.go @@ -27,12 +27,12 @@ func extractPasswordsWithQuery(masterKeys masterkey.Set, path string, store reco logins, err := sqlitex.QueryRows(path, false, query, func(rows *sql.Rows) (record.Login, error) { var url, username string - var pwd []byte + var encryptedPassword []byte var created int64 - if err := rows.Scan(&url, &username, &pwd, &created); err != nil { + if err := rows.Scan(&url, &username, &encryptedPassword, &created); err != nil { return record.Login{}, err } - password, err := decryptValue(masterKeys, pwd) + password, err := decryptValue(masterKeys, encryptedPassword) if err != nil { out.Fail(fmt.Errorf("decrypt password for %s: %w", url, err)) } @@ -51,7 +51,7 @@ func extractPasswordsWithQuery(masterKeys masterkey.Set, path string, store reco return nil } -// The URL column is origin_url, which the per-row AAD covers, not action_url. +// extractYandexPasswords reads origin_url, which the per-row AAD covers, not action_url. func extractYandexPasswords(masterKeys masterkey.Set, path string, out browser.Collector) error { dataKey, keyErr := loadYandexDataKey(path, masterKeys[masterkey.V10]) diff --git a/internal/browser/chromium/extract_password_test.go b/internal/browser/chromium/extract_password_test.go index d8e2ac4..3ec5815 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) { assert.Equal(t, record.StoreLocal, got[1].Store) } -// An undecryptable credential is still listed, or a missing key would silently shrink the export. +// TestExtractPasswords_UndecryptableBlobStillListed keeps such a login, or a missing key would shrink the export. func TestExtractPasswords_UndecryptableBlobStillListed(t *testing.T) { path := createTestDB(t, "Login Data", loginsSchema, insertLogin("https://enc.com", "https://enc.com/login", "carol", "763130deadbeef", 13350000000000000), @@ -122,8 +122,8 @@ func TestExtractYandexPasswords_WithoutAKeyKeepsTheLogins(t *testing.T) { require.NoError(t, extractYandexPasswords(nil, path, &out)) logins := collected[record.Login](t, &out) require.Len(t, logins, 2) - for _, l := range logins { - assert.Empty(t, l.Password) + for _, login := range logins { + assert.Empty(t, login.Password) } assert.Len(t, out.fails, 2, "each login without its password is a record-level problem") } @@ -152,9 +152,9 @@ func TestExtractYandexPasswords_WrongMasterKey(t *testing.T) { func TestYandexLoginAAD_NoMasterPassword(t *testing.T) { got := yandexLoginAAD("https://example.com/", "user", "alice", "pass", "https://example.com/", nil) - h := sha1.New() - h.Write([]byte("https://example.com/\x00user\x00alice\x00pass\x00https://example.com/")) - want := h.Sum(nil) + hasher := sha1.New() + hasher.Write([]byte("https://example.com/\x00user\x00alice\x00pass\x00https://example.com/")) + want := hasher.Sum(nil) assert.Equal(t, want, got) assert.Len(t, got, sha1.Size) diff --git a/internal/browser/chromium/extract_storage.go b/internal/browser/chromium/extract_storage.go index ccd4905..97bc90d 100644 --- a/internal/browser/chromium/extract_storage.go +++ b/internal/browser/chromium/extract_storage.go @@ -34,28 +34,28 @@ func extractLocalStorage(path string, out browser.Collector) error { if _, err := os.Stat(path); err != nil { return fmt.Errorf("leveldb path %q: %w", path, err) } - db, err := leveldb.OpenFile(path, readOnly) + database, err := leveldb.OpenFile(path, readOnly) if err != nil { return err } - defer db.Close() + defer database.Close() var entries []record.LocalStorage - iter := db.NewIterator(nil, nil) - defer iter.Release() + cursor := database.NewIterator(nil, nil) + defer cursor.Release() - for iter.Next() { - entry, ok := parseLocalStorageEntry(iter.Key(), iter.Value()) + for cursor.Next() { + entry, ok := parseLocalStorageEntry(cursor.Key(), cursor.Value()) if !ok { continue } entries = append(entries, entry) } emit(out, entries) - return iter.Error() + return cursor.Error() } -// VERSION and unknown keys are dropped; META entries are kept with IsMeta set. +// parseLocalStorageEntry drops VERSION and unknown keys and keeps META entries with IsMeta set. func parseLocalStorageEntry(key, value []byte) (record.LocalStorage, bool) { switch { case bytes.Equal(key, []byte(localStorageVersionKey)): @@ -99,41 +99,41 @@ func parseLocalStorageDataEntry(key, value []byte) record.LocalStorage { return entry } -// The first byte selects the encoding: 0x01 is Latin-1, 0x00 is UTF-16 LE. -func decodeChromiumString(b []byte) (string, error) { - if len(b) == 0 { +// decodeChromiumString switches on the first byte: 0x01 is Latin-1, 0x00 is UTF-16 LE. +func decodeChromiumString(encoded []byte) (string, error) { + if len(encoded) == 0 { return "", fmt.Errorf("empty chromium string") } - switch b[0] { + switch encoded[0] { case chromiumStringLatin1Format: - return decodeLatin1(b[1:]), nil + return decodeLatin1(encoded[1:]), nil case chromiumStringUTF16Format: - return decodeUTF16LE(b[1:]) + return decodeUTF16LE(encoded[1:]) default: - return "", fmt.Errorf("unknown chromium string format 0x%02x", b[0]) + return "", fmt.Errorf("unknown chromium string format 0x%02x", encoded[0]) } } -func decodeLatin1(b []byte) string { - runes := make([]rune, len(b)) - for i, c := range b { - runes[i] = rune(c) +func decodeLatin1(encoded []byte) string { + runes := make([]rune, len(encoded)) + for i, char := range encoded { + runes[i] = rune(char) } return string(runes) } -func decodeUTF16LE(b []byte) (string, error) { - if len(b) == 0 { +func decodeUTF16LE(encoded []byte) (string, error) { + if len(encoded) == 0 { return "", nil } - if len(b)%2 != 0 { - return "", fmt.Errorf("invalid UTF-16 byte length %d", len(b)) + if len(encoded)%2 != 0 { + return "", fmt.Errorf("invalid UTF-16 byte length %d", len(encoded)) } - u16s := make([]uint16, len(b)/2) - for i := range u16s { - u16s[i] = binary.LittleEndian.Uint16(b[i*2:]) + units := make([]uint16, len(encoded)/2) + for i := range units { + units[i] = binary.LittleEndian.Uint16(encoded[i*2:]) } - return string(utf16.Decode(u16s)), nil + return string(utf16.Decode(units)), nil } func decodeLocalStorageValue(value []byte) string { @@ -150,21 +150,21 @@ func decodeLocalStorageValue(value []byte) string { return decoded } -// Keys are namespace-- -> map_id and map-- -> UTF-16 LE value; the rest is metadata. +// extractSessionStorage joins namespace-- -> map_id with map-- -> UTF-16 LE value. func extractSessionStorage(path string, out browser.Collector) error { if _, err := os.Stat(path); err != nil { return fmt.Errorf("leveldb path %q: %w", path, err) } - db, err := leveldb.OpenFile(path, readOnly) + database, err := leveldb.OpenFile(path, readOnly) if err != nil { return err } - defer db.Close() + defer database.Close() originByMapID := make(map[string]string) - iter := db.NewIterator(nil, nil) - for iter.Next() { - key := string(iter.Key()) + namespaceCursor := database.NewIterator(nil, nil) + for namespaceCursor.Next() { + key := string(namespaceCursor.Key()) if !strings.HasPrefix(key, "namespace-") { continue } @@ -173,38 +173,38 @@ func extractSessionStorage(path string, out browser.Collector) error { if origin == "" { continue } - mapID := string(iter.Value()) + mapID := string(namespaceCursor.Value()) originByMapID[mapID] = origin } - iter.Release() - if err := iter.Error(); err != nil { + namespaceCursor.Release() + if err := namespaceCursor.Error(); err != nil { return fmt.Errorf("read namespace entries: %w", err) } var entries []record.SessionStorage - iter2 := db.NewIterator(nil, nil) - defer iter2.Release() + mapCursor := database.NewIterator(nil, nil) + defer mapCursor.Release() mapPrefix := []byte("map-") - for iter2.Next() { - key := iter2.Key() + for mapCursor.Next() { + key := mapCursor.Key() if !bytes.HasPrefix(key, mapPrefix) { continue } rest := key[len(mapPrefix):] // "-" - sep := bytes.IndexByte(rest, '-') - if sep < 0 { + separatorIndex := bytes.IndexByte(rest, '-') + if separatorIndex < 0 { continue } - mapID := string(rest[:sep]) - keyName := string(rest[sep+1:]) + mapID := string(rest[:separatorIndex]) + keyName := string(rest[separatorIndex+1:]) origin := originByMapID[mapID] if origin == "" { origin = mapID // fallback to map_id if namespace not found } - value := decodeSessionStorageValue(iter2.Value()) + value := decodeSessionStorageValue(mapCursor.Value()) entries = append(entries, record.SessionStorage{ URL: origin, Key: keyName, @@ -212,20 +212,20 @@ func extractSessionStorage(path string, out browser.Collector) error { }) } emit(out, entries) - return iter2.Error() + return mapCursor.Error() } func extractNamespaceOrigin(key string) string { for _, prefix := range []string{"-https://", "-http://", "-chrome://"} { - idx := strings.Index(key, prefix) - if idx >= 0 { - return key[idx+1:] + index := strings.Index(key, prefix) + if index >= 0 { + return key[index+1:] } } return "" } -// Values are raw UTF-16 LE, without localStorage's format byte. +// decodeSessionStorageValue reads raw UTF-16 LE, which has no localStorage format byte. func decodeSessionStorageValue(value []byte) string { if len(value) == 0 { return "" diff --git a/internal/browser/chromium/extract_storage_test.go b/internal/browser/chromium/extract_storage_test.go index 9b3db62..3f2a871 100644 --- a/internal/browser/chromium/extract_storage_test.go +++ b/internal/browser/chromium/extract_storage_test.go @@ -63,16 +63,16 @@ func TestDecodeChromiumString(t *testing.T) { }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := decodeChromiumString(tt.input) - if tt.wantErr != "" { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + got, err := decodeChromiumString(testCase.input) + if testCase.wantErr != "" { require.Error(t, err) - assert.Contains(t, err.Error(), tt.wantErr) + assert.Contains(t, err.Error(), testCase.wantErr) return } require.NoError(t, err) - assert.Equal(t, tt.want, got) + assert.Equal(t, testCase.want, got) }) } } @@ -140,17 +140,17 @@ func TestParseLocalStorageEntry(t *testing.T) { }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - entry, parsed := parseLocalStorageEntry(tt.key, tt.value) - assert.Equal(t, tt.wantParsed, parsed) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + entry, parsed := parseLocalStorageEntry(testCase.key, testCase.value) + assert.Equal(t, testCase.wantParsed, parsed) if !parsed { return } - assert.Equal(t, tt.wantMeta, entry.IsMeta) - assert.Equal(t, tt.wantURL, entry.URL) - assert.Equal(t, tt.wantKey, entry.Key) - assert.Equal(t, tt.wantValue, entry.Value) + assert.Equal(t, testCase.wantMeta, entry.IsMeta) + assert.Equal(t, testCase.wantURL, entry.URL) + assert.Equal(t, testCase.wantKey, entry.Key) + assert.Equal(t, testCase.wantValue, entry.Value) }) } } @@ -189,14 +189,14 @@ func TestExtractLocalStorage(t *testing.T) { metaCount := 0 byKey := map[string]string{} - for _, e := range got { - assert.Equal(t, "https://example.com", e.URL) - if e.IsMeta { + for _, entry := range got { + assert.Equal(t, "https://example.com", entry.URL) + if entry.IsMeta { metaCount++ - assert.Contains(t, e.Value, "meta data, value bytes is") + assert.Contains(t, entry.Value, "meta data, value bytes is") continue } - byKey[e.Key] = e.Value + byKey[entry.Key] = entry.Value } assert.Equal(t, 2, metaCount) assert.Equal(t, "abc123", byKey["token"]) @@ -220,7 +220,7 @@ func TestExtractSessionStorage(t *testing.T) { assert.Equal(t, "abc123", byKey["https://example.com//token"]) } -// Opening the copy read-write replays its journal into new files; on Windows that write can fail and lose the profile. +// TestExtractStorage_LeavesTheCopyUnchanged opens read-only, since a journal replay can fail on Windows and lose data. func TestExtractStorage_LeavesTheCopyUnchanged(t *testing.T) { tests := []struct { name string @@ -230,12 +230,12 @@ func TestExtractStorage_LeavesTheCopyUnchanged(t *testing.T) { {name: "localstorage", setup: setupLocalStorageLevelDB, extract: extractLocalStorage}, {name: "sessionstorage", setup: setupSessionStorageLevelDB, extract: extractSessionStorage}, } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - dir := tt.setup(t) + for _, testCase := range tests { + testCase := testCase + t.Run(testCase.name, func(t *testing.T) { + dir := testCase.setup(t) before := levelDBFiles(t, dir) - require.NoError(t, tt.extract(dir, &testCollector{})) + require.NoError(t, testCase.extract(dir, &testCollector{})) assert.Equal(t, before, levelDBFiles(t, dir)) }) } @@ -246,36 +246,36 @@ func levelDBFiles(t *testing.T, dir string) map[string]string { entries, err := os.ReadDir(dir) require.NoError(t, err) files := make(map[string]string, len(entries)) - for _, e := range entries { - data, err := os.ReadFile(filepath.Join(dir, e.Name())) + for _, entry := range entries { + data, err := os.ReadFile(filepath.Join(dir, entry.Name())) require.NoError(t, err) - files[e.Name()] = string(data) + files[entry.Name()] = string(data) } return files } -func testEncodeLatin1(s string) []byte { - return append([]byte{chromiumStringLatin1Format}, []byte(s)...) +func testEncodeLatin1(text string) []byte { + return append([]byte{chromiumStringLatin1Format}, []byte(text)...) } -func testEncodeUTF16(s string) []byte { - encoded := utf16.Encode([]rune(s)) +func testEncodeUTF16(text string) []byte { + encoded := utf16.Encode([]rune(text)) result := make([]byte, 1, 1+len(encoded)*2) result[0] = chromiumStringUTF16Format - for _, r := range encoded { + for _, unit := range encoded { var raw [2]byte - binary.LittleEndian.PutUint16(raw[:], r) + binary.LittleEndian.PutUint16(raw[:], unit) result = append(result, raw[:]...) } return result } -func testEncodeUTF16Raw(s string) []byte { - encoded := utf16.Encode([]rune(s)) +func testEncodeUTF16Raw(text string) []byte { + encoded := utf16.Encode([]rune(text)) result := make([]byte, 0, len(encoded)*2) - for _, r := range encoded { + for _, unit := range encoded { var raw [2]byte - binary.LittleEndian.PutUint16(raw[:], r) + binary.LittleEndian.PutUint16(raw[:], unit) result = append(result, raw[:]...) } return result diff --git a/internal/browser/chromium/extractors.go b/internal/browser/chromium/extractors.go index eb3d680..4a146a4 100644 --- a/internal/browser/chromium/extractors.go +++ b/internal/browser/chromium/extractors.go @@ -12,28 +12,28 @@ import ( ) var ( - localState = browser.Source{Paths: []string{"Local State"}, Shared: true, Optional: true} - loginData = browser.Source{Paths: []string{"Login Data"}, Optional: true} - loginDataForAccount = browser.Source{Paths: []string{"Login Data For Account"}, Optional: true} + localState = browser.FileSpec{Paths: []string{"Local State"}, Shared: true, Optional: true} + loginData = browser.FileSpec{Paths: []string{"Login Data"}, Optional: true} + loginDataForAccount = browser.FileSpec{Paths: []string{"Login Data For Account"}, Optional: true} ) var defaultExtractors = browser.Extractors{ - category.Password: {Sources: []browser.Source{loginData, loginDataForAccount, localState}, Extract: extractPasswordStores}, - category.Cookie: encrypted(file("Network/Cookies", "Cookies"), extractCookies), - category.Bookmark: plain(file("Bookmarks"), extractBookmarks), - category.History: plain(file("History"), extractHistories), - category.Download: plain(file("History"), extractDownloads), - category.CreditCard: encrypted(file("Web Data"), extractCreditCards), - category.Extension: plain(file("Secure Preferences"), extractExtensions), - category.LocalStorage: plain(directory("Local Storage/leveldb"), extractLocalStorage), - category.SessionStorage: plain(directory("Session Storage"), extractSessionStorage), + category.Password: {FileSpecs: []browser.FileSpec{loginData, loginDataForAccount, localState}, Extract: extractPasswordStores}, + category.Cookie: newDecryptingExtractor(newFileSpec("Network/Cookies", "Cookies"), extractCookies), + category.Bookmark: newPlainExtractor(newFileSpec("Bookmarks"), extractBookmarks), + category.History: newPlainExtractor(newFileSpec("History"), extractHistories), + category.Download: newPlainExtractor(newFileSpec("History"), extractDownloads), + category.CreditCard: newDecryptingExtractor(newFileSpec("Web Data"), extractCreditCards), + category.Extension: newPlainExtractor(newFileSpec("Secure Preferences"), extractExtensions), + category.LocalStorage: newPlainExtractor(newDirectorySpec("Local Storage/leveldb"), extractLocalStorage), + category.SessionStorage: newPlainExtractor(newDirectorySpec("Session Storage"), extractSessionStorage), } -// overrides is keyed by Def.ID, never DirID, which differs for a second user data dir of one browser. +// overrides is keyed by Browser.Name, never UserDataDirID, which differs for a second user data dir of one browser. var overrides = map[string]browser.Extractors{ "yandex": { - category.Password: encrypted(file("Ya Passman Data"), extractYandexPasswords), - category.CreditCard: encrypted(file("Ya Credit Cards"), extractYandexCreditCards), + category.Password: newDecryptingExtractor(newFileSpec("Ya Passman Data"), extractYandexPasswords), + category.CreditCard: newDecryptingExtractor(newFileSpec("Ya Credit Cards"), extractYandexCreditCards), }, "opera": operaExtractors, "opera-gx": operaExtractors, @@ -41,42 +41,44 @@ var overrides = map[string]browser.Extractors{ } var operaExtractors = browser.Extractors{ - category.Extension: plain(file("Secure Preferences"), extractOperaExtensions), + category.Extension: newPlainExtractor(newFileSpec("Secure Preferences"), extractOperaExtensions), } func Extractors(dir browser.UserDataDir, _ browser.Profile) browser.Extractors { - ex := make(browser.Extractors, len(defaultExtractors)) - for c, e := range defaultExtractors { - ex[c] = e + extractors := make(browser.Extractors, len(defaultExtractors)) + for dataCategory, extractor := range defaultExtractors { + extractors[dataCategory] = extractor } - for c, e := range overrides[dir.Def.ID] { - ex[c] = e + for dataCategory, extractor := range overrides[dir.Browser.Name] { + extractors[dataCategory] = extractor } - return ex + return extractors } -func file(paths ...string) browser.Source { return browser.Source{Paths: paths} } -func directory(path string) browser.Source { return browser.Source{Paths: []string{path}, IsDir: true} } +func newFileSpec(paths ...string) browser.FileSpec { return browser.FileSpec{Paths: paths} } +func newDirectorySpec(path string) browser.FileSpec { + return browser.FileSpec{Paths: []string{path}, IsDir: true} +} -// encrypted lists Local State beside src, so the keys that decrypt src can be retrieved from the snapshot. -func encrypted(src browser.Source, parse func(masterkey.Set, string, browser.Collector) error) browser.Extractor { +// newDecryptingExtractor lists Local State beside fileSpec, so the keys that decrypt it are in the snapshot. +func newDecryptingExtractor(fileSpec browser.FileSpec, parse func(masterkey.Set, string, browser.Collector) error) browser.Extractor { return browser.Extractor{ - Sources: []browser.Source{src, localState}, - Extract: func(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { - path, err := ps.Path(src) + FileSpecs: []browser.FileSpec{fileSpec, localState}, + Extract: func(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + path, err := profileSnapshot.Path(fileSpec) if err != nil { return err } - return parse(ps.MasterKeys(ctx), path, out) + return parse(profileSnapshot.MasterKeys(ctx), path, out) }, } } -func plain(src browser.Source, parse func(string, browser.Collector) error) browser.Extractor { +func newPlainExtractor(fileSpec browser.FileSpec, parse func(string, browser.Collector) error) browser.Extractor { return browser.Extractor{ - Sources: []browser.Source{src}, - Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { - path, err := ps.Path(src) + FileSpecs: []browser.FileSpec{fileSpec}, + Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + path, err := profileSnapshot.Path(fileSpec) if err != nil { return err } @@ -85,30 +87,30 @@ func plain(src browser.Source, parse func(string, browser.Collector) error) brow } } -// A profile that only synced passwords has just the account store, and one store failing keeps the other's logins. -func extractPasswordStores(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { +// extractPasswordStores reads both stores: a synced-only profile has one, and one failing keeps the other's logins. +func extractPasswordStores(ctx context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { stores := []struct { - src browser.Source - store record.Store + fileSpec browser.FileSpec + store record.Store }{ {loginData, record.StoreLocal}, {loginDataForAccount, record.StoreAccount}, } var errs []error - for _, s := range stores { - path, err := ps.Path(s.src) + for _, loginStore := range stores { + path, err := profileSnapshot.Path(loginStore.fileSpec) if errors.Is(err, fs.ErrNotExist) { continue } if err == nil { - err = extractPasswords(ps.MasterKeys(ctx), path, s.store, out) + err = extractPasswords(profileSnapshot.MasterKeys(ctx), path, loginStore.store, out) } errs = append(errs, err) } return errors.Join(errs...) } -// emit hands rows to out by pointer, because out stamps each record in place. +// emit hands rows to out by pointer, because out sets each record's Browser and Profile in place. func emit[T any, P interface { *T record.Record diff --git a/internal/browser/chromium/testutil_test.go b/internal/browser/chromium/testutil_test.go index 73f6c9d..23608f2 100644 --- a/internal/browser/chromium/testutil_test.go +++ b/internal/browser/chromium/testutil_test.go @@ -8,9 +8,9 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/syndtr/goleveldb/leveldb" _ "modernc.org/sqlite" + "github.com/moond4rk/hackbrowserdata/internal/browser/browsertest" "github.com/moond4rk/hackbrowserdata/internal/record" ) @@ -192,15 +192,15 @@ func installFile(t *testing.T, profileDir, srcPath, dstName string) { func createTestDB(t *testing.T, name, schema string, inserts ...string) string { t.Helper() path := filepath.Join(t.TempDir(), name) - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) require.NoError(t, err) - defer db.Close() + defer database.Close() - _, err = db.Exec(schema) + _, err = database.Exec(schema) require.NoError(t, err) - for _, stmt := range inserts { - _, err = db.Exec(stmt) + for _, statement := range inserts { + _, err = database.Exec(statement) require.NoError(t, err) } return path @@ -216,12 +216,11 @@ func createTestJSON(t *testing.T, name, content string) string { func createTestLevelDB(t *testing.T, entries map[string]string) string { t.Helper() dir := filepath.Join(t.TempDir(), "leveldb") - db, err := leveldb.OpenFile(dir, nil) - require.NoError(t, err) - for k, v := range entries { - require.NoError(t, db.Put([]byte(k), []byte(v), nil)) + database := browsertest.OpenLevelDB(t, dir) + for key, value := range entries { + require.NoError(t, database.Put([]byte(key), []byte(value), nil)) } - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) return dir } @@ -230,16 +229,16 @@ type testCollector struct { fails []error } -func (c *testCollector) Add(r record.Record) { c.records = append(c.records, r) } -func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) } +func (c *testCollector) Add(row record.Record) { c.records = append(c.records, row) } +func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) } -func collected[T any](t *testing.T, c *testCollector) []T { +func collected[T any](t *testing.T, collector *testCollector) []T { t.Helper() - got := make([]T, 0, len(c.records)) - for _, r := range c.records { - v, ok := any(r).(*T) - require.Truef(t, ok, "collected a %T, want *%T", r, *new(T)) - got = append(got, *v) + got := make([]T, 0, len(collector.records)) + for _, row := range collector.records { + value, ok := any(row).(*T) + require.Truef(t, ok, "collected a %T, want *%T", row, *new(T)) + got = append(got, *value) } return got } diff --git a/internal/browser/chromium/vault.go b/internal/browser/chromium/vault.go index 35378a9..5bb1c18 100644 --- a/internal/browser/chromium/vault.go +++ b/internal/browser/chromium/vault.go @@ -21,18 +21,18 @@ var kinds = map[string]string{ "vought": kindOpera, } -func VaultKind(def browser.Def) string { - if kind, ok := kinds[def.ID]; ok { +func VaultKind(chromiumBrowser browser.Browser) string { + if kind, ok := kinds[chromiumBrowser.Name]; ok { return kind } return kindChromium } -// FormatID is the Def.ID whose extractors read a vault of kind; a plain Chromium vault keeps its own id. -func FormatID(kind, id string) (string, error) { +// FormatName is the browser Name whose extractors read a vault of kind; a plain Chromium vault keeps its own name. +func FormatName(kind, name string) (string, error) { switch kind { case kindChromium: - return id, nil + return name, nil case kindYandex: return "yandex", nil case kindOpera: diff --git a/internal/browser/chromium/yandex.go b/internal/browser/chromium/yandex.go index 87d4055..4e12b8b 100644 --- a/internal/browser/chromium/yandex.go +++ b/internal/browser/chromium/yandex.go @@ -12,17 +12,17 @@ import ( ) func yandexLoginAAD(originURL, usernameElem, usernameVal, passwordElem, signonRealm string, keyID []byte) []byte { - h := sha1.New() - h.Write([]byte(originURL)) - h.Write([]byte{0}) - h.Write([]byte(usernameElem)) - h.Write([]byte{0}) - h.Write([]byte(usernameVal)) - h.Write([]byte{0}) - h.Write([]byte(passwordElem)) - h.Write([]byte{0}) - h.Write([]byte(signonRealm)) - sum := h.Sum(nil) + hasher := sha1.New() + hasher.Write([]byte(originURL)) + hasher.Write([]byte{0}) + hasher.Write([]byte(usernameElem)) + hasher.Write([]byte{0}) + hasher.Write([]byte(usernameVal)) + hasher.Write([]byte{0}) + hasher.Write([]byte(passwordElem)) + hasher.Write([]byte{0}) + hasher.Write([]byte(signonRealm)) + sum := hasher.Sum(nil) if len(keyID) == 0 { return sum } @@ -52,18 +52,18 @@ func loadYandexDataKey(dbPath string, masterKey []byte) ([]byte, error) { if _, err := os.Stat(dbPath); err != nil { return nil, fmt.Errorf("yandex db file: %w", err) } - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) if err != nil { return nil, err } - defer db.Close() + defer database.Close() - if hasMasterPassword(db) { + if hasMasterPassword(database) { return nil, errYandexMasterPasswordSet } var blob []byte - if err := db.QueryRow("SELECT value FROM meta WHERE key = 'local_encryptor_data'").Scan(&blob); err != nil { + if err := database.QueryRow("SELECT value FROM meta WHERE key = 'local_encryptor_data'").Scan(&blob); err != nil { return nil, fmt.Errorf("read local_encryptor_data: %w", err) } @@ -75,9 +75,9 @@ func loadYandexDataKey(dbPath string, masterKey []byte) ([]byte, error) { } // hasMasterPassword: missing table (Ya Credit Cards) or empty sealed_key both mean false. -func hasMasterPassword(db *sql.DB) bool { +func hasMasterPassword(database *sql.DB) bool { var sealed sql.NullString - if err := db.QueryRow("SELECT sealed_key FROM active_keys").Scan(&sealed); err != nil { + if err := database.QueryRow("SELECT sealed_key FROM active_keys").Scan(&sealed); err != nil { return false } return sealed.Valid && strings.TrimSpace(sealed.String) != "" diff --git a/internal/browser/chromium/yandex_key.go b/internal/browser/chromium/yandex_key.go index 63d2b85..8e75b1a 100644 --- a/internal/browser/chromium/yandex_key.go +++ b/internal/browser/chromium/yandex_key.go @@ -25,11 +25,11 @@ var ( ) func decryptYandexIntermediateKey(masterKey, blob []byte) ([]byte, error) { - idx := bytes.Index(blob, localEncryptorPrefix) - if idx < 0 { + index := bytes.Index(blob, localEncryptorPrefix) + if index < 0 { return nil, errYandexMarkerNotFound } - payload := blob[idx+len(localEncryptorPrefix):] + payload := blob[index+len(localEncryptorPrefix):] if len(payload) < yandexIntKeyBlobLen { return nil, errYandexBlobShort } diff --git a/internal/browser/chromium/yandex_key_test.go b/internal/browser/chromium/yandex_key_test.go index 2f0b14c..31e0a90 100644 --- a/internal/browser/chromium/yandex_key_test.go +++ b/internal/browser/chromium/yandex_key_test.go @@ -21,7 +21,7 @@ func encryptAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { return aead.Seal(nil, nonce, plaintext, aad) } -// 96 (blob) - 12 (nonce) - 16 (tag) = 68 bytes of payload before sealing. +// testPlaintextPayloadLen is 96 (blob) - 12 (nonce) - 16 (tag) = 68 bytes of payload before sealing. const testPlaintextPayloadLen = yandexIntKeyBlobLen - gcmNonceSize - 16 func buildLocalEncryptorBlob(t *testing.T, masterKey, dataKey []byte) []byte { diff --git a/internal/browser/chromium/yandex_testutil_test.go b/internal/browser/chromium/yandex_testutil_test.go index 2481a75..15b18c6 100644 --- a/internal/browser/chromium/yandex_testutil_test.go +++ b/internal/browser/chromium/yandex_testutil_test.go @@ -45,13 +45,13 @@ const yandexRecordsSchema = `CREATE TABLE records ( private_data BLOB )` -// A fixed nonce keeps failures reproducible by hand; Yandex itself draws a random one per row. +// yandexTestNonce is fixed to keep failures reproducible by hand; Yandex itself draws a random one per row. var yandexTestNonce = bytes.Repeat([]byte{0x77}, 12) -// Distinct from yandexTestNonce, so mixing the two up fails to decrypt instead of passing. +// yandexMasterKeyBlobNonce differs from yandexTestNonce, so mixing the two up fails to decrypt instead of passing. var yandexMasterKeyBlobNonce = bytes.Repeat([]byte{0xAB}, 12) -// Protobuf header: field 1 varint 1, field 2 length 32. +// yandexSignatureForFixtures is a protobuf header: field 1 varint 1, field 2 length 32. var yandexSignatureForFixtures = []byte{0x08, 0x01, 0x12, 0x20} func yandexSealAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { @@ -63,7 +63,7 @@ func yandexSealAESGCM(t *testing.T, key, nonce, plaintext, aad []byte) []byte { return aead.Seal(nil, nonce, plaintext, aad) } -// meta.local_encryptor_data: preamble, "v10", nonce, then signature and key sealed and padded to 68 bytes. +// buildYandexLocalEncryptorBlob lays out meta.local_encryptor_data: preamble, "v10", nonce, sealed signature and key. func buildYandexLocalEncryptorBlob(t *testing.T, masterKey, dataKey []byte) []byte { t.Helper() plaintext := append([]byte{}, yandexSignatureForFixtures...) @@ -84,41 +84,41 @@ type yandexPassword struct { DateCreated int64 } -// hasMasterPassword adds a non-empty sealed_key row, as a master-password profile has. +// setupYandexPasswordDB adds a non-empty sealed_key row when hasMasterPassword, as a master-password profile has. func setupYandexPasswordDB(t *testing.T, masterKey, dataKey []byte, hasMasterPassword bool, rows ...yandexPassword) string { t.Helper() path := filepath.Join(t.TempDir(), "Ya Passman Data") - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) require.NoError(t, err) - defer db.Close() + defer database.Close() for _, schema := range []string{yandexLoginsSchema, yandexMetaSchema, yandexActiveKeysSchema} { - _, err = db.Exec(schema) + _, err = database.Exec(schema) require.NoError(t, err) } blob := buildYandexLocalEncryptorBlob(t, masterKey, dataKey) - _, err = db.Exec(`INSERT INTO meta (key, value) VALUES ('local_encryptor_data', ?)`, blob) + _, err = database.Exec(`INSERT INTO meta (key, value) VALUES ('local_encryptor_data', ?)`, blob) require.NoError(t, err) if hasMasterPassword { - _, err = db.Exec(`INSERT INTO active_keys (key_id, sealed_key) VALUES ('kid', 'sealed-opaque')`) + _, err = database.Exec(`INSERT INTO active_keys (key_id, sealed_key) VALUES ('kid', 'sealed-opaque')`) require.NoError(t, err) } - for _, r := range rows { - aad := yandexLoginAAD(r.OriginURL, r.UsernameElem, r.UsernameVal, r.PasswordElem, r.SignonRealm, nil) - ciphertext := yandexSealAESGCM(t, dataKey, yandexTestNonce, []byte(r.Password), aad) + for _, row := range rows { + aad := yandexLoginAAD(row.OriginURL, row.UsernameElem, row.UsernameVal, row.PasswordElem, row.SignonRealm, nil) + ciphertext := yandexSealAESGCM(t, dataKey, yandexTestNonce, []byte(row.Password), aad) passwordBlob := append([]byte{}, yandexTestNonce...) passwordBlob = append(passwordBlob, ciphertext...) - stmt := fmt.Sprintf( + statement := fmt.Sprintf( `INSERT INTO logins (origin_url, action_url, username_element, username_value, password_element, password_value, signon_realm, date_created) VALUES ('%s', '', '%s', '%s', '%s', x'%s', '%s', %d)`, - r.OriginURL, r.UsernameElem, r.UsernameVal, r.PasswordElem, - hex.EncodeToString(passwordBlob), r.SignonRealm, r.DateCreated, + row.OriginURL, row.UsernameElem, row.UsernameVal, row.PasswordElem, + hex.EncodeToString(passwordBlob), row.SignonRealm, row.DateCreated, ) - _, err = db.Exec(stmt) + _, err = database.Exec(statement) require.NoError(t, err) } return path @@ -133,45 +133,45 @@ type yandexCreditCard struct { func setupYandexCreditCardDB(t *testing.T, masterKey, dataKey []byte, rows ...yandexCreditCard) string { t.Helper() path := filepath.Join(t.TempDir(), "Ya Credit Cards") - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) require.NoError(t, err) - defer db.Close() + defer database.Close() for _, schema := range []string{yandexRecordsSchema, yandexMetaSchema} { - _, err = db.Exec(schema) + _, err = database.Exec(schema) require.NoError(t, err) } blob := buildYandexLocalEncryptorBlob(t, masterKey, dataKey) - _, err = db.Exec(`INSERT INTO meta (key, value) VALUES ('local_encryptor_data', ?)`, blob) + _, err = database.Exec(`INSERT INTO meta (key, value) VALUES ('local_encryptor_data', ?)`, blob) require.NoError(t, err) - for _, r := range rows { + for _, row := range rows { public := yandexPublicData{ - CardHolder: r.CardHolder, - CardTitle: r.CardTitle, - ExpireDateYear: r.ExpYear, - ExpireDateMonth: r.ExpMonth, + CardHolder: row.CardHolder, + CardTitle: row.CardTitle, + ExpireDateYear: row.ExpYear, + ExpireDateMonth: row.ExpMonth, } publicJSON, err := json.Marshal(public) require.NoError(t, err) private := yandexPrivateData{ - FullCardNumber: r.FullCardNumber, - PinCode: r.PinCode, - SecretComment: r.SecretComment, + FullCardNumber: row.FullCardNumber, + PinCode: row.PinCode, + SecretComment: row.SecretComment, } privateJSON, err := json.Marshal(private) require.NoError(t, err) - aad := yandexCardAAD(r.GUID, nil) + aad := yandexCardAAD(row.GUID, nil) ciphertext := yandexSealAESGCM(t, dataKey, yandexTestNonce, privateJSON, aad) privateBlob := append([]byte{}, yandexTestNonce...) privateBlob = append(privateBlob, ciphertext...) - _, err = db.Exec( + _, err = database.Exec( `INSERT INTO records (guid, public_data, private_data) VALUES (?, ?, ?)`, - r.GUID, string(publicJSON), privateBlob, + row.GUID, string(publicJSON), privateBlob, ) require.NoError(t, err) } diff --git a/internal/browser/extractor.go b/internal/browser/extractor.go index a669e29..109edf2 100644 --- a/internal/browser/extractor.go +++ b/internal/browser/extractor.go @@ -14,60 +14,60 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -// Source is one file or directory an extractor reads; Paths are its candidates in priority order. -type Source struct { +// FileSpec is one file or directory an extractor reads; Paths are its candidates in priority order. +type FileSpec struct { Paths []string // slash-separated, relative to the profile dir, or to the user data dir when Shared 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 } -// Candidates are the Paths for profile p, relative to the user data dir, in priority order. -func (s Source) Candidates(p Profile) []string { - rels := make([]string, len(s.Paths)) - for i, rel := range s.Paths { +// CandidatePaths are the Paths for a profile, relative to the user data dir, in priority order. +func (s FileSpec) CandidatePaths(profile Profile) []string { + paths := make([]string, len(s.Paths)) + for i, relativePath := range s.Paths { if !s.Shared { - rel = path.Join(p.Dir, rel) + relativePath = path.Join(profile.Dir, relativePath) } - rels[i] = rel + paths[i] = relativePath } - return rels + return paths } type Extractor struct { - Sources []Source - Extract func(ctx context.Context, ps ProfileSnapshot, out Collector) error + FileSpecs []FileSpec + Extract func(ctx context.Context, profileSnapshot ProfileSnapshot, out Collector) error } type Extractors map[category.Category]Extractor -// Collector stamps every record's Browser and Profile; Fail reports a bad record and the extraction goes on. +// Collector sets every record's Browser and Profile; Fail reports a bad record and the extraction goes on. type Collector interface { - Add(r record.Record) + Add(row record.Record) Fail(err error) } type ProfileSnapshot struct { Profile Profile - snap snapshot.Snapshot + snapshot snapshot.Snapshot masterKeys func(ctx context.Context) masterkey.Set } -// masterKeys is the user data dir's call-once retrieval, nil for the bases that keep no Chromium keys. -func NewProfileSnapshot(snap snapshot.Snapshot, p Profile, masterKeys func(context.Context) masterkey.Set) ProfileSnapshot { - return ProfileSnapshot{Profile: p, snap: snap, masterKeys: masterKeys} +// NewProfileSnapshot takes masterKeys, the dir's call-once retrieval, nil for bases that keep no Chromium keys. +func NewProfileSnapshot(dirSnapshot snapshot.Snapshot, profile Profile, masterKeys func(context.Context) masterkey.Set) ProfileSnapshot { + return ProfileSnapshot{Profile: profile, snapshot: dirSnapshot, masterKeys: masterKeys} } // Path skips a candidate that was never captured but returns the error of one whose copy failed. -func (ps ProfileSnapshot) Path(src Source) (string, error) { - for _, rel := range src.Candidates(ps.Profile) { - p, err := ps.snap.Path(rel) +func (ps ProfileSnapshot) Path(fileSpec FileSpec) (string, error) { + for _, relativePath := range fileSpec.CandidatePaths(ps.Profile) { + capturedPath, err := ps.snapshot.Path(relativePath) if errors.Is(err, fs.ErrNotExist) { continue } - return p, err + return capturedPath, err } - return "", fmt.Errorf("%s: %w", strings.Join(src.Paths, " or "), fs.ErrNotExist) + return "", fmt.Errorf("%s: %w", strings.Join(fileSpec.Paths, " or "), fs.ErrNotExist) } // MasterKeys may block on its first call; a key version that could not be retrieved is absent from the Set. diff --git a/internal/browser/extractor_test.go b/internal/browser/extractor_test.go index 8ba8c97..7d26cd2 100644 --- a/internal/browser/extractor_test.go +++ b/internal/browser/extractor_test.go @@ -14,11 +14,11 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -func writeSnapshotFile(t *testing.T, root, rel string) string { +func writeSnapshotFile(t *testing.T, root, relativePath string) string { t.Helper() - path := filepath.Join(root, filepath.FromSlash(rel)) + path := filepath.Join(root, filepath.FromSlash(relativePath)) require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700)) - require.NoError(t, os.WriteFile(path, []byte(rel), 0o600)) + require.NoError(t, os.WriteFile(path, []byte(relativePath), 0o600)) return path } @@ -26,69 +26,69 @@ func TestProfileSnapshotPath(t *testing.T) { root := t.TempDir() legacyCookies := writeSnapshotFile(t, root, "chrome/Default/Cookies") localState := writeSnapshotFile(t, root, "chrome/Local State") - snap := snapshot.Open(root).Snapshot("chrome") - ps := NewProfileSnapshot(snap, Profile{Name: "Default", Dir: "Default"}, nil) + dirSnapshot := snapshot.Open(root).Snapshot("chrome") + profileSnapshot := NewProfileSnapshot(dirSnapshot, Profile{Name: "Default", Dir: "Default"}, nil) - got, err := ps.Path(Source{Paths: []string{"Network/Cookies", "Cookies"}}) + got, err := profileSnapshot.Path(FileSpec{Paths: []string{"Network/Cookies", "Cookies"}}) require.NoError(t, err) assert.Equal(t, legacyCookies, got, "a candidate that was never captured is skipped") - got, err = ps.Path(Source{Paths: []string{"Local State"}, Shared: true}) + got, err = profileSnapshot.Path(FileSpec{Paths: []string{"Local State"}, Shared: 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 shared file spec resolves under the user data dir, not the profile") - _, err = ps.Path(Source{Paths: []string{"History"}}) + _, err = profileSnapshot.Path(FileSpec{Paths: []string{"History"}}) require.ErrorIs(t, err, fs.ErrNotExist) } func TestProfileSnapshotPath_FlatLayoutProfile(t *testing.T) { root := t.TempDir() history := writeSnapshotFile(t, root, "opera/History") - ps := NewProfileSnapshot(snapshot.Open(root).Snapshot("opera"), Profile{Name: "Opera Stable"}, nil) + profileSnapshot := NewProfileSnapshot(snapshot.Open(root).Snapshot("opera"), Profile{Name: "Opera Stable"}, nil) - got, err := ps.Path(Source{Paths: []string{"History"}}) + got, err := profileSnapshot.Path(FileSpec{Paths: []string{"History"}}) require.NoError(t, err) assert.Equal(t, history, got) } -// A copy that failed is that extraction's error, not a reason to read a lower-priority candidate instead. +// 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") - d, err := snapshot.Temp() + snapshotDir, err := snapshot.Temp() require.NoError(t, err) - defer func() { require.NoError(t, d.Close()) }() - require.NoError(t, d.Capture(context.Background(), []snapshot.File{ - {DirID: "chrome", From: from, Rel: "Default/Network/Cookies"}, - {DirID: "chrome", From: from, Rel: "Default/Cookies"}, + defer func() { require.NoError(t, snapshotDir.Close()) }() + require.NoError(t, snapshotDir.Capture(context.Background(), []snapshot.File{ + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Network/Cookies"}, + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Cookies"}, })) - ps := NewProfileSnapshot(d.Snapshot("chrome"), Profile{Name: "Default", Dir: "Default"}, nil) - _, err = ps.Path(Source{Paths: []string{"Network/Cookies", "Cookies"}}) + profileSnapshot := NewProfileSnapshot(snapshotDir.Snapshot("chrome"), Profile{Name: "Default", Dir: "Default"}, nil) + _, err = profileSnapshot.Path(FileSpec{Paths: []string{"Network/Cookies", "Cookies"}}) require.Error(t, err) assert.NotErrorIs(t, err, fs.ErrNotExist) } func TestProfileSnapshotMasterKeys(t *testing.T) { - snap := snapshot.Open(t.TempDir()).Snapshot("chrome") - assert.Nil(t, NewProfileSnapshot(snap, Profile{}, nil).MasterKeys(context.Background())) + dirSnapshot := snapshot.Open(t.TempDir()).Snapshot("chrome") + assert.Nil(t, NewProfileSnapshot(dirSnapshot, Profile{}, nil).MasterKeys(context.Background())) calls := 0 want := masterkey.Set{masterkey.V10: []byte("k")} - ps := NewProfileSnapshot(snap, Profile{}, func(context.Context) masterkey.Set { + profileSnapshot := NewProfileSnapshot(dirSnapshot, Profile{}, func(context.Context) masterkey.Set { calls++ return want }) - assert.Equal(t, want, ps.MasterKeys(context.Background())) + assert.Equal(t, want, profileSnapshot.MasterKeys(context.Background())) assert.Equal(t, 1, calls) } -func TestSource_Candidates(t *testing.T) { - p := Profile{Name: "Default", Dir: "Default"} - assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{Paths: []string{"Network/Cookies", "Cookies"}}.Candidates(p)) - assert.Equal(t, []string{"Local State"}, Source{Paths: []string{"Local State"}, Shared: true}.Candidates(p)) - assert.Equal(t, []string{"History"}, Source{Paths: []string{"History"}}.Candidates(Profile{Name: "default"}), +func TestFileSpec_CandidatePaths(t *testing.T) { + profile := Profile{Name: "Default", Dir: "Default"} + assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, FileSpec{Paths: []string{"Network/Cookies", "Cookies"}}.CandidatePaths(profile)) + assert.Equal(t, []string{"Local State"}, FileSpec{Paths: []string{"Local State"}, Shared: true}.CandidatePaths(profile)) + assert.Equal(t, []string{"History"}, FileSpec{Paths: []string{"History"}}.CandidatePaths(Profile{Name: "default"}), "a user data dir that is itself the profile") } diff --git a/internal/browser/firefox/extract_bookmark.go b/internal/browser/firefox/extract_bookmark.go index cc9535b..2c8700c 100644 --- a/internal/browser/firefox/extract_bookmark.go +++ b/internal/browser/firefox/extract_bookmark.go @@ -9,7 +9,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/timeconv" ) -// Folders and separators have no place, so the place join keeps only bookmarks; the parent join names their folder. +// firefoxBookmarkQuery keeps only bookmarks, as folders and separators have no place; the parent join names the folder. const firefoxBookmarkQuery = `SELECT b.id, p.url, b.type, b.dateAdded, COALESCE(b.title, ''), COALESCE(f.title, '') FROM moz_bookmarks b INNER JOIN moz_places p ON b.fk = p.id @@ -20,14 +20,14 @@ func extractBookmarks(path string, out browser.Collector) error { func(rows *sql.Rows) (record.Bookmark, error) { var id, dateAdded int64 var url, title, folder string - var bt int64 - if err := rows.Scan(&id, &url, &bt, &dateAdded, &title, &folder); err != nil { + var typeCode int64 + if err := rows.Scan(&id, &url, &typeCode, &dateAdded, &title, &folder); err != nil { return record.Bookmark{}, err } return record.Bookmark{ ID: id, Name: title, - Type: bookmarkType(bt), + Type: bookmarkType(typeCode), URL: url, Folder: folder, CreatedAt: timeconv.UnixMicro(dateAdded), @@ -40,8 +40,8 @@ func extractBookmarks(path string, out browser.Collector) error { return nil } -func bookmarkType(bt int64) string { - switch bt { +func bookmarkType(typeCode int64) string { + switch typeCode { case 1: return "url" default: diff --git a/internal/browser/firefox/extract_bookmark_test.go b/internal/browser/firefox/extract_bookmark_test.go index b6433c9..12bc454 100644 --- a/internal/browser/firefox/extract_bookmark_test.go +++ b/internal/browser/firefox/extract_bookmark_test.go @@ -39,7 +39,7 @@ func TestExtractBookmarks(t *testing.T) { assert.False(t, got[1].CreatedAt.IsZero()) } -// Before, every bookmark came out with folder "url", an empty type, and id 0. +// TestExtractBookmarks_FolderTypeAndIDFromTheTree guards a fixed bug: bookmarks had folder "url", no type, and id 0. func TestExtractBookmarks_FolderTypeAndIDFromTheTree(t *testing.T) { path := createTestDB(t, "places.sqlite", []string{mozPlacesSchema, mozBookmarksSchema}, insertMozPlace(1, "https://go.dev", "Go", 0, 0), @@ -56,8 +56,8 @@ func TestExtractBookmarks_FolderTypeAndIDFromTheTree(t *testing.T) { var out testCollector require.NoError(t, extractBookmarks(path, &out)) byID := map[int64]record.Bookmark{} - for _, b := range collected[record.Bookmark](t, &out) { - byID[b.ID] = b + for _, bookmark := range collected[record.Bookmark](t, &out) { + byID[bookmark.ID] = bookmark } require.Len(t, byID, 2, "folders and separators are not bookmarks") want := record.Bookmark{ID: 7, Name: "Go", Type: "url", URL: "https://go.dev", Folder: "toolbar", CreatedAt: byID[7].CreatedAt} diff --git a/internal/browser/firefox/extract_extension.go b/internal/browser/firefox/extract_extension.go index 6b19602..2c6ef9c 100644 --- a/internal/browser/firefox/extract_extension.go +++ b/internal/browser/firefox/extract_extension.go @@ -16,20 +16,20 @@ func extractExtensions(path string, out browser.Collector) error { } var extensions []record.Extension - for _, v := range gjson.GetBytes(data, "addons").Array() { + for _, value := range gjson.GetBytes(data, "addons").Array() { // Only include user-installed extensions // https://searchfox.org/mozilla-central/source/toolkit/mozapps/extensions/internal/XPIDatabase.jsm#157 - if v.Get("location").String() != "app-profile" { + if value.Get("location").String() != "app-profile" { continue } extensions = append(extensions, record.Extension{ - Name: v.Get("defaultLocale.name").String(), - ID: v.Get("id").String(), - Description: v.Get("defaultLocale.description").String(), - Version: v.Get("version").String(), - HomepageURL: v.Get("defaultLocale.homepageURL").String(), - Enabled: v.Get("active").Bool(), + Name: value.Get("defaultLocale.name").String(), + ID: value.Get("id").String(), + Description: value.Get("defaultLocale.description").String(), + Version: value.Get("version").String(), + HomepageURL: value.Get("defaultLocale.homepageURL").String(), + Enabled: value.Get("active").Bool(), }) } emit(out, extensions) diff --git a/internal/browser/firefox/extract_extension_test.go b/internal/browser/firefox/extract_extension_test.go index f34216f..f9e78fe 100644 --- a/internal/browser/firefox/extract_extension_test.go +++ b/internal/browser/firefox/extract_extension_test.go @@ -53,10 +53,10 @@ func TestExtractExtensions(t *testing.T) { require.Len(t, got, 2) // system addon filtered out ids := map[string]bool{} - for _, ext := range got { - ids[ext.ID] = true - assert.NotEmpty(t, ext.Name) - assert.NotEmpty(t, ext.Version) + for _, extension := range got { + ids[extension.ID] = true + assert.NotEmpty(t, extension.Name) + assert.NotEmpty(t, extension.Version) } assert.True(t, ids["ublock@gorhill.org"]) assert.True(t, ids["bitwarden@bitwarden.com"]) diff --git a/internal/browser/firefox/extract_password.go b/internal/browser/firefox/extract_password.go index 8ffb277..d0f6f80 100644 --- a/internal/browser/firefox/extract_password.go +++ b/internal/browser/firefox/extract_password.go @@ -36,18 +36,18 @@ func extractPasswords(masterKey func() []byte, path string, out browser.Collecto } var logins []record.Login - for _, v := range gjson.GetBytes(data, "logins").Array() { - url := v.Get("formSubmitURL").String() + for _, value := range gjson.GetBytes(data, "logins").Array() { + url := value.Get("formSubmitURL").String() if url == "" { - url = v.Get("hostname").String() + url = value.Get("hostname").String() } key := masterKey() - user, err := decryptPBE(v.Get("encryptedUsername").String(), key) + user, err := decryptPBE(value.Get("encryptedUsername").String(), key) if err != nil { out.Fail(fmt.Errorf("decrypt username for %s: %w", url, err)) } - pwd, err := decryptPBE(v.Get("encryptedPassword").String(), key) + password, err := decryptPBE(value.Get("encryptedPassword").String(), key) if err != nil { out.Fail(fmt.Errorf("decrypt password for %s: %w", url, err)) } @@ -55,8 +55,8 @@ func extractPasswords(masterKey func() []byte, path string, out browser.Collecto logins = append(logins, record.Login{ URL: url, Username: string(user), - Password: string(pwd), - CreatedAt: timeconv.UnixMilli(v.Get("timeCreated").Int()), + Password: string(password), + CreatedAt: timeconv.UnixMilli(value.Get("timeCreated").Int()), Store: record.StoreLocal, }) } diff --git a/internal/browser/firefox/extract_password_test.go b/internal/browser/firefox/extract_password_test.go index d4e1a86..2ed1ae0 100644 --- a/internal/browser/firefox/extract_password_test.go +++ b/internal/browser/firefox/extract_password_test.go @@ -13,7 +13,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// From crypto's loginPBETestCases: decrypts to "Hello, World!" with globalSalt = "moond4rk" * 3. +// loginPBEHex is from crypto's loginPBETestCases: it decrypts to "Hello, World!" with globalSalt = "moond4rk" * 3. const loginPBEHex = "303b0410f8000000000000000000000000000001301506092a864886f70d010503040830313233343536370410fe968b6565149114ea688defd6683e45" var testGlobalSalt = bytes.Repeat([]byte("moond4rk"), 3) // 24 bytes diff --git a/internal/browser/firefox/extract_storage.go b/internal/browser/firefox/extract_storage.go index 395b800..33ef66b 100644 --- a/internal/browser/firefox/extract_storage.go +++ b/internal/browser/firefox/extract_storage.go @@ -32,15 +32,15 @@ func extractLocalStorage(path string, out browser.Collector) error { return nil } -func reverseString(s string) string { - b := []byte(s) - for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { - b[i], b[j] = b[j], b[i] +func reverseString(text string) string { + reversed := []byte(text) + for i, j := 0, len(reversed)-1; i < j; i, j = i+1, j-1 { + reversed[i], reversed[j] = reversed[j], reversed[i] } - return string(b) + return string(reversed) } -// Firefox reverses the host: "moc.buhtig.:https:443" is https://github.com:443. +// parseOriginKey undoes Firefox's reversed host: "moc.buhtig.:https:443" is https://github.com:443. func parseOriginKey(originKey string) string { parts := strings.SplitN(originKey, ":", 3) if len(parts) < 2 { diff --git a/internal/browser/firefox/extract_storage_test.go b/internal/browser/firefox/extract_storage_test.go index 9b63f4e..5f0b34d 100644 --- a/internal/browser/firefox/extract_storage_test.go +++ b/internal/browser/firefox/extract_storage_test.go @@ -64,10 +64,10 @@ func TestParseOriginKey(t *testing.T) { }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := parseOriginKey(tt.originKey) - assert.Equal(t, tt.want, got) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + got := parseOriginKey(testCase.originKey) + assert.Equal(t, testCase.want, got) }) } } diff --git a/internal/browser/firefox/firefox.go b/internal/browser/firefox/firefox.go index bd6e207..bb6a777 100644 --- a/internal/browser/firefox/firefox.go +++ b/internal/browser/firefox/firefox.go @@ -15,31 +15,31 @@ import ( ) var ( - loginsJSON = browser.Source{Paths: []string{"logins.json"}} - keyStore = browser.Source{Paths: []string{"key4.db"}, Optional: true} - placesDB = browser.Source{Paths: []string{"places.sqlite"}} + loginsJSON = browser.FileSpec{Paths: []string{"logins.json"}} + keyStore = browser.FileSpec{Paths: []string{"key4.db"}, Optional: true} + placesDB = browser.FileSpec{Paths: []string{"places.sqlite"}} ) -// Firefox keeps no credit cards or session storage that HBD reads, so those categories have no extractor. -var extractors = browser.Extractors{ - category.Password: {Sources: []browser.Source{loginsJSON, keyStore}, Extract: extractLogins}, - category.Cookie: plain(file("cookies.sqlite"), extractCookies), - category.Bookmark: plain(placesDB, extractBookmarks), - category.History: plain(placesDB, extractHistories), - category.Download: plain(placesDB, extractDownloads), - category.Extension: plain(file("extensions.json"), extractExtensions), - category.LocalStorage: plain(file("webappsstore.sqlite"), extractLocalStorage), +// defaultExtractors has no credit card or session storage extractor, because Firefox keeps none that HBD reads. +var defaultExtractors = browser.Extractors{ + category.Password: {FileSpecs: []browser.FileSpec{loginsJSON, keyStore}, Extract: extractLogins}, + category.Cookie: newPlainExtractor(newFileSpec("cookies.sqlite"), extractCookies), + category.Bookmark: newPlainExtractor(placesDB, extractBookmarks), + category.History: newPlainExtractor(placesDB, extractHistories), + category.Download: newPlainExtractor(placesDB, extractDownloads), + category.Extension: newPlainExtractor(newFileSpec("extensions.json"), extractExtensions), + category.LocalStorage: newPlainExtractor(newFileSpec("webappsstore.sqlite"), extractLocalStorage), } -// -p names one profile: its parent is the Profiles directory, and only that profile is selected. -func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { - if opts.ProfilePath != "" { - return profileAt(def, opts.ProfilePath), nil +// 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 } var errs []error var dirs []browser.UserDataDir - for i, path := range userDataDirPaths(def, opts) { - dir := browser.UserDataDir{ID: dirID(def, i), Def: def, Path: path} + for i, path := range userDataDirPaths(firefoxBrowser, options) { + dir := browser.UserDataDir{ID: firefoxBrowser.UserDataDirID(i), Browser: firefoxBrowser, Path: path} profiles, err := discoverProfiles(dir) if errors.Is(err, fs.ErrNotExist) { continue @@ -54,58 +54,51 @@ func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserData return dirs, errors.Join(errs...) } -func profileAt(def browser.Def, path string) []browser.UserDataDir { +func profileAt(firefoxBrowser browser.Browser, path string) []browser.UserDataDir { clean := filepath.Clean(path) if !hasDataFile(clean) { return nil } name := filepath.Base(clean) return []browser.UserDataDir{{ - ID: dirID(def, 0), - Def: def, + ID: firefoxBrowser.UserDataDirID(0), + Browser: firefoxBrowser, Path: filepath.Dir(clean), Profiles: []browser.Profile{{Name: name, Dir: name}}, }} } -func userDataDirPaths(def browser.Def, opts browser.DiscoverOptions) []string { - paths := make([]string, 0, len(def.Platform().UserDataDirs)) - for _, rel := range def.Platform().UserDataDirs { - paths = append(paths, filepath.Join(opts.Home, filepath.FromSlash(rel))) +func userDataDirPaths(firefoxBrowser browser.Browser, options browser.DiscoverOptions) []string { + paths := make([]string, 0, len(firefoxBrowser.Platform().UserDataDirs)) + for _, relativePath := range firefoxBrowser.Platform().UserDataDirs { + paths = append(paths, filepath.Join(options.Home, filepath.FromSlash(relativePath))) } return paths } -func dirID(def browser.Def, i int) browser.DirID { - if i == 0 { - return browser.DirID(def.ID) - } - return browser.DirID(fmt.Sprintf("%s-%d", def.ID, i+1)) -} - -// Profile directories have random names, so any subdirectory holding a source counts; key4.db alone does not. +// discoverProfiles counts any subdirectory with a file an extractor reads, as names are random; key4.db does not. func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { entries, err := os.ReadDir(dir.Path) if err != nil { return nil, err } var profiles []browser.Profile - for _, e := range entries { - if e.IsDir() && hasDataFile(filepath.Join(dir.Path, e.Name())) { - profiles = append(profiles, browser.Profile{Name: e.Name(), Dir: e.Name()}) + for _, entry := range entries { + if entry.IsDir() && hasDataFile(filepath.Join(dir.Path, entry.Name())) { + profiles = append(profiles, browser.Profile{Name: entry.Name(), Dir: entry.Name()}) } } return profiles, nil } func hasDataFile(dir string) bool { - for _, e := range extractors { - for _, src := range e.Sources { - if src.Optional { + for _, extractor := range defaultExtractors { + for _, fileSpec := range extractor.FileSpecs { + if fileSpec.Optional { continue } - for _, rel := range src.Paths { - if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(rel))); err == nil { + for _, relativePath := range fileSpec.Paths { + if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(relativePath))); err == nil { return true } } @@ -115,20 +108,20 @@ func hasDataFile(dir string) bool { } func Extractors(_ browser.UserDataDir, _ browser.Profile) browser.Extractors { - ex := make(browser.Extractors, len(extractors)) - for c, e := range extractors { - ex[c] = e + extractors := make(browser.Extractors, len(defaultExtractors)) + for dataCategory, extractor := range defaultExtractors { + extractors[dataCategory] = extractor } - return ex + return extractors } -func file(path string) browser.Source { return browser.Source{Paths: []string{path}} } +func newFileSpec(path string) browser.FileSpec { return browser.FileSpec{Paths: []string{path}} } -func plain(src browser.Source, parse func(string, browser.Collector) error) browser.Extractor { +func newPlainExtractor(fileSpec browser.FileSpec, parse func(string, browser.Collector) error) browser.Extractor { return browser.Extractor{ - Sources: []browser.Source{src}, - Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { - path, err := ps.Path(src) + FileSpecs: []browser.FileSpec{fileSpec}, + Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + path, err := profileSnapshot.Path(fileSpec) if err != nil { return err } @@ -137,9 +130,9 @@ func plain(src browser.Source, parse func(string, browser.Collector) error) brow } } -// The key is derived only once a login needs it; without one the logins export with empty secrets. -func extractLogins(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { - path, err := ps.Path(loginsJSON) +// extractLogins derives the key only once a login needs it; without one the logins export with empty secrets. +func extractLogins(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + path, err := profileSnapshot.Path(loginsJSON) if err != nil { return err } @@ -150,26 +143,26 @@ func extractLogins(_ context.Context, ps browser.ProfileSnapshot, out browser.Co masterKey := func() []byte { if !derived { derived = true - k, keyErr := profileKey(ps, path) + retrieved, keyErr := profileKey(profileSnapshot, path) if keyErr != nil { out.Fail(fmt.Errorf("master key: %w", keyErr)) } - key = k + key = retrieved } return key } return extractPasswords(masterKey, path, out) } -func profileKey(ps browser.ProfileSnapshot, loginsPath string) ([]byte, error) { - key4Path, err := ps.Path(keyStore) +func profileKey(profileSnapshot browser.ProfileSnapshot, loginsPath string) ([]byte, error) { + key4Path, err := profileSnapshot.Path(keyStore) if err != nil { return nil, err } return retrieveMasterKey(key4Path, loginsPath) } -// emit hands rows to out by pointer, because out stamps each record in place. +// emit hands rows to out by pointer, because out sets each record's Browser and Profile in place. func emit[T any, P interface { *T record.Record diff --git a/internal/browser/firefox/firefox_test.go b/internal/browser/firefox/firefox_test.go index c0c9484..1f25584 100644 --- a/internal/browser/firefox/firefox_test.go +++ b/internal/browser/firefox/firefox_test.go @@ -18,9 +18,9 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/snapshot" ) -func testDef(userDataDirs ...string) browser.Def { - p := browser.Platform{UserDataDirs: userDataDirs} - return browser.Def{ID: "firefox", Name: "Firefox", Base: browser.Firefox, Darwin: p, Linux: p, Windows: p} +func testBrowser(userDataDirs ...string) browser.Browser { + platform := browser.Platform{UserDataDirs: userDataDirs} + return browser.Browser{Name: "firefox", DisplayName: "Firefox", Base: browser.Firefox, Darwin: platform, Linux: platform, Windows: platform} } func touch(t *testing.T, parts ...string) { @@ -33,10 +33,10 @@ func touch(t *testing.T, parts ...string) { func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot { t.Helper() root := t.TempDir() - for rel, src := range files { - dir := filepath.Join(root, "firefox", filepath.Dir(filepath.FromSlash(rel))) + for relativePath, fixturePath := range files { + dir := filepath.Join(root, "firefox", filepath.Dir(filepath.FromSlash(relativePath))) require.NoError(t, os.MkdirAll(dir, 0o700)) - installFile(t, dir, src, filepath.Base(rel)) + installFile(t, dir, fixturePath, filepath.Base(relativePath)) } return snapshot.Open(root).Snapshot("firefox") } @@ -49,10 +49,10 @@ func TestDiscover_ProfilesAreDirsWithDataFiles(t *testing.T) { touch(t, home, "Profiles", "Crash Reports", "InstallTime20240101000000") touch(t, home, "Profiles", "profiles.ini") - dirs, err := Discover(testDef("Profiles"), browser.DiscoverOptions{Home: home}) + dirs, err := Discover(testBrowser("Profiles"), browser.DiscoverOptions{Home: home}) require.NoError(t, err) require.Len(t, dirs, 1) - assert.Equal(t, browser.DirID("firefox"), dirs[0].ID) + assert.Equal(t, browser.UserDataDirID("firefox"), dirs[0].ID) assert.Equal(t, filepath.Join(home, "Profiles"), dirs[0].Path) assert.Equal(t, []browser.Profile{ {Name: "abcd1234.default-release", Dir: "abcd1234.default-release"}, @@ -61,12 +61,12 @@ func TestDiscover_ProfilesAreDirsWithDataFiles(t *testing.T) { } func TestDiscover_MissingUserDataDirYieldsNothing(t *testing.T) { - dirs, err := Discover(testDef("Profiles"), browser.DiscoverOptions{Home: t.TempDir()}) + dirs, err := Discover(testBrowser("Profiles"), browser.DiscoverOptions{Home: t.TempDir()}) require.NoError(t, err) assert.Empty(t, dirs) } -// A user data dir that exists but cannot be read must not look like a browser that is not installed. +// TestDiscover_UnreadableUserDataDirIsAnError keeps an unreadable dir from looking like a browser not installed. func TestDiscover_UnreadableUserDataDirIsAnError(t *testing.T) { if runtime.GOOS == "windows" || os.Geteuid() == 0 { t.Skip("directory permissions do not deny reads here") @@ -77,19 +77,19 @@ func TestDiscover_UnreadableUserDataDirIsAnError(t *testing.T) { require.NoError(t, os.Chmod(profiles, 0o000)) defer func() { require.NoError(t, os.Chmod(profiles, 0o700)) }() - dirs, err := Discover(testDef("Profiles"), browser.DiscoverOptions{Home: home}) + dirs, err := Discover(testBrowser("Profiles"), browser.DiscoverOptions{Home: home}) require.Error(t, err) assert.Empty(t, dirs) } -// Before, -p searched its parent and exported every profile beside the one it named. +// TestDiscover_ProfilePathSelectsOnlyThatProfile guards a fixed bug: -p exported every profile beside its own. func TestDiscover_ProfilePathSelectsOnlyThatProfile(t *testing.T) { custom := t.TempDir() touch(t, custom, "abcd1234.default-release", "places.sqlite") touch(t, custom, "wxyz5678.work", "places.sqlite") - opts := browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: filepath.Join(custom, "abcd1234.default-release")} - dirs, err := Discover(testDef("Profiles"), opts) + options := browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: filepath.Join(custom, "abcd1234.default-release")} + dirs, err := Discover(testBrowser("Profiles"), options) require.NoError(t, err) require.Len(t, dirs, 1) assert.Equal(t, custom, dirs[0].Path) @@ -100,37 +100,37 @@ func TestDiscover_ProfilePathWithoutDataFindsNothing(t *testing.T) { custom := t.TempDir() touch(t, custom, "abcd1234.default-release", "key4.db") - opts := browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: filepath.Join(custom, "abcd1234.default-release")} - dirs, err := Discover(testDef("Profiles"), opts) + options := browser.DiscoverOptions{Home: t.TempDir(), ProfilePath: filepath.Join(custom, "abcd1234.default-release")} + dirs, err := Discover(testBrowser("Profiles"), options) require.NoError(t, err) assert.Empty(t, dirs) } func TestExtractors_CoverFirefoxCategories(t *testing.T) { - ex := Extractors(browser.UserDataDir{Def: testDef()}, browser.Profile{}) - for _, c := range category.All() { - e, ok := ex[c] - if c == category.CreditCard || c == category.SessionStorage { - assert.Falsef(t, ok, "Firefox has no %s extractor", c) + extractors := Extractors(browser.UserDataDir{Browser: testBrowser()}, browser.Profile{}) + for _, dataCategory := range category.All() { + extractor, ok := extractors[dataCategory] + if dataCategory == category.CreditCard || dataCategory == category.SessionStorage { + assert.Falsef(t, ok, "Firefox has no %s extractor", dataCategory) continue } - if assert.Truef(t, ok, "no extractor for %s", c) { - assert.NotNil(t, e.Extract, c) - assert.NotEmpty(t, e.Sources, c) + if assert.Truef(t, ok, "no extractor for %s", dataCategory) { + assert.NotNil(t, extractor.Extract, dataCategory) + assert.NotEmpty(t, extractor.FileSpecs, dataCategory) } } } -// Without key4.db the logins export with empty secrets; before, a legacy-cipher login without a key panicked. +// TestExtractLogins_WithoutKeyStore exports empty secrets without key4.db; a legacy-cipher login once panicked. func TestExtractLogins_WithoutKeyStore(t *testing.T) { - enc := loginPBEBase64(t) + encodedLogin := loginPBEBase64(t) logins := createTestJSON(t, "logins.json", fmt.Sprintf(`{"logins": [{"hostname": "https://a.test", - "encryptedUsername": %q, "encryptedPassword": %q, "timeCreated": 1700000000000}]}`, enc, enc)) - ps := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"p/logins.json": logins}), + "encryptedUsername": %q, "encryptedPassword": %q, "timeCreated": 1700000000000}]}`, encodedLogin, encodedLogin)) + profileSnapshot := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{"p/logins.json": logins}), browser.Profile{Name: "p", Dir: "p"}, nil) var out testCollector - require.NoError(t, extractLogins(context.Background(), ps, &out)) + require.NoError(t, extractLogins(context.Background(), profileSnapshot, &out)) got := collected[record.Login](t, &out) require.Len(t, got, 1) assert.Equal(t, "https://a.test", got[0].URL) @@ -140,34 +140,34 @@ func TestExtractLogins_WithoutKeyStore(t *testing.T) { assert.ErrorIs(t, out.fails[0], fs.ErrNotExist) } -// A profile with no saved logins never needs its key, so an unreadable key4.db is no problem there. +// TestExtractLogins_NoLoginsNeverReadsTheKey leaves key4.db unread without logins, so an unreadable one is harmless. func TestExtractLogins_NoLoginsNeverReadsTheKey(t *testing.T) { - ps := browser.NewProfileSnapshot(snapshotOf(t, map[string]string{ + profileSnapshot := browser.NewProfileSnapshot(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", Dir: "p"}, nil) var out testCollector - require.NoError(t, extractLogins(context.Background(), ps, &out)) + require.NoError(t, extractLogins(context.Background(), profileSnapshot, &out)) assert.Empty(t, out.records) assert.Empty(t, out.fails) } -// One snapshot serves every profile of a user data dir; each profile must read its own files from it. +// TestExtractors_EachProfileReadsItsOwnFiles reads one snapshot shared by every profile; each must get its own files. func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) { - snap := snapshotOf(t, map[string]string{ + dirSnapshot := snapshotOf(t, map[string]string{ "a.default/places.sqlite": createTestDB(t, "places.sqlite", []string{mozPlacesSchema}, insertMozPlace(1, "https://home.example", "Home", 1, 1700000000000000)), "b.work/places.sqlite": createTestDB(t, "places.sqlite", []string{mozPlacesSchema}, insertMozPlace(1, "https://work.example", "Work", 1, 1700000000000000)), }) - dir := browser.UserDataDir{Def: testDef()} + dir := browser.UserDataDir{Browser: testBrowser()} want := map[string]string{"a.default": "Home", "b.work": "Work"} - for _, p := range []browser.Profile{{Name: "a.default", Dir: "a.default"}, {Name: "b.work", Dir: "b.work"}} { + for _, profile := range []browser.Profile{{Name: "a.default", Dir: "a.default"}, {Name: "b.work", Dir: "b.work"}} { var out testCollector - require.NoError(t, Extractors(dir, p)[category.History].Extract(context.Background(), browser.NewProfileSnapshot(snap, p, nil), &out)) + require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewProfileSnapshot(dirSnapshot, profile, nil), &out)) got := collected[record.History](t, &out) - require.Len(t, got, 1, p.Name) - assert.Equal(t, want[p.Name], got[0].Title, p.Name) + require.Len(t, got, 1, profile.Name) + assert.Equal(t, want[profile.Name], got[0].Title, profile.Name) } } diff --git a/internal/browser/firefox/masterkey.go b/internal/browser/firefox/masterkey.go index dde1a4b..3581909 100644 --- a/internal/browser/firefox/masterkey.go +++ b/internal/browser/firefox/masterkey.go @@ -17,12 +17,12 @@ import ( // retrieveMasterKey derives the key candidates in key4.db and returns the one that opens the logins in loginsPath. func retrieveMasterKey(key4Path, loginsPath string) ([]byte, error) { - k4, err := readKey4DB(key4Path) + key4, err := readKey4DB(key4Path) if err != nil { return nil, err } - keys, err := k4.deriveKeys() + keys, err := key4.deriveKeys() if err != nil { return nil, err } @@ -37,7 +37,7 @@ func retrieveMasterKey(key4Path, loginsPath string) ([]byte, error) { return nil, fmt.Errorf("derived %d key(s) but none could decrypt logins", len(keys)) } -// See https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/ for key4.db's layout. +// key4DB mirrors key4.db; see https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/ for its layout. type key4DB struct { globalSalt []byte // metaData.item1: salt used as PBE decryption input passwordCheck []byte // metaData.item2: encrypted marker to verify DB integrity @@ -49,36 +49,36 @@ type privateKey struct { typeTag []byte // a102: key type identifier (must match nssKeyTypeTag) } -// Only nssPrivate rows tagged with this a102 value hold keys; see softoken/pkcs11i.h in NSS. +// nssKeyTypeTag is the a102 value of the nssPrivate rows that hold keys; see softoken/pkcs11i.h in NSS. var nssKeyTypeTag = []byte{248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} func readKey4DB(path string) (*key4DB, error) { - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) if err != nil { return nil, fmt.Errorf("open key4.db: %w", err) } - defer db.Close() + defer database.Close() var record key4DB const metaQuery = `SELECT item1, item2 FROM metaData WHERE id = 'password'` - if err := db.QueryRow(metaQuery).Scan(&record.globalSalt, &record.passwordCheck); err != nil { + if err := database.QueryRow(metaQuery).Scan(&record.globalSalt, &record.passwordCheck); err != nil { return nil, fmt.Errorf("query metaData: %w", err) } const nssQuery = `SELECT a11, a102 FROM nssPrivate` - rows, err := db.Query(nssQuery) + rows, err := database.Query(nssQuery) if err != nil { return nil, fmt.Errorf("query nssPrivate: %w", err) } defer rows.Close() for rows.Next() { - var pk privateKey - if err := rows.Scan(&pk.encrypted, &pk.typeTag); err != nil { + var entry privateKey + if err := rows.Scan(&entry.encrypted, &entry.typeTag); err != nil { return nil, fmt.Errorf("scan nssPrivate row: %w", err) } - record.privateKeys = append(record.privateKeys, pk) + record.privateKeys = append(record.privateKeys, entry) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("iterate nssPrivate: %w", err) @@ -96,11 +96,11 @@ func (k *key4DB) deriveKeys() ([][]byte, error) { } var keys [][]byte - for _, pk := range k.privateKeys { - if !bytes.Equal(pk.typeTag, nssKeyTypeTag) { + for _, entry := range k.privateKeys { + if !bytes.Equal(entry.typeTag, nssKeyTypeTag) { continue } - key, err := k.decryptPrivateKey(pk) + key, err := k.decryptPrivateKey(entry) if err != nil { log.Debugf("decrypt nss private key: %v", err) continue @@ -125,8 +125,8 @@ func (k *key4DB) verifyPasswordCheck() error { return nil } -func (k *key4DB) decryptPrivateKey(pk privateKey) ([]byte, error) { - pbe, err := crypto.NewASN1PBE(pk.encrypted) +func (k *key4DB) decryptPrivateKey(entry privateKey) ([]byte, error) { + pbe, err := crypto.NewASN1PBE(entry.encrypted) if err != nil { return nil, fmt.Errorf("parse private key: %w", err) } @@ -164,16 +164,16 @@ func validateKeyWithLogins(keys [][]byte, loginsPath string) []byte { return nil } -// Up to 5 logins are enough to tell which key opens them. +// sampleEncryptedLogins takes up to 5 logins, enough to tell which key opens them. func sampleEncryptedLogins(raw []byte) []encryptedLogin { - arr := gjson.GetBytes(raw, "logins").Array() + logins := gjson.GetBytes(raw, "logins").Array() var samples []encryptedLogin - for _, v := range arr { - userRaw, err := base64.StdEncoding.DecodeString(v.Get("encryptedUsername").String()) + for _, value := range logins { + userRaw, err := base64.StdEncoding.DecodeString(value.Get("encryptedUsername").String()) if err != nil { continue } - pwdRaw, err := base64.StdEncoding.DecodeString(v.Get("encryptedPassword").String()) + pwdRaw, err := base64.StdEncoding.DecodeString(value.Get("encryptedPassword").String()) if err != nil { continue } diff --git a/internal/browser/firefox/masterkey_test.go b/internal/browser/firefox/masterkey_test.go index df5e84e..b973492 100644 --- a/internal/browser/firefox/masterkey_test.go +++ b/internal/browser/firefox/masterkey_test.go @@ -19,16 +19,16 @@ func TestReadKey4DB(t *testing.T) { `INSERT INTO nssPrivate (a11, a102) VALUES (x'feedface', x'12345678')`, ) - k4, err := readKey4DB(path) + key4, err := readKey4DB(path) require.NoError(t, err) - assert.Equal(t, []byte{0xaa, 0xbb, 0xcc, 0xdd}, k4.globalSalt) - assert.Equal(t, []byte{0x11, 0x22, 0x33, 0x44}, k4.passwordCheck) - require.Len(t, k4.privateKeys, 2) + assert.Equal(t, []byte{0xaa, 0xbb, 0xcc, 0xdd}, key4.globalSalt) + assert.Equal(t, []byte{0x11, 0x22, 0x33, 0x44}, key4.passwordCheck) + require.Len(t, key4.privateKeys, 2) // Don't assume row order — check that both entries exist encryptedBlobs := map[string]bool{} - for _, pk := range k4.privateKeys { - encryptedBlobs[fmt.Sprintf("%x", pk.encrypted)] = true + for _, entry := range key4.privateKeys { + encryptedBlobs[fmt.Sprintf("%x", entry.encrypted)] = true } assert.True(t, encryptedBlobs["deadbeef"]) assert.True(t, encryptedBlobs["feedface"]) diff --git a/internal/browser/firefox/testutil_test.go b/internal/browser/firefox/testutil_test.go index 65c2a93..7696c46 100644 --- a/internal/browser/firefox/testutil_test.go +++ b/internal/browser/firefox/testutil_test.go @@ -109,11 +109,11 @@ func insertMozPlace(id int, url, title string, visitCount int, lastVisitDate int ) } -func insertMozBookmark(id, fk, bookmarkType int, title string, dateAdded int64) string { +func insertMozBookmark(id, foreignKey, bookmarkType int, title string, dateAdded int64) string { return fmt.Sprintf( `INSERT INTO moz_bookmarks (id, type, fk, parent, position, title, dateAdded, lastModified, guid) VALUES (%d, %d, %d, 0, 0, '%s', %d, %d, 'bm-guid-%d')`, - id, bookmarkType, fk, title, dateAdded, dateAdded, id, + id, bookmarkType, foreignKey, title, dateAdded, dateAdded, id, ) } @@ -143,16 +143,16 @@ func installFile(t *testing.T, profileDir, srcPath, dstName string) { func createTestDB(t *testing.T, name string, schemas []string, inserts ...string) string { t.Helper() path := filepath.Join(t.TempDir(), name) - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) require.NoError(t, err) - defer db.Close() + defer database.Close() for _, schema := range schemas { - _, err = db.Exec(schema) + _, err = database.Exec(schema) require.NoError(t, err) } - for _, stmt := range inserts { - _, err = db.Exec(stmt) + for _, statement := range inserts { + _, err = database.Exec(statement) require.NoError(t, err) } return path @@ -170,16 +170,16 @@ type testCollector struct { fails []error } -func (c *testCollector) Add(r record.Record) { c.records = append(c.records, r) } -func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) } +func (c *testCollector) Add(row record.Record) { c.records = append(c.records, row) } +func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) } -func collected[T any](t *testing.T, c *testCollector) []T { +func collected[T any](t *testing.T, collector *testCollector) []T { t.Helper() - got := make([]T, 0, len(c.records)) - for _, r := range c.records { - v, ok := any(r).(*T) - require.Truef(t, ok, "collected a %T, want *%T", r, *new(T)) - got = append(got, *v) + got := make([]T, 0, len(collector.records)) + for _, row := range collector.records { + value, ok := any(row).(*T) + require.Truef(t, ok, "collected a %T, want *%T", row, *new(T)) + got = append(got, *value) } return got } diff --git a/internal/browser/platform_darwin.go b/internal/browser/platform_darwin.go index 969e540..e6e2e42 100644 --- a/internal/browser/platform_darwin.go +++ b/internal/browser/platform_darwin.go @@ -2,4 +2,4 @@ package browser -func (d Def) Platform() Platform { return d.Darwin } +func (b Browser) Platform() Platform { return b.Darwin } diff --git a/internal/browser/platform_linux.go b/internal/browser/platform_linux.go index 1f4712b..ad1de40 100644 --- a/internal/browser/platform_linux.go +++ b/internal/browser/platform_linux.go @@ -2,4 +2,4 @@ package browser -func (d Def) Platform() Platform { return d.Linux } +func (b Browser) Platform() Platform { return b.Linux } diff --git a/internal/browser/platform_windows.go b/internal/browser/platform_windows.go index 7a2fc52..5d0efe8 100644 --- a/internal/browser/platform_windows.go +++ b/internal/browser/platform_windows.go @@ -2,4 +2,4 @@ package browser -func (d Def) Platform() Platform { return d.Windows } +func (b Browser) Platform() Platform { return b.Windows } diff --git a/internal/browser/safari/extract_bookmark.go b/internal/browser/safari/extract_bookmark.go index 408559e..6615fab 100644 --- a/internal/browser/safari/extract_bookmark.go +++ b/internal/browser/safari/extract_bookmark.go @@ -29,14 +29,14 @@ const ( ) func extractBookmarks(path string, out browser.Collector) error { - f, err := os.Open(path) + file, err := os.Open(path) if err != nil { return fmt.Errorf("open bookmarks: %w", err) } - defer f.Close() + defer file.Close() var root safariBookmark - if err := plist.NewDecoder(f).Decode(&root); err != nil { + if err := plist.NewDecoder(file).Decode(&root); err != nil { return fmt.Errorf("decode bookmarks: %w", err) } @@ -46,7 +46,7 @@ func extractBookmarks(path string, out browser.Collector) error { return nil } -// A leaf's ID is its position among all leaves, from 1: the plist stores no number, and per-folder indexes repeat. +// walkBookmarks numbers leaves from 1 across all folders: the plist stores no number, and per-folder indexes repeat. func walkBookmarks(nodes []safariBookmark, folder string, out *[]record.Bookmark) { for _, node := range nodes { switch node.Type { diff --git a/internal/browser/safari/extract_bookmark_test.go b/internal/browser/safari/extract_bookmark_test.go index d57ad9f..da49fe0 100644 --- a/internal/browser/safari/extract_bookmark_test.go +++ b/internal/browser/safari/extract_bookmark_test.go @@ -15,10 +15,10 @@ import ( func buildTestBookmarksPlist(t *testing.T, root safariBookmark) string { t.Helper() path := filepath.Join(t.TempDir(), "Bookmarks.plist") - f, err := os.Create(path) + file, err := os.Create(path) require.NoError(t, err) - defer f.Close() - require.NoError(t, plist.NewBinaryEncoder(f).Encode(root)) + defer file.Close() + require.NoError(t, plist.NewBinaryEncoder(file).Encode(root)) return path } @@ -174,7 +174,7 @@ func TestExtractBookmarks_Empty(t *testing.T) { assert.Empty(t, bookmarks) } -// Before, each ID was the index among its siblings, so the first bookmark of every folder was 0. +// TestExtractBookmarks_IDsAreUniqueAcrossFolders guards a fixed bug: IDs were sibling indexes, so each folder had a 0. func TestExtractBookmarks_IDsAreUniqueAcrossFolders(t *testing.T) { leaf := func(url string) safariBookmark { return safariBookmark{Type: bookmarkTypeLeaf, URLString: url, URIDictionary: uriDictionary{Title: url}} @@ -195,9 +195,9 @@ func TestExtractBookmarks_IDsAreUniqueAcrossFolders(t *testing.T) { require.NoError(t, extractBookmarks(path, &out)) var ids []int64 var urls []string - for _, b := range collected[record.Bookmark](t, &out) { - ids = append(ids, b.ID) - urls = append(urls, b.URL) + for _, bookmark := range collected[record.Bookmark](t, &out) { + ids = append(ids, bookmark.ID) + urls = append(urls, bookmark.URL) } assert.Equal(t, []int64{1, 2, 3, 4}, ids) assert.Equal(t, []string{"https://a.test", "https://b.test", "https://c.test", "https://d.test"}, urls) diff --git a/internal/browser/safari/extract_cookie.go b/internal/browser/safari/extract_cookie.go index 5863116..6e28013 100644 --- a/internal/browser/safari/extract_cookie.go +++ b/internal/browser/safari/extract_cookie.go @@ -18,20 +18,20 @@ func extractCookies(path string, out browser.Collector) error { var cookies []record.Cookie for _, page := range pages { - for _, c := range page.Cookies { - hasExpire := !c.Expires.IsZero() + for _, cookie := range page.Cookies { + hasExpire := !cookie.Expires.IsZero() // binarycookies returns local times; UTC keeps the JSON in line with Chromium's and Firefox's cookies. cookies = append(cookies, record.Cookie{ - Host: string(c.Domain), - Path: string(c.Path), - Name: string(c.Name), - Value: string(c.Value), - IsSecure: c.Secure, - IsHTTPOnly: c.HTTPOnly, + Host: string(cookie.Domain), + Path: string(cookie.Path), + Name: string(cookie.Name), + Value: string(cookie.Value), + IsSecure: cookie.Secure, + IsHTTPOnly: cookie.HTTPOnly, HasExpire: hasExpire, IsPersistent: hasExpire, - ExpireAt: c.Expires.UTC(), - CreatedAt: c.Creation.UTC(), + ExpireAt: cookie.Expires.UTC(), + CreatedAt: cookie.Creation.UTC(), }) } } @@ -40,13 +40,13 @@ func extractCookies(path string, out browser.Collector) error { } func decodeBinaryCookies(path string) ([]binarycookies.Page, error) { - f, err := os.Open(path) + file, err := os.Open(path) if err != nil { return nil, fmt.Errorf("open cookies file: %w", err) } - defer f.Close() + defer file.Close() - jar := binarycookies.New(f) + jar := binarycookies.New(file) pages, err := jar.Decode() if err != nil { return nil, fmt.Errorf("decode cookies: %w", err) diff --git a/internal/browser/safari/extract_cookie_test.go b/internal/browser/safari/extract_cookie_test.go index cf5deb2..1d18bda 100644 --- a/internal/browser/safari/extract_cookie_test.go +++ b/internal/browser/safari/extract_cookie_test.go @@ -13,37 +13,37 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// Each cookie goes in its own page of a minimal Cookies.binarycookies file. +// buildTestBinaryCookies puts each cookie in its own page of a minimal Cookies.binarycookies file. func buildTestBinaryCookies(t *testing.T, cookies []testCookie) string { t.Helper() var pages [][]byte - for _, c := range cookies { - pages = append(pages, buildPage(c)) + for _, cookie := range cookies { + pages = append(pages, buildPage(cookie)) } path := filepath.Join(t.TempDir(), "Cookies.binarycookies") - f, err := os.Create(path) + file, err := os.Create(path) require.NoError(t, err) - defer f.Close() + defer file.Close() // File header: magic + numPages (big-endian) - _, err = f.WriteString("cook") + _, err = file.WriteString("cook") require.NoError(t, err) - require.NoError(t, binary.Write(f, binary.BigEndian, uint32(len(pages)))) + require.NoError(t, binary.Write(file, binary.BigEndian, uint32(len(pages)))) // Page sizes (big-endian) - for _, p := range pages { - require.NoError(t, binary.Write(f, binary.BigEndian, uint32(len(p)))) + for _, page := range pages { + require.NoError(t, binary.Write(file, binary.BigEndian, uint32(len(page)))) } - for _, p := range pages { - _, err = f.Write(p) + for _, page := range pages { + _, err = file.Write(page) require.NoError(t, err) } // Checksum (8 bytes, not validated by decoder) - _, err = f.Write(make([]byte, 8)) + _, err = file.Write(make([]byte, 8)) require.NoError(t, err) return path @@ -55,28 +55,28 @@ type testCookie struct { expires, creation float64 // Core Data epoch seconds } -func buildPage(c testCookie) []byte { +func buildPage(fixture testCookie) []byte { // Cookie string data: domain\0 name\0 path\0 value\0 - domain := c.domain + "\x00" - name := c.name + "\x00" - cpath := c.path + "\x00" - value := c.value + "\x00" + domain := fixture.domain + "\x00" + name := fixture.name + "\x00" + cookiePath := fixture.path + "\x00" + value := fixture.value + "\x00" // A cookie is a 56-byte header (sizes, flags, string offsets, expiry, creation), then its strings. const headerSize = 56 domainOffset := uint32(headerSize) nameOffset := domainOffset + uint32(len(domain)) pathOffset := nameOffset + uint32(len(name)) - valueOffset := pathOffset + uint32(len(cpath)) + valueOffset := pathOffset + uint32(len(cookiePath)) cookieSize := valueOffset + uint32(len(value)) var flags uint32 switch { - case c.secure && c.httpOnly: + case fixture.secure && fixture.httpOnly: flags = 0x5 - case c.httpOnly: + case fixture.httpOnly: flags = 0x4 - case c.secure: + case fixture.secure: flags = 0x1 } @@ -88,11 +88,11 @@ func buildPage(c testCookie) []byte { binary.LittleEndian.PutUint32(cookie[20:], nameOffset) binary.LittleEndian.PutUint32(cookie[24:], pathOffset) binary.LittleEndian.PutUint32(cookie[28:], valueOffset) - binary.LittleEndian.PutUint64(cookie[40:], math.Float64bits(c.expires)) - binary.LittleEndian.PutUint64(cookie[48:], math.Float64bits(c.creation)) + binary.LittleEndian.PutUint64(cookie[40:], math.Float64bits(fixture.expires)) + binary.LittleEndian.PutUint64(cookie[48:], math.Float64bits(fixture.creation)) copy(cookie[domainOffset:], domain) copy(cookie[nameOffset:], name) - copy(cookie[pathOffset:], cpath) + copy(cookie[pathOffset:], cookiePath) copy(cookie[valueOffset:], value) // Page layout: marker(4) + cookieCount(4) + offsets(4*N) + endMarker(4) + cookies @@ -130,14 +130,14 @@ func TestExtractCookies(t *testing.T) { assert.Equal(t, ".example.com", cookies[0].Host) assert.Equal(t, ".go.dev", cookies[1].Host) - c := cookies[0] - assert.Equal(t, "session", c.Name) - assert.Equal(t, "abc123", c.Value) - assert.Equal(t, "/", c.Path) - assert.True(t, c.IsSecure) - assert.True(t, c.IsHTTPOnly) - assert.False(t, c.CreatedAt.IsZero()) - assert.False(t, c.ExpireAt.IsZero()) + cookie := cookies[0] + assert.Equal(t, "session", cookie.Name) + assert.Equal(t, "abc123", cookie.Value) + assert.Equal(t, "/", cookie.Path) + assert.True(t, cookie.IsSecure) + assert.True(t, cookie.IsHTTPOnly) + assert.False(t, cookie.CreatedAt.IsZero()) + assert.False(t, cookie.ExpireAt.IsZero()) } func TestExtractCookies_InvalidFile(t *testing.T) { diff --git a/internal/browser/safari/extract_download.go b/internal/browser/safari/extract_download.go index 47a1f9f..615b12e 100644 --- a/internal/browser/safari/extract_download.go +++ b/internal/browser/safari/extract_download.go @@ -23,28 +23,28 @@ type safariDownloadEntry struct { DownloadIdentifier string `plist:"DownloadEntryIdentifier"` } -// Downloads.plist is shared across profiles: entries are kept by owner UUID, and untagged ones are the default's. +// extractDownloads filters the shared Downloads.plist by owner UUID; untagged entries belong to the default profile. func extractDownloads(path, ownerUUID string, out browser.Collector) error { - f, err := os.Open(path) + file, err := os.Open(path) if err != nil { return fmt.Errorf("open downloads: %w", err) } - defer f.Close() + defer file.Close() - var dl safariDownloads - if err := plist.NewDecoder(f).Decode(&dl); err != nil { + var decoded safariDownloads + if err := plist.NewDecoder(file).Decode(&decoded); err != nil { return fmt.Errorf("decode downloads: %w", err) } var downloads []record.Download - for _, d := range dl.DownloadHistory { - if !ownsDownload(d.ProfileUUID, ownerUUID) { + for _, entry := range decoded.DownloadHistory { + if !ownsDownload(entry.ProfileUUID, ownerUUID) { continue } downloads = append(downloads, record.Download{ - URL: d.URL, - TargetPath: d.Path, - TotalBytes: d.TotalBytes, + URL: entry.URL, + TargetPath: entry.Path, + TotalBytes: entry.TotalBytes, }) } emit(out, downloads) diff --git a/internal/browser/safari/extract_download_test.go b/internal/browser/safari/extract_download_test.go index 96c75dd..2b38b8a 100644 --- a/internal/browser/safari/extract_download_test.go +++ b/internal/browser/safari/extract_download_test.go @@ -12,20 +12,20 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -func buildTestDownloadsPlist(t *testing.T, dl safariDownloads) string { +func buildTestDownloadsPlist(t *testing.T, downloadsPlist safariDownloads) string { t.Helper() path := filepath.Join(t.TempDir(), "Downloads.plist") - f, err := os.Create(path) + file, err := os.Create(path) require.NoError(t, err) - defer f.Close() - require.NoError(t, plist.NewBinaryEncoder(f).Encode(dl)) + defer file.Close() + require.NoError(t, plist.NewBinaryEncoder(file).Encode(downloadsPlist)) return path } func TestExtractDownloads_DefaultProfileOnly(t *testing.T) { // Only DefaultProfile and untagged (pre-profile) entries surface for the default profile. const namedUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" - dl := safariDownloads{ + downloadsPlist := safariDownloads{ DownloadHistory: []safariDownloadEntry{ {URL: "https://a.com/a.zip", Path: "/tmp/a.zip", TotalBytes: 1024000, ProfileUUID: defaultProfileSentinel}, {URL: "https://b.com/b.zip", Path: "/tmp/b.zip", TotalBytes: 98765432, ProfileUUID: namedUUID}, @@ -33,7 +33,7 @@ func TestExtractDownloads_DefaultProfileOnly(t *testing.T) { }, } - path := buildTestDownloadsPlist(t, dl) + path := buildTestDownloadsPlist(t, downloadsPlist) var out testCollector err := extractDownloads(path, defaultProfileSentinel, &out) downloads := collected[record.Download](t, &out) @@ -45,14 +45,14 @@ func TestExtractDownloads_DefaultProfileOnly(t *testing.T) { func TestExtractDownloads_NamedProfileOnly(t *testing.T) { const namedUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" - dl := safariDownloads{ + downloadsPlist := safariDownloads{ DownloadHistory: []safariDownloadEntry{ {URL: "https://a.com/a.zip", Path: "/tmp/a.zip", TotalBytes: 100, ProfileUUID: defaultProfileSentinel}, {URL: "https://b.com/b.zip", Path: "/tmp/b.zip", TotalBytes: 200, ProfileUUID: namedUUID}, }, } - path := buildTestDownloadsPlist(t, dl) + path := buildTestDownloadsPlist(t, downloadsPlist) var out testCollector err := extractDownloads(path, namedUUID, &out) downloads := collected[record.Download](t, &out) @@ -63,8 +63,8 @@ func TestExtractDownloads_NamedProfileOnly(t *testing.T) { } func TestExtractDownloads_Empty(t *testing.T) { - dl := safariDownloads{} - path := buildTestDownloadsPlist(t, dl) + downloadsPlist := safariDownloads{} + path := buildTestDownloadsPlist(t, downloadsPlist) var out testCollector err := extractDownloads(path, defaultProfileSentinel, &out) diff --git a/internal/browser/safari/extract_extension.go b/internal/browser/safari/extract_extension.go index 2bcbc9f..f25992c 100644 --- a/internal/browser/safari/extract_extension.go +++ b/internal/browser/safari/extract_extension.go @@ -13,11 +13,11 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// Safari keeps App Extensions and Web Extensions in two plists keyed by " ()". +// extensionKeyPattern parses the " ()" keys of the App Extensions and Web Extensions plists. // Only Web Extensions carry Enabled; a listed App Extension is enabled. var extensionKeyPattern = regexp.MustCompile(`^(\S+)\s+\(([^)]+)\)$`) -// Only the fields record.Extension needs are decoded. +// safariExtension decodes only the fields record.Extension needs. type safariExtension struct { Enabled *bool `plist:"Enabled"` } @@ -30,11 +30,11 @@ func extractExtensions(paths []string, out browser.Collector) error { } extensions := make([]record.Extension, 0, len(records)) - for _, r := range records { + for _, entry := range records { extensions = append(extensions, record.Extension{ - Name: r.bundleID, - ID: r.key, - Enabled: r.enabled, + Name: entry.bundleID, + ID: entry.key, + Enabled: entry.enabled, }) } emit(out, extensions) @@ -49,8 +49,8 @@ type extensionRecord struct { func readSafariExtensions(paths []string) ([]extensionRecord, error) { var all []extensionRecord - for _, p := range paths { - records, err := decodeSafariExtensionsPlist(p) + for _, plistPath := range paths { + records, err := decodeSafariExtensionsPlist(plistPath) if err != nil { return nil, err } @@ -61,22 +61,22 @@ func readSafariExtensions(paths []string) ([]extensionRecord, error) { } func decodeSafariExtensionsPlist(path string) ([]extensionRecord, error) { - f, err := os.Open(path) + file, err := os.Open(path) if err != nil { return nil, err } - defer f.Close() + defer file.Close() var decoded map[string]safariExtension - if err := plist.NewDecoder(f).Decode(&decoded); err != nil { + if err := plist.NewDecoder(file).Decode(&decoded); err != nil { return nil, fmt.Errorf("decode extensions %s: %w", path, err) } records := make([]extensionRecord, 0, len(decoded)) - for key, ext := range decoded { + for key, extension := range decoded { enabled := true - if ext.Enabled != nil { - enabled = *ext.Enabled + if extension.Enabled != nil { + enabled = *extension.Enabled } records = append(records, extensionRecord{ key: key, @@ -87,10 +87,10 @@ func decodeSafariExtensionsPlist(path string) ([]extensionRecord, error) { return records, nil } -// A key that does not match the pattern falls back to the whole trimmed key. +// bundleIDFromExtensionKey falls back to the whole trimmed key when it does not match the pattern. func bundleIDFromExtensionKey(key string) string { - if m := extensionKeyPattern.FindStringSubmatch(key); m != nil { - return m[1] + if match := extensionKeyPattern.FindStringSubmatch(key); match != nil { + return match[1] } return strings.TrimSpace(key) } diff --git a/internal/browser/safari/extract_extension_test.go b/internal/browser/safari/extract_extension_test.go index 49c974b..b030b82 100644 --- a/internal/browser/safari/extract_extension_test.go +++ b/internal/browser/safari/extract_extension_test.go @@ -12,7 +12,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// A map rather than safariExtension, so fixtures can omit Enabled as App Extensions do. +// testExtensionEntry is a map rather than safariExtension, so fixtures can omit Enabled as App Extensions do. type testExtensionEntry map[string]any func writeTestExtensionsPlist(t *testing.T, container, subdir string, entries map[string]testExtensionEntry) { @@ -20,18 +20,18 @@ func writeTestExtensionsPlist(t *testing.T, container, subdir string, entries ma dir := filepath.Join(container, "Safari", subdir) require.NoError(t, os.MkdirAll(dir, 0o755)) - f, err := os.Create(filepath.Join(dir, "Extensions.plist")) + file, err := os.Create(filepath.Join(dir, "Extensions.plist")) require.NoError(t, err) - defer f.Close() - require.NoError(t, plist.NewBinaryEncoder(f).Encode(entries)) + defer file.Close() + require.NoError(t, plist.NewBinaryEncoder(file).Encode(entries)) } // extensionPlists lists the plists present under container, as the extractor finds them in its snapshot. func extensionPlists(container string) []string { var paths []string for _, sub := range []string{"AppExtensions", "WebExtensions"} { - if p := filepath.Join(container, "Safari", sub, "Extensions.plist"); fileExists(p) { - paths = append(paths, p) + if plistPath := filepath.Join(container, "Safari", sub, "Extensions.plist"); fileExists(plistPath) { + paths = append(paths, plistPath) } } return paths diff --git a/internal/browser/safari/extract_history.go b/internal/browser/safari/extract_history.go index c1e1526..f1bf87c 100644 --- a/internal/browser/safari/extract_history.go +++ b/internal/browser/safari/extract_history.go @@ -10,7 +10,7 @@ import ( ) const ( - // Each item joins its latest visit, so title and visit_time come from the same history_visits row. + // safariHistoryQuery joins each item's latest visit, so title and visit_time come from the same history_visits row. safariHistoryQuery = `SELECT hi.url, COALESCE(hv.title, ''), hi.visit_count, COALESCE(hv.visit_time, 0) FROM history_items hi diff --git a/internal/browser/safari/extract_history_test.go b/internal/browser/safari/extract_history_test.go index f1f4c87..2520e3c 100644 --- a/internal/browser/safari/extract_history_test.go +++ b/internal/browser/safari/extract_history_test.go @@ -55,12 +55,12 @@ func TestExtractHistories_Dedup(t *testing.T) { require.Len(t, got, 3) // GitHub (item 1) should have the later visit_time and its title. - for _, h := range got { - if h.URL == "https://github.com" { + for _, history := range got { + if history.URL == "https://github.com" { // 705067600 + 978307200 = 1683374800 (unix) - assert.Equal(t, int64(1683374800), h.LastVisit.Unix()) + assert.Equal(t, int64(1683374800), history.LastVisit.Unix()) // Title must come from the latest visit row, not an arbitrary one. - assert.Equal(t, "GitHub - Latest", h.Title) + assert.Equal(t, "GitHub - Latest", history.Title) return } } diff --git a/internal/browser/safari/extract_password.go b/internal/browser/safari/extract_password.go index d6ce186..13d4a33 100644 --- a/internal/browser/safari/extract_password.go +++ b/internal/browser/safari/extract_password.go @@ -9,23 +9,23 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -func extractPasswords(ctx context.Context, kc LoginKeychain, out browser.Collector) error { - passwords, err := kc.InternetPasswords(ctx) +func extractPasswords(ctx context.Context, loginKeychain LoginKeychain, out browser.Collector) error { + passwords, err := loginKeychain.InternetPasswords(ctx) if err != nil { return err } var logins []record.Login - for _, p := range passwords { - url := buildURL(p.Protocol, p.Server, p.Port, p.Path) - if url == "" || p.Account == "" { + for _, internetPassword := range passwords { + url := buildURL(internetPassword.Protocol, internetPassword.Server, internetPassword.Port, internetPassword.Path) + if url == "" || internetPassword.Account == "" { continue } logins = append(logins, record.Login{ URL: url, - Username: p.Account, - Password: p.PlainPassword, - CreatedAt: p.Created.UTC(), + Username: internetPassword.Account, + Password: internetPassword.PlainPassword, + CreatedAt: internetPassword.Created.UTC(), Store: record.StoreLocal, }) } diff --git a/internal/browser/safari/extract_password_test.go b/internal/browser/safari/extract_password_test.go index 542ae52..fb0ec24 100644 --- a/internal/browser/safari/extract_password_test.go +++ b/internal/browser/safari/extract_password_test.go @@ -82,10 +82,10 @@ func TestBuildURL(t *testing.T) { }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := buildURL(tt.protocol, tt.server, tt.port, tt.path) - assert.Equal(t, tt.want, got) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + got := buildURL(testCase.protocol, testCase.server, testCase.port, testCase.path) + assert.Equal(t, testCase.want, got) }) } } diff --git a/internal/browser/safari/extract_storage.go b/internal/browser/safari/extract_storage.go index 60395c6..3fd61d6 100644 --- a/internal/browser/safari/extract_storage.go +++ b/internal/browser/safari/extract_storage.go @@ -47,23 +47,23 @@ func extractLocalStorage(root string, out browser.Collector) error { } var entries []record.LocalStorage - for _, od := range dirs { - origin, err := readOriginFile(filepath.Join(od, webkitOriginFile)) + for _, originDir := range dirs { + origin, err := readOriginFile(filepath.Join(originDir, webkitOriginFile)) if err != nil { - log.Debugf("safari localstorage: origin %s: %v", od, err) + log.Debugf("safari localstorage: origin %s: %v", originDir, err) continue } - dbPath := filepath.Join(od, webkitLocalStorageSubdir, webkitLocalStorageDB) + dbPath := filepath.Join(originDir, webkitLocalStorageSubdir, webkitLocalStorageDB) items, err := readLocalStorageFile(dbPath) if err != nil { log.Debugf("safari localstorage: db %s: %v", dbPath, err) continue } - for _, it := range items { + for _, item := range items { entries = append(entries, record.LocalStorage{ URL: origin, - Key: it.key, - Value: it.value, + Key: item.key, + Value: item.value, }) } } @@ -71,7 +71,7 @@ func extractLocalStorage(root string, out browser.Collector) error { return nil } -// Only dirs holding both an origin file and a localstorage.sqlite3 count; the salt sibling and the rest are skipped. +// findOriginDataDirs counts only dirs with both an origin file and a localstorage.sqlite3; the salt sibling is skipped. func findOriginDataDirs(root string) ([]string, error) { topEntries, err := os.ReadDir(root) if err != nil { @@ -105,25 +105,25 @@ func findOriginDataDirs(root string) ([]string, error) { return out, nil } -// Port 0 is the scheme's default and is left out of the URL. +// originEndpoint leaves port 0, the scheme's default, out of the URL. type originEndpoint struct { scheme string host string port uint16 } -// The file holds the top-frame block, then the frame block; without a readable frame the top frame is reported. +// readOriginFile reads the top-frame block, then the frame block; without a readable frame the top frame is reported. func readOriginFile(path string) (string, error) { data, err := os.ReadFile(path) if err != nil { return "", fmt.Errorf("read origin file %s: %w", path, err) } - top, pos, terr := readOriginBlock(data, 0) - if terr != nil { - return "", fmt.Errorf("parse top-frame origin: %w", terr) + top, position, topErr := readOriginBlock(data, 0) + if topErr != nil { + return "", fmt.Errorf("parse top-frame origin: %w", topErr) } - frame, _, ferr := readOriginBlock(data, pos) - if ferr != nil { + frame, _, frameErr := readOriginBlock(data, position) + if frameErr != nil { frame = top } if frame.scheme == "" || frame.host == "" { @@ -132,72 +132,72 @@ func readOriginFile(path string) (string, error) { return formatOriginURL(frame), nil } -func readOriginBlock(data []byte, pos int) (originEndpoint, int, error) { - var ep originEndpoint +func readOriginBlock(data []byte, position int) (originEndpoint, int, error) { + var endpoint originEndpoint var err error - ep.scheme, pos, err = readOriginString(data, pos) + endpoint.scheme, position, err = readOriginString(data, position) if err != nil { - return ep, pos, err + return endpoint, position, err } - ep.host, pos, err = readOriginString(data, pos) + endpoint.host, position, err = readOriginString(data, position) if err != nil { - return ep, pos, err + return endpoint, position, err } - if pos >= len(data) { - return ep, pos, fmt.Errorf("unexpected EOF before port marker") + if position >= len(data) { + return endpoint, position, fmt.Errorf("unexpected EOF before port marker") } - marker := data[pos] - pos++ + marker := data[position] + position++ switch marker { case originPortDefaultMarker: - ep.port = 0 + endpoint.port = 0 case originPortExplicitFlag: - if pos+2 > len(data) { - return ep, pos, fmt.Errorf("truncated port value at offset %d", pos) + if position+2 > len(data) { + return endpoint, position, fmt.Errorf("truncated port value at offset %d", position) } - ep.port = binary.LittleEndian.Uint16(data[pos : pos+2]) - pos += 2 + endpoint.port = binary.LittleEndian.Uint16(data[position : position+2]) + position += 2 default: - return ep, pos, fmt.Errorf("unexpected port marker 0x%02x at offset %d", marker, pos-1) + return endpoint, position, fmt.Errorf("unexpected port marker 0x%02x at offset %d", marker, position-1) } - return ep, pos, nil + return endpoint, position, nil } // readOriginString consumes one length-prefixed record (uint32_le length + encoding byte + data). -func readOriginString(data []byte, pos int) (string, int, error) { - if pos+5 > len(data) { - return "", pos, fmt.Errorf("truncated string record at offset %d", pos) +func readOriginString(data []byte, position int) (string, int, error) { + if position+5 > len(data) { + return "", position, fmt.Errorf("truncated string record at offset %d", position) } - length := int(binary.LittleEndian.Uint32(data[pos : pos+4])) - enc := data[pos+4] - pos += 5 - if length < 0 || pos+length > len(data) { - return "", pos, fmt.Errorf("string record overruns buffer: length %d at offset %d", length, pos-5) + length := int(binary.LittleEndian.Uint32(data[position : position+4])) + encoding := data[position+4] + position += 5 + if length < 0 || position+length > len(data) { + return "", position, fmt.Errorf("string record overruns buffer: length %d at offset %d", length, position-5) } - chunk := data[pos : pos+length] - pos += length - switch enc { + chunk := data[position : position+length] + position += length + switch encoding { case originEncASCII: - return decodeLatin1(chunk), pos, nil + return decodeLatin1(chunk), position, nil case originEncUTF16: - return decodeUTF16LE(chunk), pos, nil + return decodeUTF16LE(chunk), position, nil default: - return decodeLatin1(chunk), pos, nil + return decodeLatin1(chunk), position, nil } } -func decodeLatin1(b []byte) string { - runes := make([]rune, len(b)) - for i, c := range b { - runes[i] = rune(c) +func decodeLatin1(encoded []byte) string { + runes := make([]rune, len(encoded)) + for i, char := range encoded { + runes[i] = rune(char) } return string(runes) } -func formatOriginURL(ep originEndpoint) string { - url := ep.scheme + "://" + ep.host - if ep.port != 0 { - url += fmt.Sprintf(":%d", ep.port) +func formatOriginURL(endpoint originEndpoint) string { + url := endpoint.scheme + "://" + endpoint.host + if endpoint.port != 0 { + url += fmt.Sprintf(":%d", endpoint.port) } return url } @@ -211,16 +211,16 @@ func readLocalStorageFile(path string) ([]localStorageItem, error) { // mode=ro without immutable lets SQLite replay the copied -wal, so entries Safari has not checkpointed appear. // ORDER BY key, rowid keeps exports stable across runs and SQLite versions. dsn := "file:" + path + "?mode=ro" - db, err := sql.Open("sqlite", dsn) + database, err := sql.Open("sqlite", dsn) if err != nil { return nil, fmt.Errorf("open %s: %w", path, err) } - defer db.Close() - if err := db.Ping(); err != nil { + defer database.Close() + if err := database.Ping(); err != nil { return nil, fmt.Errorf("ping %s: %w", path, err) } - rows, err := db.Query(`SELECT key, value FROM ItemTable ORDER BY key, rowid`) + rows, err := database.Query(`SELECT key, value FROM ItemTable ORDER BY key, rowid`) if err != nil { return nil, fmt.Errorf("query ItemTable: %w", err) } @@ -247,28 +247,28 @@ func readLocalStorageFile(path string) ([]localStorageItem, error) { return items, rows.Err() } -// Values at or above the cap become a size marker to bound the output, as in chromium/extract_storage.go. -func decodeLocalStorageValue(b []byte) string { - if len(b) >= maxLocalStorageValueLength { +// decodeLocalStorageValue turns values at or above the cap into a size marker to bound the output, as Chromium's does. +func decodeLocalStorageValue(encoded []byte) string { + if len(encoded) >= maxLocalStorageValueLength { return fmt.Sprintf( "value is too long, length is %d, supported max length is %d", - len(b), maxLocalStorageValueLength, + len(encoded), maxLocalStorageValueLength, ) } - return decodeUTF16LE(b) + return decodeUTF16LE(encoded) } -// An odd-length value comes back as is, so a stray byte does not drop the row. -func decodeUTF16LE(b []byte) string { - if len(b) == 0 { +// decodeUTF16LE returns an odd-length value as is, so a stray byte does not drop the row. +func decodeUTF16LE(encoded []byte) string { + if len(encoded) == 0 { return "" } - if len(b)%2 != 0 { - return string(b) + if len(encoded)%2 != 0 { + return string(encoded) } - u16 := make([]uint16, len(b)/2) - for i := range u16 { - u16[i] = binary.LittleEndian.Uint16(b[i*2:]) + units := make([]uint16, len(encoded)/2) + for i := range units { + units[i] = binary.LittleEndian.Uint16(encoded[i*2:]) } - return string(utf16.Decode(u16)) + return string(utf16.Decode(units)) } diff --git a/internal/browser/safari/extract_storage_test.go b/internal/browser/safari/extract_storage_test.go index 4d7f0f1..01f271c 100644 --- a/internal/browser/safari/extract_storage_test.go +++ b/internal/browser/safari/extract_storage_test.go @@ -16,13 +16,13 @@ import ( func TestReadOriginBlock_FirstParty(t *testing.T) { data := encodeOriginFile("https://example.com", "https://example.com") - top, pos, err := readOriginBlock(data, 0) + top, position, err := readOriginBlock(data, 0) require.NoError(t, err) assert.Equal(t, "https", top.scheme) assert.Equal(t, "example.com", top.host) assert.Equal(t, uint16(0), top.port, "port 0 ⇒ scheme default") - frame, _, err := readOriginBlock(data, pos) + frame, _, err := readOriginBlock(data, position) require.NoError(t, err) assert.Equal(t, "https://example.com", formatOriginURL(frame)) } @@ -42,10 +42,10 @@ func TestReadOriginBlock_Latin1HighByte(t *testing.T) { 0x04, 0x00, 0x00, 0x00, 0x01, 'c', 'a', 'f', 0xe9, // host "café" (Latin-1) 0x00, // port default } - ep, _, err := readOriginBlock(data, 0) + endpoint, _, err := readOriginBlock(data, 0) require.NoError(t, err) - assert.Equal(t, "http", ep.scheme) - assert.Equal(t, "café", ep.host) + assert.Equal(t, "http", endpoint.scheme) + assert.Equal(t, "café", endpoint.host) } func TestDecodeLatin1(t *testing.T) { @@ -67,10 +67,10 @@ func TestReadOriginFile_FramePreferred(t *testing.T) { func TestReadOriginFile_FallbackToTop(t *testing.T) { // Only the top-frame block is written; the extractor falls back to it. - var buf []byte - buf = appendOriginBlock(buf, "https://example.com") + var data []byte + data = appendOriginBlock(data, "https://example.com") originPath := filepath.Join(t.TempDir(), "origin") - require.NoError(t, os.WriteFile(originPath, buf, 0o644)) + require.NoError(t, os.WriteFile(originPath, data, 0o644)) got, err := readOriginFile(originPath) require.NoError(t, err) @@ -144,8 +144,8 @@ func TestExtractLocalStorage_MultiOrigin(t *testing.T) { require.Len(t, entries, 3) byURL := make(map[string][]string) - for _, e := range entries { - byURL[e.URL] = append(byURL[e.URL], e.Key+"="+e.Value) + for _, entry := range entries { + byURL[entry.URL] = append(byURL[entry.URL], entry.Key+"="+entry.Value) } assert.ElementsMatch(t, []string{"theme=dark", "lang=en"}, byURL["https://github.com"]) assert.ElementsMatch(t, []string{"session=xyz"}, byURL["https://example.com:8443"]) @@ -165,8 +165,8 @@ func TestExtractLocalStorage_CJKAndEmoji(t *testing.T) { require.Len(t, entries, 2) values := make(map[string]string) - for _, e := range entries { - values[e.Key] = e.Value + for _, entry := range entries { + values[entry.Key] = entry.Value } assert.Equal(t, "张三", values["名字"]) assert.Equal(t, "hello 世界 🌍", values["status"]) diff --git a/internal/browser/safari/profiles.go b/internal/browser/safari/profiles.go index 4459887..49ea90e 100644 --- a/internal/browser/safari/profiles.go +++ b/internal/browser/safari/profiles.go @@ -23,10 +23,10 @@ const ( defaultProfileSentinel = "DefaultProfile" ) -// Path-unsafe bytes for filenames/CSV values; Unicode letters (CJK etc.) survive. +// unsafeNameChars are path-unsafe bytes for filenames and CSV values; Unicode letters (CJK etc.) survive. var unsafeNameChars = regexp.MustCompile(`[/\\:*?"<>|\x00-\x1f]+`) -// Canonical 8-4-4-4-12 hex UUID — format check only, no semantic parse. +// uuidPattern only checks the canonical 8-4-4-4-12 hex form; it does not parse the UUID. var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$`) // namedProfiles reads SafariTabs.db (authoritative), with a ReadDir fallback only if the DB itself is unreadable. @@ -38,39 +38,41 @@ func namedProfiles(library string) []browser.Profile { return named } -// A copy is read, never the live file Safari has open; (nil, err) means unreadable, any slice is authoritative. +// readNamedProfilesFromDB reads a copy, never Safari's live file; (nil, err) means unreadable, and any slice is final. func readNamedProfilesFromDB(library string) ([]browser.Profile, error) { - d, err := snapshot.Temp() + snapshotDir, err := snapshot.Temp() if err != nil { return nil, err } defer func() { - if err := d.Close(); err != nil { + if err := snapshotDir.Close(); err != nil { log.Warnf("%v", err) } }() - if err := d.Capture(context.Background(), []snapshot.File{{DirID: discoverDirID, From: library, Rel: safariTabsDBRelPath}}); err != nil { + if err := snapshotDir.Capture(context.Background(), []snapshot.File{{ + UserDataDirID: discoveryUserDataDirID, UserDataDirPath: library, RelativePath: safariTabsDBRelPath, + }}); err != nil { return nil, fmt.Errorf("copy SafariTabs.db: %w", err) } - path, err := d.Snapshot(discoverDirID).Path(safariTabsDBRelPath) + path, err := snapshotDir.Snapshot(discoveryUserDataDirID).Path(safariTabsDBRelPath) if err != nil { return nil, fmt.Errorf("copy SafariTabs.db: %w", err) } // Immutable, as on the live file before: the copied -wal is not replayed, so the profile list stays today's. dsn := "file:" + path + "?mode=ro&immutable=1" - db, err := sql.Open("sqlite", dsn) + database, err := sql.Open("sqlite", dsn) if err != nil { return nil, fmt.Errorf("open SafariTabs.db: %w", err) } - defer db.Close() + defer database.Close() // Ping forces connection; sql.Open is lazy and won't detect a missing file. - if err := db.Ping(); err != nil { + if err := database.Ping(); err != nil { return nil, fmt.Errorf("ping SafariTabs.db: %w", err) } - rows, err := db.Query( + rows, err := database.Query( `SELECT external_uuid, title FROM bookmarks WHERE subtype = ? AND external_uuid != ?`, safariProfileSubtype, defaultProfileSentinel, ) @@ -97,7 +99,7 @@ func readNamedProfilesFromDB(library string) ([]browser.Profile, error) { return out, nil } -// Names are synthesized from UUIDs when SafariTabs.db is missing. +// readNamedProfilesFromDir synthesizes names from UUIDs when SafariTabs.db is missing. func readNamedProfilesFromDir(library string) []browser.Profile { entries, err := os.ReadDir(filepath.Join(library, filepath.FromSlash(namedProfilesDir))) if err != nil { @@ -105,21 +107,21 @@ func readNamedProfilesFromDir(library string) []browser.Profile { } var out []browser.Profile - for _, e := range entries { - if !e.IsDir() || !isCanonicalUUID(e.Name()) { + for _, entry := range entries { + if !entry.IsDir() || !isCanonicalUUID(entry.Name()) { continue } - out = append(out, newNamedProfile(e.Name(), "")) + out = append(out, newNamedProfile(entry.Name(), "")) } return out } -// A named profile's Dir is its own History.db directory, so its UUID travels with it to Extractors. +// newNamedProfile sets Dir to the profile's own History.db directory, so its UUID travels with it to Extractors. func newNamedProfile(upperUUID, title string) browser.Profile { return browser.Profile{Name: resolveProfileName(title, upperUUID), Dir: namedProfilesDir + "/" + upperUUID} } -func isCanonicalUUID(s string) bool { return uuidPattern.MatchString(s) } +func isCanonicalUUID(value string) bool { return uuidPattern.MatchString(value) } func resolveProfileName(title, upperUUID string) string { if name := sanitizeProfileName(title); name != "" { diff --git a/internal/browser/safari/profiles_test.go b/internal/browser/safari/profiles_test.go index 2d3a13d..3b58782 100644 --- a/internal/browser/safari/profiles_test.go +++ b/internal/browser/safari/profiles_test.go @@ -11,9 +11,9 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/browser" ) -func testDef() browser.Def { - p := browser.Platform{UserDataDirs: []string{"Library/Safari"}} - return browser.Def{ID: "safari", Name: "Safari", Base: browser.Safari, Darwin: p, Linux: p, Windows: p} +func testBrowser() browser.Browser { + platform := browser.Platform{UserDataDirs: []string{"Library/Safari"}} + return browser.Browser{Name: "safari", DisplayName: "Safari", Base: browser.Safari, Darwin: platform, Linux: platform, Windows: platform} } func libraryAt(t *testing.T, home string) (container string) { @@ -24,10 +24,10 @@ func libraryAt(t *testing.T, home string) (container string) { func discoverProfiles(t *testing.T, home string) []browser.Profile { t.Helper() - dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: home}) + dirs, err := Discover(testBrowser(), browser.DiscoverOptions{Home: home}) require.NoError(t, err) require.Len(t, dirs, 1) - assert.Equal(t, browser.DirID("safari"), dirs[0].ID) + assert.Equal(t, browser.UserDataDirID("safari"), dirs[0].ID) assert.Equal(t, filepath.Join(home, "Library"), dirs[0].Path) return dirs[0].Profiles } @@ -45,7 +45,7 @@ func TestDiscover_DefaultOnly(t *testing.T) { } func TestDiscover_MissingSafariYieldsNothing(t *testing.T) { - dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: t.TempDir()}) + dirs, err := Discover(testBrowser(), browser.DiscoverOptions{Home: t.TempDir()}) require.NoError(t, err) assert.Empty(t, dirs) } @@ -60,8 +60,8 @@ func TestDiscover_ProfilePathIsTheSafariDir(t *testing.T) { home := t.TempDir() libraryAt(t, home) - opts := browser.DiscoverOptions{Home: home, ProfilePath: filepath.Join(copied, "Library", "SafariCopy")} - dirs, err := Discover(testDef(), opts) + options := browser.DiscoverOptions{Home: home, ProfilePath: filepath.Join(copied, "Library", "SafariCopy")} + dirs, err := Discover(testBrowser(), options) require.NoError(t, err) require.Len(t, dirs, 1) assert.Equal(t, filepath.Join(copied, "Library"), dirs[0].Path) @@ -80,7 +80,7 @@ func TestDiscover_WithNamedProfile(t *testing.T) { assert.Equal(t, []browser.Profile{defaultProfile, named("work", uuid)}, discoverProfiles(t, home)) } -// A '#' in the live path cuts a SQLite URI short, so the titles come through only when discovery opens its copy. +// TestDiscover_ReadsACopyOfSafariTabs puts '#' in the live path, which cuts a SQLite URI: only the copy yields titles. func TestDiscover_ReadsACopyOfSafariTabs(t *testing.T) { const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" home := filepath.Join(t.TempDir(), "user#1") @@ -97,7 +97,7 @@ func TestDiscover_EmptyTitleFallbackToUUID(t *testing.T) { assert.Equal(t, []browser.Profile{defaultProfile, named("profile-abcdef01", uuid)}, discoverProfiles(t, home)) } -// A profile directory SafariTabs.db does not mention stays hidden: a readable DB is authoritative. +// TestDiscover_OrphanUUIDWithoutDBEntry hides a profile dir SafariTabs.db omits, as a readable DB is authoritative. func TestDiscover_OrphanUUIDWithoutDBEntry(t *testing.T) { const dbUUID = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE" const orphanUUID = "11111111-2222-3333-4444-555555555555" @@ -117,7 +117,7 @@ func TestDiscover_EmptyDBIsAuthoritative(t *testing.T) { assert.Equal(t, []browser.Profile{defaultProfile}, discoverProfiles(t, home)) } -// Without SafariTabs.db the Profiles dir is listed; dirs without data stay, since a file's presence is Plan's question. +// TestDiscover_MissingDBFallsBackToReadDir lists the Profiles dir, keeping dirs without data: presence is Plan's call. func TestDiscover_MissingDBFallsBackToReadDir(t *testing.T) { const uuid = "11111111-2222-3333-4444-555555555555" const empty = "4E2D8DD0-A7D2-4684-939A-898B7675C700" @@ -161,9 +161,9 @@ func TestResolveProfileName(t *testing.T) { {"with/slash", "AAAAAAAA-0000-0000-0000-000000000000", "with_slash"}, {"中文", "AAAAAAAA-0000-0000-0000-000000000000", "中文"}, } - for _, tt := range tests { - t.Run(tt.title, func(t *testing.T) { - assert.Equal(t, tt.want, resolveProfileName(tt.title, tt.uuid)) + for _, testCase := range tests { + t.Run(testCase.title, func(t *testing.T) { + assert.Equal(t, testCase.want, resolveProfileName(testCase.title, testCase.uuid)) }) } } diff --git a/internal/browser/safari/safari.go b/internal/browser/safari/safari.go index e91bce2..a5abdda 100644 --- a/internal/browser/safari/safari.go +++ b/internal/browser/safari/safari.go @@ -23,8 +23,8 @@ const ( containerDir = "Containers/com.apple.Safari/Data/Library" namedProfilesDir = containerDir + "/Safari/Profiles" - defaultProfileName = "default" - discoverDirID = "safari" + defaultProfileName = "default" + discoveryUserDataDirID = "safari" ) var errNoKeychain = errors.New("no login keychain") @@ -34,11 +34,11 @@ type LoginKeychain interface { InternetPasswords(ctx context.Context) ([]keychainbreaker.InternetPassword, error) } -// The default profile's Dir is the Safari directory; -p names another one, whose parent stands in for ~/Library. -func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) { +// Discover makes the Safari directory the default profile's Dir; -p names another, whose parent replaces ~/Library. +func Discover(safariBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) { var errs []error var dirs []browser.UserDataDir - for i, safariPath := range safariPaths(def, opts) { + for i, safariPath := range safariPaths(safariBrowser, options) { if _, err := os.Stat(safariPath); err != nil { if !errors.Is(err, fs.ErrNotExist) { errs = append(errs, fmt.Errorf("%s: %w", safariPath, err)) @@ -48,90 +48,85 @@ func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserData library := filepath.Dir(safariPath) profiles := append([]browser.Profile{{Name: defaultProfileName, Dir: filepath.Base(safariPath)}}, namedProfiles(library)...) disambiguateNames(profiles) - dirs = append(dirs, browser.UserDataDir{ID: dirID(def, i), Def: def, Path: library, Profiles: profiles}) + dirs = append(dirs, browser.UserDataDir{ID: safariBrowser.UserDataDirID(i), Browser: safariBrowser, Path: library, Profiles: profiles}) } return dirs, errors.Join(errs...) } -func safariPaths(def browser.Def, opts browser.DiscoverOptions) []string { - if opts.ProfilePath != "" { - return []string{filepath.Clean(opts.ProfilePath)} +func safariPaths(safariBrowser browser.Browser, options browser.DiscoverOptions) []string { + if options.ProfilePath != "" { + return []string{filepath.Clean(options.ProfilePath)} } - paths := make([]string, 0, len(def.Platform().UserDataDirs)) - for _, rel := range def.Platform().UserDataDirs { - paths = append(paths, filepath.Join(opts.Home, filepath.FromSlash(rel))) + paths := make([]string, 0, len(safariBrowser.Platform().UserDataDirs)) + for _, relativePath := range safariBrowser.Platform().UserDataDirs { + paths = append(paths, filepath.Join(options.Home, filepath.FromSlash(relativePath))) } return paths } -func dirID(def browser.Def, i int) browser.DirID { - if i == 0 { - return browser.DirID(def.ID) - } - return browser.DirID(fmt.Sprintf("%s-%d", def.ID, i+1)) -} - -// A named profile's files sit under two directories named for its UUID, so its sources are built from Profile.Dir. +// Extractors builds a named profile's file specs from Profile.Dir; 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, p browser.Profile, kc LoginKeychain) browser.Extractors { - library := func(rel string) string { return fromLibrary(p, rel) } - uuid, named := profileUUID(p) +func Extractors(dir browser.UserDataDir, profile browser.Profile, loginKeychain LoginKeychain) browser.Extractors { + library := func(relativePath string) string { return fromLibrary(profile, relativePath) } + uuid, named := profileUUID(profile) if !named { return browser.Extractors{ - category.Password: {Extract: passwordsFrom(kc)}, - category.History: plain(file("History.db"), extractHistories), - category.Cookie: plain(file( + category.Password: {Extract: passwordsFrom(loginKeychain)}, + category.History: newPlainExtractor(newFileSpec("History.db"), extractHistories), + category.Cookie: newPlainExtractor(newFileSpec( library(containerDir+"/Cookies/Cookies.binarycookies"), library("Cookies/Cookies.binarycookies"), ), extractCookies), - category.Bookmark: plain(file("Bookmarks.plist"), extractBookmarks), - category.Download: plain(file("Downloads.plist"), downloadsOf(defaultProfileSentinel)), - category.LocalStorage: plain(directory(library(containerDir+"/WebKit/WebsiteData/Default")), extractLocalStorage), + category.Bookmark: newPlainExtractor(newFileSpec("Bookmarks.plist"), extractBookmarks), + category.Download: newPlainExtractor(newFileSpec("Downloads.plist"), downloadsOf(defaultProfileSentinel)), + category.LocalStorage: newPlainExtractor(newDirectorySpec(library(containerDir+"/WebKit/WebsiteData/Default")), extractLocalStorage), category.Extension: extensionsFrom(library), } } store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(uuid) return browser.Extractors{ - category.History: plain(file("History.db"), extractHistories), - category.Cookie: plain(file(library(store+"/Cookies/Cookies.binarycookies")), extractCookies), - category.Download: plain(file(library(safariDir(dir)+"/Downloads.plist")), downloadsOf(uuid)), - category.LocalStorage: plain(directory(library(store+"/Origins")), extractLocalStorage), + category.History: newPlainExtractor(newFileSpec("History.db"), extractHistories), + category.Cookie: newPlainExtractor(newFileSpec(library(store+"/Cookies/Cookies.binarycookies")), extractCookies), + category.Download: newPlainExtractor(newFileSpec(library(safariDir(dir)+"/Downloads.plist")), downloadsOf(uuid)), + category.LocalStorage: newPlainExtractor(newDirectorySpec(library(store+"/Origins")), extractLocalStorage), } } -func profileUUID(p browser.Profile) (string, bool) { - if path.Dir(p.Dir) != namedProfilesDir { +func profileUUID(profile browser.Profile) (string, bool) { + if path.Dir(profile.Dir) != namedProfilesDir { return "", false } - return path.Base(p.Dir), true + return path.Base(profile.Dir), true } // safariDir is the default profile's Dir, which holds the Downloads.plist every profile reads its entries from. func safariDir(dir browser.UserDataDir) string { - for _, p := range dir.Profiles { - if _, named := profileUUID(p); !named { - return p.Dir + for _, profile := range dir.Profiles { + if _, named := profileUUID(profile); !named { + return profile.Dir } } return "Safari" } -// fromLibrary turns a path under ~/Library into one relative to p.Dir, because a profile's sources are joined with it. -func fromLibrary(p browser.Profile, rel string) string { - if p.Dir == "" { - return rel +// fromLibrary turns a path under ~/Library into one relative to profile.Dir, which file specs are joined with. +func fromLibrary(profile browser.Profile, relativePath string) string { + if profile.Dir == "" { + return relativePath } - return strings.Repeat("../", strings.Count(p.Dir, "/")+1) + rel + return strings.Repeat("../", strings.Count(profile.Dir, "/")+1) + relativePath } -func file(paths ...string) browser.Source { return browser.Source{Paths: paths} } -func directory(rel string) browser.Source { return browser.Source{Paths: []string{rel}, IsDir: true} } +func newFileSpec(paths ...string) browser.FileSpec { return browser.FileSpec{Paths: paths} } +func newDirectorySpec(relativePath string) browser.FileSpec { + return browser.FileSpec{Paths: []string{relativePath}, IsDir: true} +} -func plain(src browser.Source, parse func(string, browser.Collector) error) browser.Extractor { +func newPlainExtractor(fileSpec browser.FileSpec, parse func(string, browser.Collector) error) browser.Extractor { return browser.Extractor{ - Sources: []browser.Source{src}, - Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { - captured, err := ps.Path(src) + FileSpecs: []browser.FileSpec{fileSpec}, + Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { + captured, err := profileSnapshot.Path(fileSpec) if err != nil { return err } @@ -140,13 +135,13 @@ func plain(src browser.Source, parse func(string, browser.Collector) error) brow } } -// It reads no file, so it always runs; without a usable password the keychain stays locked and yields metadata only. -func passwordsFrom(kc LoginKeychain) func(context.Context, browser.ProfileSnapshot, browser.Collector) error { +// passwordsFrom reads no file, so it always runs; without a usable password the locked keychain yields metadata only. +func passwordsFrom(loginKeychain LoginKeychain) func(context.Context, browser.ProfileSnapshot, browser.Collector) error { return func(ctx context.Context, _ browser.ProfileSnapshot, out browser.Collector) error { - if kc == nil { + if loginKeychain == nil { return errNoKeychain } - return extractPasswords(ctx, kc, out) + return extractPasswords(ctx, loginKeychain, out) } } @@ -155,16 +150,16 @@ func downloadsOf(owner string) func(string, browser.Collector) error { } func extensionsFrom(library func(string) string) browser.Extractor { - sources := []browser.Source{ + fileSpecs := []browser.FileSpec{ {Paths: []string{library(containerDir + "/Safari/AppExtensions/Extensions.plist")}, Optional: true}, {Paths: []string{library(containerDir + "/Safari/WebExtensions/Extensions.plist")}, Optional: true}, } return browser.Extractor{ - Sources: sources, - Extract: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error { + FileSpecs: fileSpecs, + Extract: func(_ context.Context, profileSnapshot browser.ProfileSnapshot, out browser.Collector) error { var paths []string - for _, src := range sources { - captured, err := ps.Path(src) + for _, fileSpec := range fileSpecs { + captured, err := profileSnapshot.Path(fileSpec) if errors.Is(err, fs.ErrNotExist) { continue } @@ -178,7 +173,7 @@ func extensionsFrom(library func(string) string) browser.Extractor { } } -// emit hands rows to out by pointer, because out stamps each record in place. +// emit hands rows to out by pointer, because out sets each record's Browser and Profile in place. func emit[T any, P interface { *T record.Record diff --git a/internal/browser/safari/safari_test.go b/internal/browser/safari/safari_test.go index e53b7c4..8da14c6 100644 --- a/internal/browser/safari/safari_test.go +++ b/internal/browser/safari/safari_test.go @@ -25,23 +25,23 @@ const workUUID = "5604E6F5-02ED-4E40-8249-63DE7BC986C8" var ( workProfile = named("work", workUUID) - libraryDir = browser.UserDataDir{Def: testDef(), Profiles: []browser.Profile{defaultProfile, workProfile}} + libraryDir = browser.UserDataDir{Browser: testBrowser(), Profiles: []browser.Profile{defaultProfile, workProfile}} ) -func sourcePaths(p browser.Profile, ex browser.Extractors) map[category.Category][]string { - got := make(map[category.Category][]string, len(ex)) - for c, e := range ex { - for _, src := range e.Sources { - for _, rel := range src.Paths { - got[c] = append(got[c], path.Join(p.Dir, rel)) +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 _, fileSpec := range extractor.FileSpecs { + for _, relativePath := range fileSpec.Paths { + got[dataCategory] = append(got[dataCategory], path.Join(profile.Dir, relativePath)) } } } return got } -func TestExtractors_DefaultProfileSources(t *testing.T) { - ex := Extractors(libraryDir, defaultProfile, nil) +func TestExtractors_DefaultProfileFileSpecs(t *testing.T) { + extractors := Extractors(libraryDir, defaultProfile, nil) assert.Equal(t, map[category.Category][]string{ category.History: {"Safari/History.db"}, category.Cookie: {containerDir + "/Cookies/Cookies.binarycookies", "Cookies/Cookies.binarycookies"}, @@ -54,12 +54,12 @@ func TestExtractors_DefaultProfileSources(t *testing.T) { containerDir + "/Safari/AppExtensions/Extensions.plist", containerDir + "/Safari/WebExtensions/Extensions.plist", }, - }, sourcePaths(defaultProfile, ex)) - require.Contains(t, ex, category.Password) - assert.Empty(t, ex[category.Password].Sources, "passwords come from the keychain, not a file") + }, sourcePaths(defaultProfile, extractors)) + require.Contains(t, extractors, category.Password) + assert.Empty(t, extractors[category.Password].FileSpecs, "passwords come from the keychain, not a file") } -func TestExtractors_NamedProfileSources(t *testing.T) { +func TestExtractors_NamedProfileFileSpecs(t *testing.T) { store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(workUUID) assert.Equal(t, map[category.Category][]string{ category.History: {namedProfilesDir + "/" + workUUID + "/History.db"}, @@ -72,50 +72,50 @@ func TestExtractors_NamedProfileSources(t *testing.T) { func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot { t.Helper() root := t.TempDir() - for rel, src := range files { - data, err := os.ReadFile(src) + for relativePath, fixturePath := range files { + data, err := os.ReadFile(fixturePath) require.NoError(t, err) - dst := filepath.Join(root, "safari", filepath.FromSlash(rel)) - require.NoError(t, os.MkdirAll(filepath.Dir(dst), 0o755)) - require.NoError(t, os.WriteFile(dst, data, 0o644)) + target := filepath.Join(root, "safari", filepath.FromSlash(relativePath)) + require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755)) + require.NoError(t, os.WriteFile(target, data, 0o644)) } return snapshot.Open(root).Snapshot("safari") } -func writeTestPlist(t *testing.T, v any) string { +func writeTestPlist(t *testing.T, value any) string { t.Helper() - p := filepath.Join(t.TempDir(), "fixture.plist") - f, err := os.Create(p) + plistPath := filepath.Join(t.TempDir(), "fixture.plist") + file, err := os.Create(plistPath) require.NoError(t, err) - defer f.Close() - require.NoError(t, plist.NewBinaryEncoder(f).Encode(v)) - return p + defer file.Close() + require.NoError(t, plist.NewBinaryEncoder(file).Encode(value)) + return plistPath } -func extract(t *testing.T, snap snapshot.Snapshot, p browser.Profile, kc LoginKeychain, c category.Category) (*testCollector, error) { +func extract(t *testing.T, dirSnapshot snapshot.Snapshot, profile browser.Profile, loginKeychain LoginKeychain, dataCategory category.Category) (*testCollector, error) { t.Helper() - ex, ok := Extractors(libraryDir, p, kc)[c] - require.Truef(t, ok, "no %s extractor for %s", c, p.Name) + extractor, ok := Extractors(libraryDir, profile, loginKeychain)[dataCategory] + require.Truef(t, ok, "no %s extractor for %s", dataCategory, profile.Name) var out testCollector - err := ex.Extract(context.Background(), browser.NewProfileSnapshot(snap, p, nil), &out) + err := extractor.Extract(context.Background(), browser.NewProfileSnapshot(dirSnapshot, profile, nil), &out) return &out, err } -// Each profile keeps its own entries of the shared Downloads.plist; an entry without an owner is the default's. +// TestExtractors_DownloadsBelongToTheirProfile splits the shared Downloads.plist; an unowned entry is the default's. func TestExtractors_DownloadsBelongToTheirProfile(t *testing.T) { - snap := snapshotOf(t, map[string]string{"Safari/Downloads.plist": writeTestPlist(t, map[string]any{ + dirSnapshot := snapshotOf(t, map[string]string{"Safari/Downloads.plist": writeTestPlist(t, map[string]any{ "DownloadHistory": []any{ map[string]any{"DownloadEntryURL": "https://a.test/home", "DownloadEntryProfileUUIDStringKey": "DefaultProfile"}, map[string]any{"DownloadEntryURL": "https://a.test/work", "DownloadEntryProfileUUIDStringKey": workUUID}, map[string]any{"DownloadEntryURL": "https://a.test/legacy"}, }, })}) - urls := func(p browser.Profile) []string { - out, err := extract(t, snap, p, nil, category.Download) + urls := func(profile browser.Profile) []string { + out, err := extract(t, dirSnapshot, profile, nil, category.Download) require.NoError(t, err) var got []string - for _, d := range collected[record.Download](t, out) { - got = append(got, d.URL) + for _, download := range collected[record.Download](t, out) { + got = append(got, download.URL) } return got } @@ -123,14 +123,14 @@ func TestExtractors_DownloadsBelongToTheirProfile(t *testing.T) { assert.Equal(t, []string{"https://a.test/work"}, urls(workProfile)) } -// The extension plists are read from the snapshot; a missing one is skipped. +// TestExtractors_ExtensionsFromTheSnapshot reads the extension plists from the snapshot and skips a missing one. func TestExtractors_ExtensionsFromTheSnapshot(t *testing.T) { - snap := snapshotOf(t, map[string]string{ + dirSnapshot := snapshotOf(t, map[string]string{ containerDir + "/Safari/WebExtensions/Extensions.plist": writeTestPlist(t, map[string]any{ "com.example.Blocker.Extension (ABCDE12345)": map[string]any{"Enabled": false}, }), }) - out, err := extract(t, snap, defaultProfile, nil, category.Extension) + out, err := extract(t, dirSnapshot, defaultProfile, nil, category.Extension) require.NoError(t, err) got := collected[record.Extension](t, out) require.Len(t, got, 1) @@ -151,19 +151,19 @@ func (k *fakeKeychain) InternetPasswords(context.Context) ([]keychainbreaker.Int func TestExtractors_PasswordsFromTheKeychain(t *testing.T) { created := time.Date(2024, 3, 1, 9, 0, 0, 0, time.FixedZone("CET", 3600)) - kc := &fakeKeychain{passwords: []keychainbreaker.InternetPassword{ + loginKeychain := &fakeKeychain{passwords: []keychainbreaker.InternetPassword{ {Protocol: "htps", Server: "github.com", Port: 443, Account: "alice", PlainPassword: "s3cret", Created: created}, {Protocol: "htps", Server: "locked.test", Account: "bob"}, {Protocol: "htps", Server: "", Account: "nobody"}, {Protocol: "htps", Server: "anonymous.test", Account: ""}, }} - out, err := extract(t, snapshotOf(t, nil), defaultProfile, kc, category.Password) + out, err := extract(t, snapshotOf(t, nil), defaultProfile, loginKeychain, category.Password) require.NoError(t, err) assert.Equal(t, []record.Login{ {URL: "https://github.com", Username: "alice", Password: "s3cret", CreatedAt: created.UTC(), Store: record.StoreLocal}, {URL: "https://locked.test", Username: "bob", Store: record.StoreLocal}, }, collected[record.Login](t, out)) - assert.Equal(t, 1, kc.calls) + assert.Equal(t, 1, loginKeychain.calls) } func TestExtractors_PasswordsWithoutAKeychain(t *testing.T) { @@ -175,10 +175,10 @@ func TestExtractors_PasswordsWithoutAKeychain(t *testing.T) { require.ErrorIs(t, err, broken) } -// The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile reads them. -func TestExtractors_NamedProfileSkipsUserWideSources(t *testing.T) { - ex := Extractors(libraryDir, workProfile, &fakeKeychain{}) - for _, c := range []category.Category{category.Password, category.Bookmark, category.Extension} { - assert.NotContains(t, ex, c) +// TestExtractors_NamedProfileSkipsUserWideFileSpecs leaves the keychain and the untagged plists to the default profile. +func TestExtractors_NamedProfileSkipsUserWideFileSpecs(t *testing.T) { + extractors := Extractors(libraryDir, workProfile, &fakeKeychain{}) + for _, dataCategory := range []category.Category{category.Password, category.Bookmark, category.Extension} { + assert.NotContains(t, extractors, dataCategory) } } diff --git a/internal/browser/safari/testutil_test.go b/internal/browser/safari/testutil_test.go index 2c23745..3114b9b 100644 --- a/internal/browser/safari/testutil_test.go +++ b/internal/browser/safari/testutil_test.go @@ -66,16 +66,16 @@ func insertHistoryVisit(id, historyItem int, visitTime float64, title string) st func createTestDB(t *testing.T, name string, schemas []string, inserts ...string) string { //nolint:unparam // name will vary when future data types are added t.Helper() path := filepath.Join(t.TempDir(), name) - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) require.NoError(t, err) - defer db.Close() + defer database.Close() for _, schema := range schemas { - _, err = db.Exec(schema) + _, err = database.Exec(schema) require.NoError(t, err) } - for _, stmt := range inserts { - _, err = db.Exec(stmt) + for _, statement := range inserts { + _, err = database.Exec(statement) require.NoError(t, err) } return path @@ -86,16 +86,16 @@ type tabRow struct { title string } -// Every row gets subtype=2, the profile record the production query selects. +// writeSafariTabsDB gives every row subtype=2, the profile record the production query selects. func writeSafariTabsDB(t *testing.T, path string, rows []tabRow) { t.Helper() require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) require.NoError(t, err) - defer db.Close() + defer database.Close() - _, err = db.Exec(`CREATE TABLE bookmarks ( + _, err = database.Exec(`CREATE TABLE bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, external_uuid TEXT, title TEXT, @@ -103,18 +103,18 @@ func writeSafariTabsDB(t *testing.T, path string, rows []tabRow) { )`) require.NoError(t, err) - for _, r := range rows { - _, err = db.Exec(`INSERT INTO bookmarks (external_uuid, title, subtype) VALUES (?, ?, 2)`, r.uuid, r.title) + for _, row := range rows { + _, err = database.Exec(`INSERT INTO bookmarks (external_uuid, title, subtype) VALUES (?, ?, 2)`, row.uuid, row.title) require.NoError(t, err) } } -// Value is written as UTF-16 LE, as WebKit stores it. +// testLocalStorageItem holds a Value written as UTF-16 LE, as WebKit stores it. type testLocalStorageItem struct { Key, Value string } -// Every origin is written first-party, with top == frame. +// buildTestLocalStorageDir writes every origin first-party, with top == frame. func buildTestLocalStorageDir(t *testing.T, origins map[string][]testLocalStorageItem) string { t.Helper() root := filepath.Join(t.TempDir(), "Origins") @@ -141,97 +141,97 @@ func writeTestOriginStore(t *testing.T, root, topHash, frameHash, topOrigin, fra )) dbPath := filepath.Join(frameDir, webkitLocalStorageSubdir, webkitLocalStorageDB) - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) require.NoError(t, err) - _, err = db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`) + _, err = database.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`) require.NoError(t, err) for _, item := range items { - _, err = db.Exec( + _, err = database.Exec( `INSERT INTO ItemTable (key, value) VALUES (?, ?)`, item.Key, encodeUTF16LE(item.Value), ) require.NoError(t, err) } - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) } -// WebKit's SecurityOrigin layout: per block a scheme record, a host record, and a port marker; top, then frame. +// encodeOriginFile follows WebKit's SecurityOrigin layout: per block a scheme, a host, and a port; top, then frame. func encodeOriginFile(topOrigin, frameOrigin string) []byte { - var buf []byte - buf = appendOriginBlock(buf, topOrigin) - buf = appendOriginBlock(buf, frameOrigin) - return buf + var encoded []byte + encoded = appendOriginBlock(encoded, topOrigin) + encoded = appendOriginBlock(encoded, frameOrigin) + return encoded } -func appendOriginBlock(buf []byte, originURL string) []byte { +func appendOriginBlock(encoded []byte, originURL string) []byte { scheme, host, port := splitTestOriginURL(originURL) - buf = appendOriginRecord(buf, scheme) - buf = appendOriginRecord(buf, host) + encoded = appendOriginRecord(encoded, scheme) + encoded = appendOriginRecord(encoded, host) if port == 0 { - buf = append(buf, originPortDefaultMarker) - return buf + encoded = append(encoded, originPortDefaultMarker) + return encoded } - buf = append(buf, originPortExplicitFlag) + encoded = append(encoded, originPortExplicitFlag) portBytes := make([]byte, 2) binary.LittleEndian.PutUint16(portBytes, port) - return append(buf, portBytes...) + return append(encoded, portBytes...) } -func appendOriginRecord(buf []byte, s string) []byte { +func appendOriginRecord(encoded []byte, text string) []byte { lenBytes := make([]byte, 4) - binary.LittleEndian.PutUint32(lenBytes, uint32(len(s))) - buf = append(buf, lenBytes...) - buf = append(buf, originEncASCII) - return append(buf, []byte(s)...) + binary.LittleEndian.PutUint32(lenBytes, uint32(len(text))) + encoded = append(encoded, lenBytes...) + encoded = append(encoded, originEncASCII) + return append(encoded, []byte(text)...) } -// Port 0 means the URL had no explicit port. -func splitTestOriginURL(u string) (scheme, host string, port uint16) { - idx := strings.Index(u, "://") - if idx < 0 { - return "", u, 0 +// splitTestOriginURL returns port 0 when the URL had no explicit port. +func splitTestOriginURL(originURL string) (scheme, host string, port uint16) { + index := strings.Index(originURL, "://") + if index < 0 { + return "", originURL, 0 } - scheme = u[:idx] - rest := u[idx+3:] + scheme = originURL[:index] + rest := originURL[index+3:] if colon := strings.LastIndex(rest, ":"); colon >= 0 { - if p, err := strconv.ParseUint(rest[colon+1:], 10, 16); err == nil { - return scheme, rest[:colon], uint16(p) + if parsedPort, err := strconv.ParseUint(rest[colon+1:], 10, 16); err == nil { + return scheme, rest[:colon], uint16(parsedPort) } } return scheme, rest, 0 } -// addNullKey inserts a NULL-key row first, to exercise the reader's skip of NULL keys. +// writeLocalStorageDB inserts a NULL-key row first when addNullKey is set, to exercise the reader's skip of NULL keys. func writeLocalStorageDB(t *testing.T, path string, items []testLocalStorageItem, addNullKey bool) { t.Helper() - db, err := sql.Open("sqlite", path) + database, err := sql.Open("sqlite", path) require.NoError(t, err) - _, err = db.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`) + _, err = database.Exec(`CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB NOT NULL ON CONFLICT FAIL)`) require.NoError(t, err) if addNullKey { - _, err = db.Exec( + _, err = database.Exec( `INSERT INTO ItemTable (key, value) VALUES (NULL, ?)`, encodeUTF16LE("null-key-sentinel"), ) require.NoError(t, err) } for _, item := range items { - _, err = db.Exec( + _, err = database.Exec( `INSERT INTO ItemTable (key, value) VALUES (?, ?)`, item.Key, encodeUTF16LE(item.Value), ) require.NoError(t, err) } - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) } -func encodeUTF16LE(s string) []byte { - u16 := utf16.Encode([]rune(s)) - buf := make([]byte, 2*len(u16)) - for i, r := range u16 { - binary.LittleEndian.PutUint16(buf[i*2:], r) +func encodeUTF16LE(text string) []byte { + units := utf16.Encode([]rune(text)) + encoded := make([]byte, 2*len(units)) + for i, unit := range units { + binary.LittleEndian.PutUint16(encoded[i*2:], unit) } - return buf + return encoded } func mkFile(t *testing.T, parts ...string) { @@ -246,16 +246,16 @@ type testCollector struct { fails []error } -func (c *testCollector) Add(r record.Record) { c.records = append(c.records, r) } -func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) } +func (c *testCollector) Add(row record.Record) { c.records = append(c.records, row) } +func (c *testCollector) Fail(err error) { c.fails = append(c.fails, err) } -func collected[T any](t *testing.T, c *testCollector) []T { +func collected[T any](t *testing.T, collector *testCollector) []T { t.Helper() - got := make([]T, 0, len(c.records)) - for _, r := range c.records { - v, ok := any(r).(*T) - require.Truef(t, ok, "collected a %T, want *%T", r, *new(T)) - got = append(got, *v) + got := make([]T, 0, len(collector.records)) + for _, row := range collector.records { + value, ok := any(row).(*T) + require.Truef(t, ok, "collected a %T, want *%T", row, *new(T)) + got = append(got, *value) } return got } diff --git a/internal/browser/table.go b/internal/browser/table.go index 504e28aa..00c90bf 100644 --- a/internal/browser/table.go +++ b/internal/browser/table.go @@ -2,10 +2,10 @@ package browser import "github.com/moond4rk/hackbrowserdata/internal/masterkey" -// defs is in discovery order, which is also the order records reach the output files. -var defs = []Def{ +// browsers is in discovery order, which is also the order records reach the output files. +var browsers = []Browser{ { - ID: "chrome", Name: "Chrome", Base: Chromium, + Name: "chrome", DisplayName: "Chrome", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Google/Chrome"}, KeychainLabel: "Chrome"}, Linux: Platform{UserDataDirs: []string{".config/google-chrome"}, KeychainLabel: "Chrome Safe Storage"}, Windows: Platform{ @@ -20,7 +20,7 @@ var defs = []Def{ }, }, { - ID: "edge", Name: "Microsoft Edge", Base: Chromium, + Name: "edge", DisplayName: "Microsoft Edge", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Microsoft Edge"}, KeychainLabel: "Microsoft Edge"}, Linux: Platform{UserDataDirs: []string{".config/microsoft-edge"}, KeychainLabel: "Chromium Safe Storage"}, Windows: Platform{ @@ -34,13 +34,13 @@ var defs = []Def{ }, }, { - ID: "chromium", Name: "Chromium", Base: Chromium, + Name: "chromium", DisplayName: "Chromium", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Chromium"}, KeychainLabel: "Chromium"}, Linux: Platform{UserDataDirs: []string{".config/chromium"}, KeychainLabel: "Chromium Safe Storage"}, Windows: Platform{UserDataDirs: []string{"AppData/Local/Chromium/User Data"}}, }, { - ID: "chrome-beta", Name: "Chrome Beta", Base: Chromium, + Name: "chrome-beta", DisplayName: "Chrome Beta", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Google/Chrome Beta"}, KeychainLabel: "Chrome"}, Linux: Platform{UserDataDirs: []string{".config/google-chrome-beta"}, KeychainLabel: "Chrome Safe Storage"}, Windows: Platform{ @@ -55,28 +55,28 @@ var defs = []Def{ }, }, { - ID: "opera", Name: "Opera", Base: Chromium, + Name: "opera", DisplayName: "Opera", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/com.operasoftware.Opera"}, KeychainLabel: "Opera"}, Linux: Platform{UserDataDirs: []string{".config/opera"}, KeychainLabel: "Chromium Safe Storage"}, Windows: Platform{UserDataDirs: []string{"AppData/Roaming/Opera Software/Opera Stable"}}, }, { - ID: "opera-gx", Name: "OperaGX", Base: Chromium, + Name: "opera-gx", DisplayName: "OperaGX", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/com.operasoftware.OperaGX"}, KeychainLabel: "Opera"}, Windows: Platform{UserDataDirs: []string{"AppData/Roaming/Opera Software/Opera GX Stable"}}, }, { - ID: "vought", Name: "Browser from Vought", Base: Chromium, + Name: "vought", DisplayName: "Browser from Vought", Base: Chromium, Windows: Platform{UserDataDirs: []string{"AppData/Roaming/Browser from Vought"}}, }, { - ID: "vivaldi", Name: "Vivaldi", Base: Chromium, + Name: "vivaldi", DisplayName: "Vivaldi", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Vivaldi"}, KeychainLabel: "Vivaldi"}, Linux: Platform{UserDataDirs: []string{".config/vivaldi"}, KeychainLabel: "Chrome Safe Storage"}, Windows: Platform{UserDataDirs: []string{"AppData/Local/Vivaldi/User Data"}}, }, { - ID: "coccoc", Name: "CocCoc", Base: Chromium, + Name: "coccoc", DisplayName: "CocCoc", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Coccoc"}, KeychainLabel: "CocCoc"}, Windows: Platform{ UserDataDirs: []string{"AppData/Local/CocCoc/Browser/User Data"}, @@ -90,7 +90,7 @@ var defs = []Def{ }, }, { - ID: "brave", Name: "Brave", Base: Chromium, + Name: "brave", DisplayName: "Brave", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/BraveSoftware/Brave-Browser"}, KeychainLabel: "Brave"}, Linux: Platform{UserDataDirs: []string{".config/BraveSoftware/Brave-Browser"}, KeychainLabel: "Brave Safe Storage"}, Windows: Platform{ @@ -105,47 +105,47 @@ var defs = []Def{ }, }, { - ID: "yandex", Name: "Yandex", Base: Chromium, + Name: "yandex", DisplayName: "Yandex", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Yandex/YandexBrowser"}, KeychainLabel: "Yandex"}, Windows: Platform{UserDataDirs: []string{"AppData/Local/Yandex/YandexBrowser/User Data"}}, }, { - ID: "360x", Name: "360 Speed X", Base: Chromium, + Name: "360x", DisplayName: "360 Speed X", Base: Chromium, Windows: Platform{UserDataDirs: []string{"AppData/Local/360ChromeX/Chrome/User Data"}}, }, { - ID: "360", Name: "360 Speed", Base: Chromium, + Name: "360", DisplayName: "360 Speed", Base: Chromium, Windows: Platform{UserDataDirs: []string{"AppData/Local/360chrome/Chrome/User Data"}}, }, { - ID: "qq", Name: "QQ", Base: Chromium, + Name: "qq", DisplayName: "QQ", Base: Chromium, Windows: Platform{UserDataDirs: []string{"AppData/Local/Tencent/QQBrowser/User Data"}}, }, { - ID: "dc", Name: "DC", Base: Chromium, + Name: "dc", DisplayName: "DC", Base: Chromium, Windows: Platform{UserDataDirs: []string{"AppData/Local/DCBrowser/User Data"}}, }, { - ID: "sogou", Name: "Sogou", Base: Chromium, + Name: "sogou", DisplayName: "Sogou", Base: Chromium, Windows: Platform{UserDataDirs: []string{"AppData/Local/Sogou/SogouExplorer/User Data"}}, }, { - ID: "arc", Name: "Arc", Base: Chromium, + Name: "arc", DisplayName: "Arc", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Arc/User Data"}, KeychainLabel: "Arc"}, Windows: Platform{UserDataDirs: []string{"AppData/Local/Packages/TheBrowserCompany.Arc_*/LocalCache/Local/Arc/User Data"}}, }, { - ID: "duckduckgo", Name: "DuckDuckGo", Base: Chromium, + Name: "duckduckgo", DisplayName: "DuckDuckGo", Base: Chromium, Windows: Platform{UserDataDirs: []string{"AppData/Local/Packages/DuckDuckGo.DesktopBrowser_*/LocalState/EBWebView"}}, }, { - ID: "firefox", Name: "Firefox", Base: Firefox, + Name: "firefox", DisplayName: "Firefox", Base: Firefox, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Firefox/Profiles"}}, Linux: Platform{UserDataDirs: []string{".mozilla/firefox"}}, Windows: Platform{UserDataDirs: []string{"AppData/Roaming/Mozilla/Firefox/Profiles"}}, }, { - ID: "safari", Name: "Safari", Base: Safari, + Name: "safari", DisplayName: "Safari", Base: Safari, Darwin: Platform{UserDataDirs: []string{"Library/Safari"}}, }, } diff --git a/internal/browser/userdatadir.go b/internal/browser/userdatadir.go index a2f8cf6..3101915 100644 --- a/internal/browser/userdatadir.go +++ b/internal/browser/userdatadir.go @@ -6,13 +6,13 @@ type DiscoverOptions struct { ProfilePath string // the -p value; "" when not given } -// DirID is Def.ID, then "-2", "-3"... in Path order; its own type keeps it apart from a Def.ID, which it often equals. -type DirID string +// UserDataDirID is Browser.Name, then "-2", "-3"... in Path order; its own type keeps it apart from that name. +type UserDataDirID string // UserDataDir is one browser data directory found on this machine; ID also names its snapshot and archive directory. type UserDataDir struct { - ID DirID - Def Def + ID UserDataDirID + Browser Browser Path string Profiles []Profile } diff --git a/internal/category/category.go b/internal/category/category.go index 2620283..48f46e9 100644 --- a/internal/category/category.go +++ b/internal/category/category.go @@ -2,7 +2,7 @@ package category import "fmt" -// Numbering starts at 1, so the zero Category means "none". +// Category numbering starts at 1, so the zero Category means "none". type Category int const ( @@ -17,7 +17,7 @@ const ( SessionStorage ) -// String's values are the -c values and the output file names, so they cannot change. +// String gives the -c values and the output file names, so its values cannot change. func (c Category) String() string { switch c { case Password: @@ -50,17 +50,17 @@ func All() []Category { func Names() []string { all := All() names := make([]string, len(all)) - for i, c := range all { - names[i] = c.String() + for i, dataCategory := range all { + names[i] = dataCategory.String() } return names } -func Parse(s string) (Category, error) { - for _, c := range All() { - if c.String() == s { - return c, nil +func Parse(value string) (Category, error) { + for _, dataCategory := range All() { + if dataCategory.String() == value { + return dataCategory, nil } } - return 0, fmt.Errorf("unknown category: %q", s) + return 0, fmt.Errorf("unknown category: %q", value) } diff --git a/internal/category/category_test.go b/internal/category/category_test.go index ed89e04..181f7c4 100644 --- a/internal/category/category_test.go +++ b/internal/category/category_test.go @@ -9,8 +9,8 @@ import ( func TestString(t *testing.T) { tests := []struct { - c Category - want string + dataCategory Category + want string }{ {Password, "password"}, {Cookie, "cookie"}, @@ -24,8 +24,8 @@ func TestString(t *testing.T) { {Category(0), "unknown"}, {Category(999), "unknown"}, } - for _, tt := range tests { - assert.Equal(t, tt.want, tt.c.String()) + for _, testCase := range tests { + assert.Equal(t, testCase.want, testCase.dataCategory.String()) } } @@ -41,24 +41,24 @@ func TestAll_ReturnsFreshSlice(t *testing.T) { } func TestParse_RoundTrip(t *testing.T) { - for _, c := range All() { - got, err := Parse(c.String()) + for _, dataCategory := range All() { + got, err := Parse(dataCategory.String()) require.NoError(t, err) - assert.Equal(t, c, got) + assert.Equal(t, dataCategory, got) } } func TestParse_Unknown(t *testing.T) { - for _, s := range []string{"", "unknown", "all", "Password", " cookie"} { - got, err := Parse(s) - require.EqualError(t, err, "unknown category: \""+s+"\"") + for _, value := range []string{"", "unknown", "all", "Password", " cookie"} { + got, err := Parse(value) + require.EqualError(t, err, "unknown category: \""+value+"\"") assert.Zero(t, got) } } func TestZeroIsNone(t *testing.T) { - var c Category - assert.NotContains(t, All(), c) + var dataCategory Category + assert.NotContains(t, All(), dataCategory) } func TestNames(t *testing.T) { diff --git a/internal/crypto/asn1pbe.go b/internal/crypto/asn1pbe.go index 54ef152..77ddb46 100644 --- a/internal/crypto/asn1pbe.go +++ b/internal/crypto/asn1pbe.go @@ -11,25 +11,25 @@ import ( const des3KeySize = 24 // 3DES uses 24-byte (192-bit) keys -// The key is the global salt for privateKeyPBE and passwordCheckPBE, and the derived master key for credentialPBE. +// ASN1PBE keys privateKeyPBE and passwordCheckPBE with the global salt, and credentialPBE with the master key. type ASN1PBE interface { Decrypt(key []byte) ([]byte, error) Encrypt(key, plaintext []byte) ([]byte, error) } -func NewASN1PBE(b []byte) (pbe ASN1PBE, err error) { +func NewASN1PBE(encoded []byte) (pbe ASN1PBE, err error) { var ( nss privateKeyPBE meta passwordCheckPBE login credentialPBE ) - if _, err := asn1.Unmarshal(b, &nss); err == nil { + if _, err := asn1.Unmarshal(encoded, &nss); err == nil { return nss, nil } - if _, err := asn1.Unmarshal(b, &meta); err == nil { + if _, err := asn1.Unmarshal(encoded, &meta); err == nil { return meta, nil } - if _, err := asn1.Unmarshal(b, &login); err == nil { + if _, err := asn1.Unmarshal(encoded, &login); err == nil { return login, nil } return nil, errDecodeASN1 @@ -56,24 +56,24 @@ func (n privateKeyPBE) Encrypt(globalSalt, plaintext []byte) ([]byte, error) { return DES3Encrypt(key, iv, plaintext) } -// Reference: https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/lowpbe.c +// deriveKeyAndIV follows https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/lowpbe.c func (n privateKeyPBE) deriveKeyAndIV(globalSalt []byte) ([]byte, []byte) { entrySalt := n.AlgoAttr.SaltAttr.EntrySalt - hp := sha1.Sum(globalSalt) - ck := sha1.Sum(append(hp[:], entrySalt...)) + passwordHash := sha1.Sum(globalSalt) + combinedHash := sha1.Sum(append(passwordHash[:], entrySalt...)) paddedSalt := paddingZero(entrySalt, 20) - hmac1 := hmac.New(sha1.New, ck[:]) - hmac1.Write(paddedSalt) + saltHMAC := hmac.New(sha1.New, combinedHash[:]) + saltHMAC.Write(paddedSalt) - k1 := hmac.New(sha1.New, ck[:]) - k1.Write(append(paddedSalt, entrySalt...)) + firstHMAC := hmac.New(sha1.New, combinedHash[:]) + firstHMAC.Write(append(paddedSalt, entrySalt...)) - k2 := hmac.New(sha1.New, ck[:]) - k2.Write(append(hmac1.Sum(nil), entrySalt...)) + secondHMAC := hmac.New(sha1.New, combinedHash[:]) + secondHMAC.Write(append(saltHMAC.Sum(nil), entrySalt...)) - dk := append(k1.Sum(nil), k2.Sum(nil)...) - return dk[:24], dk[len(dk)-8:] + derivedKey := append(firstHMAC.Sum(nil), secondHMAC.Sum(nil)...) + return derivedKey[:24], derivedKey[len(derivedKey)-8:] } type passwordCheckPBE struct { diff --git a/internal/crypto/asn1pbe_test.go b/internal/crypto/asn1pbe_test.go index bbd4e9a..48ff341 100644 --- a/internal/crypto/asn1pbe_test.go +++ b/internal/crypto/asn1pbe_test.go @@ -73,24 +73,24 @@ var ( ) func TestNewASN1PBE(t *testing.T) { - for _, tc := range privateKeyPBETestCases { - nssRaw, err := hex.DecodeString(tc.RawHexPBE) + for _, testCase := range privateKeyPBETestCases { + nssRaw, err := hex.DecodeString(testCase.RawHexPBE) require.NoError(t, err) pbe, err := NewASN1PBE(nssRaw) require.NoError(t, err) privateKeyPBETC, ok := pbe.(privateKeyPBE) assert.True(t, ok) - assert.Equal(t, privateKeyPBETC.Encrypted, tc.Encrypted) - assert.Equal(t, privateKeyPBETC.AlgoAttr.SaltAttr.EntrySalt, tc.GlobalSalt) + assert.Equal(t, privateKeyPBETC.Encrypted, testCase.Encrypted) + assert.Equal(t, privateKeyPBETC.AlgoAttr.SaltAttr.EntrySalt, testCase.GlobalSalt) assert.Equal(t, 20, privateKeyPBETC.AlgoAttr.SaltAttr.KeyLen) - assert.Equal(t, privateKeyPBETC.AlgoAttr.ObjectIdentifier, tc.ObjectIdentifier) + assert.Equal(t, privateKeyPBETC.AlgoAttr.ObjectIdentifier, testCase.ObjectIdentifier) } } func TestPrivateKeyPBE_Encrypt(t *testing.T) { - for _, tc := range privateKeyPBETestCases { + for _, testCase := range privateKeyPBETestCases { privateKeyPBETC := privateKeyPBE{ - Encrypted: tc.Encrypted, + Encrypted: testCase.Encrypted, AlgoAttr: struct { asn1.ObjectIdentifier SaltAttr struct { @@ -98,17 +98,17 @@ func TestPrivateKeyPBE_Encrypt(t *testing.T) { KeyLen int } }{ - ObjectIdentifier: tc.ObjectIdentifier, + ObjectIdentifier: testCase.ObjectIdentifier, SaltAttr: struct { EntrySalt []byte KeyLen int }{ - EntrySalt: tc.GlobalSalt, + EntrySalt: testCase.GlobalSalt, KeyLen: 20, }, }, } - encrypted, err := privateKeyPBETC.Encrypt(tc.GlobalSalt, tc.Plaintext) + encrypted, err := privateKeyPBETC.Encrypt(testCase.GlobalSalt, testCase.Plaintext) require.NoError(t, err) assert.NotEmpty(t, encrypted) assert.Equal(t, privateKeyPBETC.Encrypted, encrypted) @@ -116,9 +116,9 @@ func TestPrivateKeyPBE_Encrypt(t *testing.T) { } func TestPrivateKeyPBE_Decrypt(t *testing.T) { - for _, tc := range privateKeyPBETestCases { + for _, testCase := range privateKeyPBETestCases { privateKeyPBETC := privateKeyPBE{ - Encrypted: tc.Encrypted, + Encrypted: testCase.Encrypted, AlgoAttr: struct { asn1.ObjectIdentifier SaltAttr struct { @@ -126,17 +126,17 @@ func TestPrivateKeyPBE_Decrypt(t *testing.T) { KeyLen int } }{ - ObjectIdentifier: tc.ObjectIdentifier, + ObjectIdentifier: testCase.ObjectIdentifier, SaltAttr: struct { EntrySalt []byte KeyLen int }{ - EntrySalt: tc.GlobalSalt, + EntrySalt: testCase.GlobalSalt, KeyLen: 20, }, }, } - decrypted, err := privateKeyPBETC.Decrypt(tc.GlobalSalt) + decrypted, err := privateKeyPBETC.Decrypt(testCase.GlobalSalt) require.NoError(t, err) assert.NotEmpty(t, decrypted) assert.Equal(t, pbePlaintext, decrypted) @@ -144,24 +144,24 @@ func TestPrivateKeyPBE_Decrypt(t *testing.T) { } func TestNewASN1PBE_PasswordCheckPBE(t *testing.T) { - for _, tc := range passwordCheckPBETestCases { - metaRaw, err := hex.DecodeString(tc.RawHexPBE) + for _, testCase := range passwordCheckPBETestCases { + metaRaw, err := hex.DecodeString(testCase.RawHexPBE) require.NoError(t, err) pbe, err := NewASN1PBE(metaRaw) require.NoError(t, err) passwordCheckPBETC, ok := pbe.(passwordCheckPBE) assert.True(t, ok) - assert.Equal(t, passwordCheckPBETC.Encrypted, tc.Encrypted) - assert.Equal(t, passwordCheckPBETC.AlgoAttr.KDFParams.IVData.IV, tc.IV) + assert.Equal(t, passwordCheckPBETC.Encrypted, testCase.Encrypted) + assert.Equal(t, passwordCheckPBETC.AlgoAttr.KDFParams.IVData.IV, testCase.IV) assert.Equal(t, passwordCheckPBETC.AlgoAttr.KDFParams.IVData.ObjectIdentifier, objWithSHA256AndAES) } } func TestPasswordCheckPBE_Encrypt(t *testing.T) { - for _, tc := range passwordCheckPBETestCases { + for _, testCase := range passwordCheckPBETestCases { passwordCheckPBETC := passwordCheckPBE{ AlgoAttr: algoAttr{ - ObjectIdentifier: tc.ObjectIdentifier, + ObjectIdentifier: testCase.ObjectIdentifier, KDFParams: struct { PBKDF2 struct { asn1.ObjectIdentifier @@ -173,27 +173,27 @@ func TestPasswordCheckPBE_Encrypt(t *testing.T) { asn1.ObjectIdentifier SaltAttr saltAttr }{ - ObjectIdentifier: tc.ObjectIdentifier, + ObjectIdentifier: testCase.ObjectIdentifier, SaltAttr: saltAttr{ - EntrySalt: tc.GlobalSalt, + EntrySalt: testCase.GlobalSalt, IterationCount: 1, KeySize: 32, Algorithm: struct { asn1.ObjectIdentifier }{ - ObjectIdentifier: tc.ObjectIdentifier, + ObjectIdentifier: testCase.ObjectIdentifier, }, }, }, IVData: ivAttr{ - ObjectIdentifier: tc.ObjectIdentifier, - IV: tc.IV, + ObjectIdentifier: testCase.ObjectIdentifier, + IV: testCase.IV, }, }, }, - Encrypted: tc.Encrypted, + Encrypted: testCase.Encrypted, } - encrypted, err := passwordCheckPBETC.Encrypt(tc.GlobalSalt, tc.Plaintext) + encrypted, err := passwordCheckPBETC.Encrypt(testCase.GlobalSalt, testCase.Plaintext) require.NoError(t, err) assert.NotEmpty(t, encrypted) assert.Equal(t, passwordCheckPBETC.Encrypted, encrypted) @@ -201,10 +201,10 @@ func TestPasswordCheckPBE_Encrypt(t *testing.T) { } func TestPasswordCheckPBE_Decrypt(t *testing.T) { - for _, tc := range passwordCheckPBETestCases { + for _, testCase := range passwordCheckPBETestCases { passwordCheckPBETC := passwordCheckPBE{ AlgoAttr: algoAttr{ - ObjectIdentifier: tc.ObjectIdentifier, + ObjectIdentifier: testCase.ObjectIdentifier, KDFParams: struct { PBKDF2 struct { asn1.ObjectIdentifier @@ -216,27 +216,27 @@ func TestPasswordCheckPBE_Decrypt(t *testing.T) { asn1.ObjectIdentifier SaltAttr saltAttr }{ - ObjectIdentifier: tc.ObjectIdentifier, + ObjectIdentifier: testCase.ObjectIdentifier, SaltAttr: saltAttr{ - EntrySalt: tc.GlobalSalt, + EntrySalt: testCase.GlobalSalt, IterationCount: 1, KeySize: 32, Algorithm: struct { asn1.ObjectIdentifier }{ - ObjectIdentifier: tc.ObjectIdentifier, + ObjectIdentifier: testCase.ObjectIdentifier, }, }, }, IVData: ivAttr{ - ObjectIdentifier: tc.ObjectIdentifier, - IV: tc.IV, + ObjectIdentifier: testCase.ObjectIdentifier, + IV: testCase.IV, }, }, }, - Encrypted: tc.Encrypted, + Encrypted: testCase.Encrypted, } - decrypted, err := passwordCheckPBETC.Decrypt(tc.GlobalSalt) + decrypted, err := passwordCheckPBETC.Decrypt(testCase.GlobalSalt) require.NoError(t, err) assert.NotEmpty(t, decrypted) assert.Equal(t, pbePlaintext, decrypted) @@ -244,33 +244,33 @@ func TestPasswordCheckPBE_Decrypt(t *testing.T) { } func TestNewASN1PBE_CredentialPBE(t *testing.T) { - for _, tc := range credentialPBETestCases { - loginRaw, err := hex.DecodeString(tc.RawHexPBE) + for _, testCase := range credentialPBETestCases { + loginRaw, err := hex.DecodeString(testCase.RawHexPBE) require.NoError(t, err) pbe, err := NewASN1PBE(loginRaw) require.NoError(t, err) credentialPBETC, ok := pbe.(credentialPBE) assert.True(t, ok) - assert.Equal(t, credentialPBETC.Encrypted, tc.Encrypted) - assert.Equal(t, credentialPBETC.Algo.IV, tc.IV) + assert.Equal(t, credentialPBETC.Encrypted, testCase.Encrypted) + assert.Equal(t, credentialPBETC.Algo.IV, testCase.IV) assert.Equal(t, credentialPBETC.Algo.ObjectIdentifier, objWithMD5AndDESCBC) } } func TestCredentialPBE_Encrypt(t *testing.T) { - for _, tc := range credentialPBETestCases { + for _, testCase := range credentialPBETestCases { credentialPBETC := credentialPBE{ KeyCheck: pbeKeyCheck, Algo: struct { asn1.ObjectIdentifier IV []byte }{ - ObjectIdentifier: tc.ObjectIdentifier, - IV: tc.IV, + ObjectIdentifier: testCase.ObjectIdentifier, + IV: testCase.IV, }, - Encrypted: tc.Encrypted, + Encrypted: testCase.Encrypted, } - encrypted, err := credentialPBETC.Encrypt(tc.GlobalSalt, plainText) + encrypted, err := credentialPBETC.Encrypt(testCase.GlobalSalt, plainText) require.NoError(t, err) assert.NotEmpty(t, encrypted) assert.Equal(t, credentialPBETC.Encrypted, encrypted) @@ -278,19 +278,19 @@ func TestCredentialPBE_Encrypt(t *testing.T) { } func TestCredentialPBE_Decrypt(t *testing.T) { - for _, tc := range credentialPBETestCases { + for _, testCase := range credentialPBETestCases { credentialPBETC := credentialPBE{ KeyCheck: pbeKeyCheck, Algo: struct { asn1.ObjectIdentifier IV []byte }{ - ObjectIdentifier: tc.ObjectIdentifier, - IV: tc.IV, + ObjectIdentifier: testCase.ObjectIdentifier, + IV: testCase.IV, }, - Encrypted: tc.Encrypted, + Encrypted: testCase.Encrypted, } - decrypted, err := credentialPBETC.Decrypt(tc.GlobalSalt) + decrypted, err := credentialPBETC.Decrypt(testCase.GlobalSalt) require.NoError(t, err) assert.NotEmpty(t, decrypted) assert.Equal(t, pbePlaintext, decrypted) @@ -348,7 +348,7 @@ func TestCredentialPBE_UnsupportedIVLength(t *testing.T) { require.ErrorIs(t, err, errUnsupportedIVLen) } -// A profile whose key could not be derived passes a nil key, which must fail instead of panicking. +// TestCredentialPBE_ShortKey passes the nil key of a profile whose key could not be derived; it must fail, not panic. func TestCredentialPBE_ShortKey(t *testing.T) { raw, err := hex.DecodeString(credentialPBETestCases[0].RawHexPBE) require.NoError(t, err) diff --git a/internal/crypto/crypto.go b/internal/crypto/crypto.go index 5b0a2c7..a0ace44 100644 --- a/internal/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -71,7 +71,7 @@ func AESGCMDecrypt(key, nonce, ciphertext []byte) ([]byte, error) { return aead.Open(nil, nonce, ciphertext, nil) } -// blob is [12-byte nonce][ciphertext + 16-byte tag], as Yandex stores it. +// AESGCMDecryptBlob takes [12-byte nonce][ciphertext + 16-byte tag], as Yandex stores it. func AESGCMDecryptBlob(key, blob, aad []byte) ([]byte, error) { if len(blob) < gcmNonceSize { return nil, errShortCiphertext @@ -93,67 +93,67 @@ func cbcEncrypt(block cipher.Block, iv, plaintext []byte) ([]byte, error) { } padded := pkcs5Padding(plaintext, block.BlockSize()) - dst := make([]byte, len(padded)) - cipher.NewCBCEncrypter(block, iv).CryptBlocks(dst, padded) - return dst, nil + encrypted := make([]byte, len(padded)) + cipher.NewCBCEncrypter(block, iv).CryptBlocks(encrypted, padded) + return encrypted, nil } func cbcDecrypt(block cipher.Block, iv, ciphertext []byte) ([]byte, error) { - bs := block.BlockSize() - if len(iv) != bs { + blockSize := block.BlockSize() + if len(iv) != blockSize { return nil, errInvalidIVLength } - if len(ciphertext) < bs { + if len(ciphertext) < blockSize { return nil, errShortCiphertext } - if len(ciphertext)%bs != 0 { + if len(ciphertext)%blockSize != 0 { return nil, errInvalidBlockSize } - dst := make([]byte, len(ciphertext)) - cipher.NewCBCDecrypter(block, iv).CryptBlocks(dst, ciphertext) + decrypted := make([]byte, len(ciphertext)) + cipher.NewCBCDecrypter(block, iv).CryptBlocks(decrypted, ciphertext) - dst, err := pkcs5UnPadding(dst, bs) + decrypted, err := pkcs5UnPadding(decrypted, blockSize) if err != nil { return nil, fmt.Errorf("decrypt: %w", err) } - return dst, nil + return decrypted, nil } -// paddingZero returns src unchanged if already long enough; otherwise a zero-padded new slice. -func paddingZero(src []byte, length int) []byte { - if len(src) >= length { - return src +// paddingZero returns data unchanged if already long enough; otherwise a zero-padded new slice. +func paddingZero(data []byte, length int) []byte { + if len(data) >= length { + return data } - dst := make([]byte, length) - copy(dst, src) - return dst + padded := make([]byte, length) + copy(padded, data) + return padded } -// pkcs5Padding always returns a new slice and never modifies src. -func pkcs5Padding(src []byte, blockSize int) []byte { - n := blockSize - (len(src) % blockSize) - dst := make([]byte, len(src)+n) - copy(dst, src) - for i := len(src); i < len(dst); i++ { - dst[i] = byte(n) +// pkcs5Padding always returns a new slice and never modifies data. +func pkcs5Padding(data []byte, blockSize int) []byte { + paddingLength := blockSize - (len(data) % blockSize) + padded := make([]byte, len(data)+paddingLength) + copy(padded, data) + for i := len(data); i < len(padded); i++ { + padded[i] = byte(paddingLength) } - return dst + return padded } -func pkcs5UnPadding(src []byte, blockSize int) ([]byte, error) { - length := len(src) +func pkcs5UnPadding(data []byte, blockSize int) ([]byte, error) { + length := len(data) if length == 0 { return nil, errInvalidPadding } - padding := int(src[length-1]) + padding := int(data[length-1]) if padding < 1 || padding > blockSize || padding > length { return nil, errInvalidPadding } - for _, b := range src[length-padding:] { - if int(b) != padding { + for _, paddingByte := range data[length-padding:] { + if int(paddingByte) != padding { return nil, errInvalidPadding } } - return src[:length-padding], nil + return data[:length-padding], nil } diff --git a/internal/crypto/crypto_test.go b/internal/crypto/crypto_test.go index c520689..621dc51 100644 --- a/internal/crypto/crypto_test.go +++ b/internal/crypto/crypto_test.go @@ -73,41 +73,41 @@ func TestAESGCMDecrypt(t *testing.T) { } func TestPkcs5Padding_NoMutation(t *testing.T) { - src := make([]byte, 3, 32) // len=3, cap=32 — append won't allocate - copy(src, "abc") - backup := make([]byte, cap(src)) - copy(backup, src[:cap(src)]) + data := make([]byte, 3, 32) // len=3, cap=32 — append won't allocate + copy(data, "abc") + backup := make([]byte, cap(data)) + copy(backup, data[:cap(data)]) - padded := pkcs5Padding(src, 16) + padded := pkcs5Padding(data, 16) assert.Len(t, padded, 16) - assert.Equal(t, []byte("abc"), src) + assert.Equal(t, []byte("abc"), data) - // The bytes beyond len(src) in the original backing array must not be touched. - current := make([]byte, cap(src)) - copy(current, src[:cap(src)]) + // The bytes beyond len(data) in the original backing array must not be touched. + current := make([]byte, cap(data)) + copy(current, data[:cap(data)]) assert.Equal(t, backup, current, "pkcs5Padding mutated the original slice backing array") } func TestPaddingZero_NoMutation(t *testing.T) { - src := make([]byte, 3, 32) - copy(src, "abc") - backup := make([]byte, cap(src)) - copy(backup, src[:cap(src)]) + data := make([]byte, 3, 32) + copy(data, "abc") + backup := make([]byte, cap(data)) + copy(backup, data[:cap(data)]) - padded := paddingZero(src, 20) + padded := paddingZero(data, 20) assert.Len(t, padded, 20) - current := make([]byte, cap(src)) - copy(current, src[:cap(src)]) + current := make([]byte, cap(data)) + copy(current, data[:cap(data)]) assert.Equal(t, backup, current, "paddingZero mutated the original slice backing array") } func TestAESCBCDecrypt_WrongIVLength(t *testing.T) { key := bytes.Repeat([]byte("k"), 16) wrongIV := []byte("short") - ct := make([]byte, 16) + ciphertext := make([]byte, 16) - _, err := AESCBCDecrypt(key, wrongIV, ct) + _, err := AESCBCDecrypt(key, wrongIV, ciphertext) require.Error(t, err, "wrong IV length should return error, not panic") assert.ErrorIs(t, err, errInvalidIVLength) } @@ -124,9 +124,9 @@ func TestAESCBCEncrypt_WrongIVLength(t *testing.T) { func TestDES3Decrypt_WrongIVLength(t *testing.T) { key := bytes.Repeat([]byte("k"), 24) wrongIV := []byte("ab") // DES needs 8-byte IV - ct := make([]byte, 8) + ciphertext := make([]byte, 8) - _, err := DES3Decrypt(key, wrongIV, ct) + _, err := DES3Decrypt(key, wrongIV, ciphertext) require.Error(t, err, "wrong IV length should return error, not panic") assert.ErrorIs(t, err, errInvalidIVLength) } @@ -163,9 +163,9 @@ func TestAESGCMEncrypt_WrongNonceLength(t *testing.T) { func TestAESGCMDecrypt_WrongNonceLength(t *testing.T) { key := bytes.Repeat([]byte("k"), 16) wrongNonce := []byte("short") - ct := make([]byte, 32) + ciphertext := make([]byte, 32) - _, err := AESGCMDecrypt(key, wrongNonce, ct) + _, err := AESGCMDecrypt(key, wrongNonce, ciphertext) require.Error(t, err, "wrong nonce length should return error, not panic") assert.ErrorIs(t, err, errInvalidNonceLen) } diff --git a/internal/crypto/pbkdf2.go b/internal/crypto/pbkdf2.go index 27dc291..a571c82 100644 --- a/internal/crypto/pbkdf2.go +++ b/internal/crypto/pbkdf2.go @@ -5,36 +5,36 @@ import ( "hash" ) -// Copied from golang.org/x/crypto/pbkdf2. -func PBKDF2Key(password, salt []byte, iterations, keyLen int, h func() hash.Hash) []byte { - prf := hmac.New(h, password) +// PBKDF2Key is adapted from golang.org/x/crypto/pbkdf2. +func PBKDF2Key(password, salt []byte, iterations, keyLen int, newHash func() hash.Hash) []byte { + prf := hmac.New(newHash, password) hashLen := prf.Size() numBlocks := (keyLen + hashLen - 1) / hashLen - var buf [4]byte - dk := make([]byte, 0, numBlocks*hashLen) - u := make([]byte, hashLen) + var blockIndex [4]byte + derivedKey := make([]byte, 0, numBlocks*hashLen) + previous := make([]byte, hashLen) for block := 1; block <= numBlocks; block++ { prf.Reset() prf.Write(salt) - buf[0] = byte(block >> 24) - buf[1] = byte(block >> 16) - buf[2] = byte(block >> 8) - buf[3] = byte(block) - prf.Write(buf[:4]) - dk = prf.Sum(dk) - t := dk[len(dk)-hashLen:] - copy(u, t) + blockIndex[0] = byte(block >> 24) + blockIndex[1] = byte(block >> 16) + blockIndex[2] = byte(block >> 8) + blockIndex[3] = byte(block) + prf.Write(blockIndex[:4]) + derivedKey = prf.Sum(derivedKey) + lastBlock := derivedKey[len(derivedKey)-hashLen:] + copy(previous, lastBlock) - for n := 2; n <= iterations; n++ { + for iteration := 2; iteration <= iterations; iteration++ { prf.Reset() - prf.Write(u) - u = u[:0] - u = prf.Sum(u) - for x := range u { - t[x] ^= u[x] + prf.Write(previous) + previous = previous[:0] + previous = prf.Sum(previous) + for byteIndex := range previous { + lastBlock[byteIndex] ^= previous[byteIndex] } } } - return dk[:keyLen] + return derivedKey[:keyLen] } diff --git a/internal/crypto/pbkdf2_test.go b/internal/crypto/pbkdf2_test.go index dc30060..97ff024 100644 --- a/internal/crypto/pbkdf2_test.go +++ b/internal/crypto/pbkdf2_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" ) -// Test vectors from RFC 6070 (PKCS #5 PBKDF2 with HMAC-SHA1). +// TestPBKDF2Key_RFC6070 uses the test vectors from RFC 6070 (PKCS #5 PBKDF2 with HMAC-SHA1). // https://www.rfc-editor.org/rfc/rfc6070 func TestPBKDF2Key_RFC6070(t *testing.T) { tests := []struct { @@ -52,10 +52,10 @@ func TestPBKDF2Key_RFC6070(t *testing.T) { want: "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038", }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := PBKDF2Key([]byte(tt.password), []byte(tt.salt), tt.iterations, tt.keyLen, sha1.New) - assert.Equal(t, tt.want, hex.EncodeToString(got)) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + got := PBKDF2Key([]byte(testCase.password), []byte(testCase.salt), testCase.iterations, testCase.keyLen, sha1.New) + assert.Equal(t, testCase.want, hex.EncodeToString(got)) }) } } diff --git a/internal/export/cookie_editor.go b/internal/export/cookie_editor.go index a886adb..76e8a15 100644 --- a/internal/export/cookie_editor.go +++ b/internal/export/cookie_editor.go @@ -8,33 +8,33 @@ import ( var sameSiteNone = "no_restriction" -func cookieEditorValue(r record.Record) any { - c, ok := r.(*record.Cookie) +func cookieEditorValue(row record.Record) any { + cookie, ok := row.(*record.Cookie) if !ok { - return r + return row } var expDate float64 - if !c.ExpireAt.IsZero() { - expDate = float64(c.ExpireAt.Unix()) + if !cookie.ExpireAt.IsZero() { + expDate = float64(cookie.ExpireAt.Unix()) } - sameSite := &c.SameSite - switch c.SameSite { + sameSite := &cookie.SameSite + switch cookie.SameSite { case "none": sameSite = &sameSiteNone case "", "unspecified": sameSite = nil } return cookieEditorEntry{ - Domain: c.Host, + Domain: cookie.Host, ExpirationDate: expDate, - HTTPOnly: c.IsHTTPOnly, - Name: c.Name, - Path: c.Path, - Secure: c.IsSecure, - Value: c.Value, + HTTPOnly: cookie.IsHTTPOnly, + Name: cookie.Name, + Path: cookie.Path, + Secure: cookie.IsSecure, + Value: cookie.Value, SameSite: sameSite, Session: expDate == 0., - HostOnly: !strings.HasPrefix(c.Host, "."), + HostOnly: !strings.HasPrefix(cookie.Host, "."), } } diff --git a/internal/export/csv.go b/internal/export/csv.go index 3b06355..6af75f3 100644 --- a/internal/export/csv.go +++ b/internal/export/csv.go @@ -8,30 +8,30 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// Excel reads a CSV file as UTF-8 only when it starts with a BOM. +// utf8BOM starts every CSV file, because Excel reads one as UTF-8 only when it starts with a BOM. var utf8BOM = []byte{0xEF, 0xBB, 0xBF} type csvEncoder struct { - w io.Writer + writer io.Writer rows *csv.Writer header bool } -func newCSVEncoder(w io.Writer) *csvEncoder { - return &csvEncoder{w: w, rows: csv.NewWriter(w)} +func newCSVEncoder(writer io.Writer) *csvEncoder { + return &csvEncoder{writer: writer, rows: csv.NewWriter(writer)} } -func (e *csvEncoder) encode(r record.Record) error { +func (e *csvEncoder) encode(row record.Record) error { if !e.header { - if _, err := e.w.Write(utf8BOM); err != nil { + if _, err := e.writer.Write(utf8BOM); err != nil { return fmt.Errorf("write BOM: %w", err) } - if err := e.rows.Write(structCSVHeader(r)); err != nil { + if err := e.rows.Write(structCSVHeader(row)); err != nil { return err } e.header = true } - return e.rows.Write(structCSVRow(r)) + return e.rows.Write(structCSVRow(row)) } func (e *csvEncoder) end() error { diff --git a/internal/export/format.go b/internal/export/format.go index 24193dd..68b5864 100644 --- a/internal/export/format.go +++ b/internal/export/format.go @@ -8,7 +8,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// The zero Format is JSON, the -f default. +// Format defaults to JSON at its zero value, as -f does. type Format int const ( @@ -17,8 +17,8 @@ const ( CookieEditor ) -func ParseFormat(s string) (Format, error) { - switch s { +func ParseFormat(value string) (Format, error) { + switch value { case "json": return JSON, nil case "csv": @@ -26,7 +26,7 @@ func ParseFormat(s string) (Format, error) { case "cookie-editor": return CookieEditor, nil default: - return 0, fmt.Errorf("unsupported format: %s", s) + return 0, fmt.Errorf("unsupported format: %s", value) } } @@ -39,17 +39,17 @@ func (f Format) ext() string { // encoder writes one category's file; it frames the document itself so that every Write can append to it. type encoder interface { - encode(r record.Record) error + encode(row record.Record) error end() error } -func newEncoder(w io.Writer, f Format, c category.Category) encoder { +func newEncoder(writer io.Writer, format Format, dataCategory category.Category) encoder { switch { - case f == CSV: - return newCSVEncoder(w) - case f == CookieEditor && c == category.Cookie: - return &jsonEncoder{w: w, value: cookieEditorValue} + case format == CSV: + return newCSVEncoder(writer) + case format == CookieEditor && dataCategory == category.Cookie: + return &jsonEncoder{writer: writer, value: cookieEditorValue} default: - return &jsonEncoder{w: w, escapeHTML: true} + return &jsonEncoder{writer: writer, escapeHTML: true} } } diff --git a/internal/export/golden_test.go b/internal/export/golden_test.go index e3ef70d..f6e72f2 100644 --- a/internal/export/golden_test.go +++ b/internal/export/golden_test.go @@ -26,7 +26,7 @@ const ( exportURLWithHTMLCharsEscaped = `https://shop.example.com/cart?item=42\u0026qty=\u003c3\u003e` ) -type exportStamp struct { +type profileExport struct { browser string profile string data *exportData @@ -51,58 +51,58 @@ type exportURLForm struct { func TestExportGolden(t *testing.T) { formats := []struct { - format string - ext string - urlForms []exportURLForm - jsonFallback bool + format string + fileExtension string + urlForms []exportURLForm + jsonFallback bool }{ { - format: "csv", - ext: "csv", - urlForms: []exportURLForm{{file: "cookie.csv"}, {file: "history.csv"}}, + format: "csv", + fileExtension: "csv", + urlForms: []exportURLForm{{file: "cookie.csv"}, {file: "history.csv"}}, }, { - format: "json", - ext: "json", - urlForms: []exportURLForm{{file: "cookie.json", escaped: true}, {file: "history.json", escaped: true}}, + format: "json", + fileExtension: "json", + urlForms: []exportURLForm{{file: "cookie.json", escaped: true}, {file: "history.json", escaped: true}}, }, { - format: "cookie-editor", - ext: "json", - urlForms: []exportURLForm{{file: "cookie.json"}, {file: "history.json", escaped: true}}, - jsonFallback: true, + format: "cookie-editor", + fileExtension: "json", + urlForms: []exportURLForm{{file: "cookie.json"}, {file: "history.json", escaped: true}}, + jsonFallback: true, }, } - for _, tc := range formats { - tc := tc - t.Run(tc.format, func(t *testing.T) { + for _, testCase := range formats { + testCase := testCase + t.Run(testCase.format, func(t *testing.T) { dir := filepath.Join(t.TempDir(), "results") - exportWrite(t, dir, tc.format, false, exportStamps()) + exportWrite(t, dir, testCase.format, false, profileExports()) got := golden.Bundle(t, dir) - if tc.jsonFallback { + if testCase.jsonFallback { jsonDir := filepath.Join(t.TempDir(), "results") - exportWrite(t, jsonDir, "json", false, exportStamps()) + exportWrite(t, jsonDir, "json", false, profileExports()) golden.AssertJSONFallback(t, dir, jsonDir) got = golden.BundleFiles(t, dir, "cookie.json") } - golden.Assert(t, "export-"+tc.format+".golden", got) - assert.Equal(t, exportCategoryFiles(tc.ext, category.All()...), exportDirFiles(t, dir)) + golden.Assert(t, "export-"+testCase.format+".golden", got) + assert.Equal(t, exportCategoryFiles(testCase.fileExtension, category.All()...), exportDirFiles(t, dir)) exportAssertFileContract(t, dir) - for _, form := range tc.urlForms { + for _, form := range testCase.urlForms { exportAssertURLForm(t, dir, form) } sparse := filepath.Join(t.TempDir(), "sparse") - exportWrite(t, sparse, tc.format, false, exportSparseStamps()) - assert.Equal(t, exportCategoryFiles(tc.ext, category.Password, category.LocalStorage), exportDirFiles(t, sparse)) + exportWrite(t, sparse, testCase.format, false, sparseProfileExports()) + assert.Equal(t, exportCategoryFiles(testCase.fileExtension, category.Password, category.LocalStorage), exportDirFiles(t, sparse)) }) } t.Run("zip", func(t *testing.T) { loose := filepath.Join(t.TempDir(), "results") - exportWrite(t, loose, "csv", false, exportStamps()) + exportWrite(t, loose, "csv", false, profileExports()) dir := filepath.Join(t.TempDir(), "results") - exportWrite(t, dir, "csv", true, exportStamps()) + exportWrite(t, dir, "csv", true, profileExports()) assert.Equal(t, []string{"results.zip"}, exportDirFiles(t, dir)) archive := filepath.Join(dir, "results.zip") @@ -111,22 +111,22 @@ func TestExportGolden(t *testing.T) { }) } -func exportWrite(t *testing.T, dir, format string, compress bool, stamps []exportStamp) { +func exportWrite(t *testing.T, dir, format string, compress bool, exports []profileExport) { t.Helper() - f, err := export.ParseFormat(format) + parsedFormat, err := export.ParseFormat(format) require.NoError(t, err) - w, err := export.NewWriter(dir, f, compress) + writer, err := export.NewWriter(dir, parsedFormat, compress) require.NoError(t, err) - for _, s := range stamps { - require.NoError(t, writeStamp(w, s)) + for _, batch := range exports { + require.NoError(t, writeProfileExport(writer, batch)) } - require.NoError(t, w.Close()) + require.NoError(t, writer.Close()) } -func exportCategoryFiles(ext string, categories ...category.Category) []string { +func exportCategoryFiles(fileExtension string, categories ...category.Category) []string { names := make([]string, 0, len(categories)) - for _, c := range categories { - names = append(names, c.String()+"."+ext) + for _, dataCategory := range categories { + names = append(names, dataCategory.String()+"."+fileExtension) } sort.Strings(names) return names @@ -137,8 +137,8 @@ func exportDirFiles(t *testing.T, dir string) []string { entries, err := os.ReadDir(dir) require.NoError(t, err) names := make([]string, 0, len(entries)) - for _, e := range entries { - names = append(names, e.Name()) + for _, entry := range entries { + names = append(names, entry.Name()) } return names } @@ -152,22 +152,22 @@ func exportReadFile(t *testing.T, dir, name string) string { func exportReadZip(t *testing.T, path string) map[string]string { t.Helper() - r, err := zip.OpenReader(path) + zipReader, err := zip.OpenReader(path) require.NoError(t, err) - defer r.Close() - entries := make(map[string]string, len(r.File)) - for _, f := range r.File { - entries[f.Name] = exportReadZipEntry(t, f) + defer zipReader.Close() + entries := make(map[string]string, len(zipReader.File)) + for _, zipFile := range zipReader.File { + entries[zipFile.Name] = exportReadZipEntry(t, zipFile) } return entries } -func exportReadZipEntry(t *testing.T, f *zip.File) string { +func exportReadZipEntry(t *testing.T, zipFile *zip.File) string { t.Helper() - rc, err := f.Open() + entryReader, err := zipFile.Open() require.NoError(t, err) - defer rc.Close() - data, err := io.ReadAll(rc) + defer entryReader.Close() + data, err := io.ReadAll(entryReader) require.NoError(t, err) return string(data) } @@ -203,9 +203,9 @@ func exportAssertURLForm(t *testing.T, dir string, form exportURLForm) { assert.NotContainsf(t, content, absent, "%s", form.file) } -// Entries are listed in extractor sort order with unique sort keys, so re-sorting a profile cannot change a golden. -func exportStamps() []exportStamp { - return []exportStamp{ +// profileExports lists entries in sort order with unique sort keys, so re-sorting a profile cannot change a golden. +func profileExports() []profileExport { + return []profileExport{ {browser: "Chrome", profile: "Default", data: &exportData{ Passwords: []record.Login{ { @@ -378,8 +378,8 @@ func exportStamps() []exportStamp { } } -func exportSparseStamps() []exportStamp { - return []exportStamp{ +func sparseProfileExports() []profileExport { + return []profileExport{ {browser: "Chrome", profile: "Default", data: &exportData{ Passwords: []record.Login{{URL: "https://example.com/", Username: "alice", Store: record.StoreLocal}}, Cookies: []record.Cookie{}, @@ -392,42 +392,42 @@ func exportSparseStamps() []exportStamp { } } -func writeStamp(w *export.Writer, s exportStamp) error { - if s.data == nil { +func writeProfileExport(writer *export.Writer, batch profileExport) error { + if batch.data == nil { return nil } - for _, c := range category.All() { - records := profileRecords(s.data, c) - for _, rec := range records { - record.Stamp(rec, s.browser, s.profile) + for _, dataCategory := range category.All() { + records := profileRecords(batch.data, dataCategory) + for _, row := range records { + row.SetBrowserAndProfile(batch.browser, batch.profile) } - if err := w.Write(c, records); err != nil { + if err := writer.Write(dataCategory, records); err != nil { return err } } return nil } -func profileRecords(d *exportData, c category.Category) []record.Record { - switch c { +func profileRecords(data *exportData, dataCategory category.Category) []record.Record { + switch dataCategory { case category.Password: - return recordsOf(d.Passwords) + return recordsOf(data.Passwords) case category.Cookie: - return recordsOf(d.Cookies) + return recordsOf(data.Cookies) case category.Bookmark: - return recordsOf(d.Bookmarks) + return recordsOf(data.Bookmarks) case category.History: - return recordsOf(d.Histories) + return recordsOf(data.Histories) case category.Download: - return recordsOf(d.Downloads) + return recordsOf(data.Downloads) case category.CreditCard: - return recordsOf(d.CreditCards) + return recordsOf(data.CreditCards) case category.Extension: - return recordsOf(d.Extensions) + return recordsOf(data.Extensions) case category.LocalStorage: - return recordsOf(d.LocalStorage) + return recordsOf(data.LocalStorage) case category.SessionStorage: - return recordsOf(d.SessionStorage) + return recordsOf(data.SessionStorage) default: return nil } diff --git a/internal/export/json.go b/internal/export/json.go index 07a3de4..dbdc72b 100644 --- a/internal/export/json.go +++ b/internal/export/json.go @@ -12,42 +12,42 @@ const jsonIndent = " " // jsonEncoder writes the bytes a single indented Encode of the whole slice would produce, one element at a time. type jsonEncoder struct { - w io.Writer + writer io.Writer escapeHTML bool value func(record.Record) any - n int + written int } -func (e *jsonEncoder) encode(r record.Record) error { - var v any = r +func (e *jsonEncoder) encode(row record.Record) error { + var value any = row if e.value != nil { - v = e.value(r) + value = e.value(row) } - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - enc.SetEscapeHTML(e.escapeHTML) - enc.SetIndent(jsonIndent, jsonIndent) - if err := enc.Encode(v); err != nil { + var buffer bytes.Buffer + valueEncoder := json.NewEncoder(&buffer) + valueEncoder.SetEscapeHTML(e.escapeHTML) + valueEncoder.SetIndent(jsonIndent, jsonIndent) + if err := valueEncoder.Encode(value); err != nil { return err } - sep := ",\n" + jsonIndent - if e.n == 0 { - sep = "[\n" + jsonIndent + separator := ",\n" + jsonIndent + if e.written == 0 { + separator = "[\n" + jsonIndent } - e.n++ - if _, err := io.WriteString(e.w, sep); err != nil { + e.written++ + if _, err := io.WriteString(e.writer, separator); err != nil { return err } - _, err := e.w.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n"))) + _, err := e.writer.Write(bytes.TrimSuffix(buffer.Bytes(), []byte("\n"))) return err } func (e *jsonEncoder) end() error { closing := "\n]\n" - if e.n == 0 { + if e.written == 0 { closing = "[]\n" } - _, err := io.WriteString(e.w, closing) + _, err := io.WriteString(e.writer, closing) return err } diff --git a/internal/export/json_test.go b/internal/export/json_test.go index 85b40c8..e43932c 100644 --- a/internal/export/json_test.go +++ b/internal/export/json_test.go @@ -11,25 +11,25 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -func encodeOnce(t *testing.T, v any, escapeHTML bool) string { +func encodeOnce(t *testing.T, value any, escapeHTML bool) string { t.Helper() - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - enc.SetIndent("", jsonIndent) - enc.SetEscapeHTML(escapeHTML) - require.NoError(t, enc.Encode(v)) - return buf.String() + var buffer bytes.Buffer + referenceEncoder := json.NewEncoder(&buffer) + referenceEncoder.SetIndent("", jsonIndent) + referenceEncoder.SetEscapeHTML(escapeHTML) + require.NoError(t, referenceEncoder.Encode(value)) + return buffer.String() } -func encodeFramed(t *testing.T, e *jsonEncoder, records []record.Record) string { +func encodeFramed(t *testing.T, framedEncoder *jsonEncoder, records []record.Record) string { t.Helper() - var buf bytes.Buffer - e.w = &buf - for _, r := range records { - require.NoError(t, e.encode(r)) + var buffer bytes.Buffer + framedEncoder.writer = &buffer + for _, row := range records { + require.NoError(t, framedEncoder.encode(row)) } - require.NoError(t, e.end()) - return buf.String() + require.NoError(t, framedEncoder.end()) + return buffer.String() } func TestJSONEncoder_MatchesOneEncodeOfTheSlice(t *testing.T) { @@ -49,8 +49,8 @@ func TestJSONEncoder_MatchesOneEncodeOfTheSlice(t *testing.T) { t.Run("cookie-editor does not", func(t *testing.T) { entries := make([]any, 0, len(cookies)) - for _, c := range cookies { - entries = append(entries, cookieEditorValue(c)) + for _, cookie := range cookies { + entries = append(entries, cookieEditorValue(cookie)) } got := encodeFramed(t, &jsonEncoder{value: cookieEditorValue}, cookies) assert.Equal(t, encodeOnce(t, entries, false), got) diff --git a/internal/export/order.go b/internal/export/order.go index 4b02301..bc60ad4 100644 --- a/internal/export/order.go +++ b/internal/export/order.go @@ -7,7 +7,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/record" ) -// Stable, so ties and keyless records keep source order: Safari's bookmarks and downloads have no timestamp. +// 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 keyOf(records[i]).before(keyOf(records[j])) @@ -15,30 +15,30 @@ func sortRecords(records []record.Record) { } type sortKey struct { - visits int - at time.Time + visits int + timestamp time.Time } -func keyOf(r record.Record) sortKey { - switch r := r.(type) { +func keyOf(row record.Record) sortKey { + switch typed := row.(type) { case *record.Login: - return sortKey{at: r.CreatedAt} + return sortKey{timestamp: typed.CreatedAt} case *record.Cookie: - return sortKey{at: r.CreatedAt} + return sortKey{timestamp: typed.CreatedAt} case *record.Bookmark: - return sortKey{at: r.CreatedAt} + return sortKey{timestamp: typed.CreatedAt} case *record.Download: - return sortKey{at: r.StartTime} + return sortKey{timestamp: typed.StartTime} case *record.History: - return sortKey{visits: r.VisitCount} + return sortKey{visits: typed.VisitCount} default: return sortKey{} } } -func (k sortKey) before(o sortKey) bool { - if k.visits != o.visits { - return k.visits > o.visits +func (k sortKey) before(other sortKey) bool { + if k.visits != other.visits { + return k.visits > other.visits } - return k.at.After(o.at) + return k.timestamp.After(other.timestamp) } diff --git a/internal/export/order_test.go b/internal/export/order_test.go index c26219a..519a00b 100644 --- a/internal/export/order_test.go +++ b/internal/export/order_test.go @@ -12,7 +12,7 @@ import ( const tiedRecords = 20 -func day(d int) time.Time { return time.Date(2026, 1, d, 0, 0, 0, 0, time.UTC) } +func day(dayOfMonth int) time.Time { return time.Date(2026, 1, dayOfMonth, 0, 0, 0, 0, time.UTC) } func TestSortRecords_NewestFirst(t *testing.T) { logins := []record.Record{ @@ -31,7 +31,7 @@ func TestSortRecords_NewestFirst(t *testing.T) { assert.Equal(t, []string{"newer", "older"}, urlsOf(t, downloads)) } -// Firefox used to write its history least visited first; the exporter now orders history the same for every browser. +// TestSortRecords_HistoryMostVisitedFirst orders history alike for every browser; Firefox wrote it least visited first. func TestSortRecords_HistoryMostVisitedFirst(t *testing.T) { histories := []record.Record{ &record.History{URL: "once", VisitCount: 1}, @@ -64,7 +64,7 @@ func TestSortRecords_TiesKeepSourceOrder(t *testing.T) { assert.Equal(t, want, bookmarks, "bookmarks without a creation time keep their tree order") } -// Interleaved timestamps make the sort move records; an unstable sort would then reorder the ties it moves. +// TestSortRecords_IsStable interleaves timestamps so the sort moves records, which an unstable sort would reorder. func TestSortRecords_IsStable(t *testing.T) { logins := make([]record.Record, 0, tiedRecords) var newer, older []string @@ -100,16 +100,16 @@ func TestSortRecords_KeylessCategoriesKeepSourceOrder(t *testing.T) { func urlsOf(t *testing.T, records []record.Record) []string { t.Helper() urls := make([]string, 0, len(records)) - for _, r := range records { - switch r := r.(type) { + for _, row := range records { + switch typed := row.(type) { case *record.Login: - urls = append(urls, r.URL) + urls = append(urls, typed.URL) case *record.Download: - urls = append(urls, r.URL) + urls = append(urls, typed.URL) case *record.History: - urls = append(urls, r.URL) + urls = append(urls, typed.URL) default: - t.Fatalf("unexpected record %T", r) + t.Fatalf("unexpected record %T", typed) } } return urls diff --git a/internal/export/reflect.go b/internal/export/reflect.go index e12469e..205238d 100644 --- a/internal/export/reflect.go +++ b/internal/export/reflect.go @@ -10,11 +10,11 @@ import ( var timeType = reflect.TypeOf(time.Time{}) -func structCSVHeader(v any) []string { - t := reflect.Indirect(reflect.ValueOf(v)).Type() - headers := make([]string, 0, t.NumField()) - for i := 0; i < t.NumField(); i++ { - name := tagName(t.Field(i), "csv") +func structCSVHeader(value any) []string { + structType := reflect.Indirect(reflect.ValueOf(value)).Type() + headers := make([]string, 0, structType.NumField()) + for i := 0; i < structType.NumField(); i++ { + name := tagName(structType.Field(i), "csv") if name == "" { continue } @@ -23,26 +23,26 @@ func structCSVHeader(v any) []string { return headers } -func structCSVRow(v any) []string { - val := reflect.Indirect(reflect.ValueOf(v)) - t := val.Type() - row := make([]string, 0, t.NumField()) - for i := 0; i < t.NumField(); i++ { - if tagName(t.Field(i), "csv") == "" { +func structCSVRow(value any) []string { + structValue := reflect.Indirect(reflect.ValueOf(value)) + structType := structValue.Type() + row := make([]string, 0, structType.NumField()) + for i := 0; i < structType.NumField(); i++ { + if tagName(structType.Field(i), "csv") == "" { continue } - row = append(row, fieldToString(val.Field(i))) + row = append(row, fieldToString(structValue.Field(i))) } return row } -func tagName(f reflect.StructField, key string) string { - tag, ok := f.Tag.Lookup(key) +func tagName(field reflect.StructField, key string) string { + tag, ok := field.Tag.Lookup(key) if !ok || tag == "-" { return "" } - if idx := strings.IndexByte(tag, ','); idx != -1 { - tag = tag[:idx] + if index := strings.IndexByte(tag, ','); index != -1 { + tag = tag[:index] } if tag == "" { return "" @@ -50,32 +50,32 @@ func tagName(f reflect.StructField, key string) string { return tag } -func fieldToString(v reflect.Value) string { - if v.Type() == timeType { - t, _ := v.Interface().(time.Time) - return formatTime(t) +func fieldToString(value reflect.Value) string { + if value.Type() == timeType { + timestamp, _ := value.Interface().(time.Time) + return formatTime(timestamp) } - switch v.Kind() { + switch value.Kind() { case reflect.String: - return v.String() + return value.String() case reflect.Bool: - return formatBool(v.Bool()) + return formatBool(value.Bool()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return strconv.FormatInt(v.Int(), 10) + return strconv.FormatInt(value.Int(), 10) default: - return fmt.Sprintf("%v", v.Interface()) + return fmt.Sprintf("%v", value.Interface()) } } -func formatTime(t time.Time) string { - if t.IsZero() { +func formatTime(timestamp time.Time) string { + if timestamp.IsZero() { return "" } - return t.Format(time.RFC3339) + return timestamp.Format(time.RFC3339) } -func formatBool(b bool) string { - if b { +func formatBool(value bool) string { + if value { return "true" } return "false" diff --git a/internal/export/reflect_test.go b/internal/export/reflect_test.go index 520bae4..1c941fa 100644 --- a/internal/export/reflect_test.go +++ b/internal/export/reflect_test.go @@ -25,18 +25,18 @@ var allRecordTypes = []record.Record{ &record.SessionStorage{}, } -// A field without a csv tag would be silently left out of the CSV output. +// TestAllRecordFieldsHaveCSVTag catches a field without a csv tag, which would be silently left out of the CSV output. func TestAllRecordFieldsHaveCSVTag(t *testing.T) { - for _, r := range allRecordTypes { - et := reflect.TypeOf(r).Elem() - t.Run(et.Name(), func(t *testing.T) { - for i := 0; i < et.NumField(); i++ { - f := et.Field(i) - if !f.IsExported() { + for _, row := range allRecordTypes { + recordType := reflect.TypeOf(row).Elem() + t.Run(recordType.Name(), func(t *testing.T) { + for i := 0; i < recordType.NumField(); i++ { + field := recordType.Field(i) + if !field.IsExported() { continue } - _, ok := f.Tag.Lookup("csv") - assert.True(t, ok, "field %s.%s missing csv tag", et.Name(), f.Name) + _, ok := field.Tag.Lookup("csv") + assert.True(t, ok, "field %s.%s missing csv tag", recordType.Name(), field.Name) } }) } @@ -67,9 +67,9 @@ func TestStructCSVHeader(t *testing.T) { "browser", "profile", "name", "id", "description", "version", "homepage_url", "enabled", }}, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.expect, structCSVHeader(tt.record)) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + assert.Equal(t, testCase.expect, structCSVHeader(testCase.record)) }) } } @@ -118,9 +118,9 @@ func TestStructCSVRow(t *testing.T) { []string{"", "", "https://a.com", "", "", "", ""}, }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.expect, structCSVRow(tt.record)) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + assert.Equal(t, testCase.expect, structCSVRow(testCase.record)) }) } } diff --git a/internal/export/writer.go b/internal/export/writer.go index 9c2b893..4832cf6 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -36,49 +36,49 @@ type File struct { } type categoryFile struct { - name string - file *os.File - buf *bufio.Writer - enc encoder - count int + name string + file *os.File + buffered *bufio.Writer + encoder encoder + count int } // NewWriter creates dir. With compress, Close packs the files it wrote into /.zip. -func NewWriter(dir string, f Format, compress bool) (*Writer, error) { +func NewWriter(dir string, format Format, compress bool) (*Writer, error) { if err := os.MkdirAll(dir, 0o750); err != nil { return nil, fmt.Errorf("create output dir: %w", err) } - return &Writer{dir: dir, format: f, compress: compress, files: make(map[category.Category]*categoryFile)}, nil + return &Writer{dir: dir, format: format, compress: compress, files: make(map[category.Category]*categoryFile)}, nil } // Write reorders records in place. -func (w *Writer) Write(c category.Category, records []record.Record) error { - if err := w.write(c, records); err != nil { +func (w *Writer) Write(dataCategory category.Category, records []record.Record) error { + if err := w.write(dataCategory, records); err != nil { w.failed = true return err } return nil } -func (w *Writer) write(c category.Category, records []record.Record) error { +func (w *Writer) write(dataCategory category.Category, records []record.Record) error { if len(records) == 0 { return nil } - for _, r := range records { - if r.Category() != c { - return fmt.Errorf("%T is not a %s record", r, c) + for _, row := range records { + if row.Category() != dataCategory { + return fmt.Errorf("%T is not a %s record", row, dataCategory) } } - cf, err := w.open(c) + file, err := w.open(dataCategory) if err != nil { return err } sortRecords(records) - for _, r := range records { - if err := cf.enc.encode(r); err != nil { - return fmt.Errorf("write %s: %w", cf.name, err) + for _, row := range records { + if err := file.encoder.encode(row); err != nil { + return fmt.Errorf("write %s: %w", file.name, err) } - cf.count++ + file.count++ } return nil } @@ -89,10 +89,10 @@ func (w *Writer) Close() error { errs []error files []File ) - for _, c := range category.All() { - if cf, ok := w.files[c]; ok { - errs = append(errs, cf.close()) - files = append(files, File{Name: cf.name, Count: cf.count}) + for _, dataCategory := range category.All() { + if file, ok := w.files[dataCategory]; ok { + errs = append(errs, file.close()) + files = append(files, File{Name: file.name, Count: file.count}) } } if err := errors.Join(errs...); err != nil { @@ -121,8 +121,8 @@ func (w *Writer) Output() Output { // pack removes the loose files only after the zip is in place, so a failure leaves every one of them where it was. func (w *Writer) pack() error { names := make([]string, 0, len(w.files)) - for _, cf := range w.files { - names = append(names, cf.name) + for _, file := range w.files { + names = append(names, file.name) } sort.Strings(names) zipName := filepath.Base(w.dir) + ".zip" @@ -138,68 +138,68 @@ func (w *Writer) pack() error { return nil } -// writeZip renames a finished temp file into place, so dst is never a partial zip. -func writeZip(dst, dir string, names []string) (err error) { - tmp, err := os.OpenFile(dst+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) +// writeZip renames a finished temp file into place, so archivePath is never a partial zip. +func writeZip(archivePath, dir string, names []string) (err error) { + temporary, err := os.OpenFile(archivePath+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { - return fmt.Errorf("create %s: %w", dst, err) + return fmt.Errorf("create %s: %w", archivePath, err) } defer func() { if err != nil { - err = errors.Join(err, os.Remove(tmp.Name())) + err = errors.Join(err, os.Remove(temporary.Name())) } }() - zw := zip.NewWriter(tmp) + zipWriter := zip.NewWriter(temporary) for _, name := range names { - if err := addZipFile(zw, filepath.Join(dir, name), name); err != nil { - return errors.Join(fmt.Errorf("add %s: %w", name, err), zw.Close(), tmp.Close()) + if err := addZipFile(zipWriter, filepath.Join(dir, name), name); err != nil { + return errors.Join(fmt.Errorf("add %s: %w", name, err), zipWriter.Close(), temporary.Close()) } } - if err := zw.Close(); err != nil { - return errors.Join(fmt.Errorf("finish %s: %w", dst, err), tmp.Close()) + if err := zipWriter.Close(); err != nil { + return errors.Join(fmt.Errorf("finish %s: %w", archivePath, err), temporary.Close()) } - if err := tmp.Close(); err != nil { - return fmt.Errorf("finish %s: %w", dst, err) + if err := temporary.Close(); err != nil { + return fmt.Errorf("finish %s: %w", archivePath, err) } - if err := os.Rename(tmp.Name(), dst); err != nil { + if err := os.Rename(temporary.Name(), archivePath); err != nil { return fmt.Errorf("move zip into place: %w", err) } return nil } -func addZipFile(zw *zip.Writer, path, name string) error { - src, err := os.Open(path) +func addZipFile(zipWriter *zip.Writer, path, name string) error { + file, err := os.Open(path) if err != nil { return err } - defer src.Close() - dst, err := zw.Create(name) + defer file.Close() + entryWriter, err := zipWriter.Create(name) if err != nil { return err } - _, err = io.Copy(dst, src) + _, err = io.Copy(entryWriter, file) return err } -func (w *Writer) open(c category.Category) (*categoryFile, error) { - if cf, ok := w.files[c]; ok { - return cf, nil +func (w *Writer) open(dataCategory category.Category) (*categoryFile, error) { + if existing, ok := w.files[dataCategory]; ok { + return existing, nil } - name := c.String() + "." + w.format.ext() - f, err := os.OpenFile(filepath.Join(w.dir, name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) + name := dataCategory.String() + "." + w.format.ext() + file, err := os.OpenFile(filepath.Join(w.dir, name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) if err != nil { return nil, fmt.Errorf("create %s: %w", name, err) } - buf := bufio.NewWriter(f) - cf := &categoryFile{name: name, file: f, buf: buf, enc: newEncoder(buf, w.format, c)} - w.files[c] = cf - return cf, nil + buffered := bufio.NewWriter(file) + opened := &categoryFile{name: name, file: file, buffered: buffered, encoder: newEncoder(buffered, w.format, dataCategory)} + w.files[dataCategory] = opened + return opened, nil } func (cf *categoryFile) close() error { - err := cf.enc.end() + err := cf.encoder.end() if err == nil { - err = cf.buf.Flush() + err = cf.buffered.Flush() } if err = errors.Join(err, cf.file.Close()); err != nil { return fmt.Errorf("write %s: %w", cf.name, err) diff --git a/internal/export/writer_test.go b/internal/export/writer_test.go index d20884e..aad3d0e 100644 --- a/internal/export/writer_test.go +++ b/internal/export/writer_test.go @@ -24,8 +24,8 @@ import ( var testTime = time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC) type extraction struct { - c category.Category - records []record.Record + dataCategory category.Category + records []record.Record } func chromeExtractions() []extraction { @@ -61,37 +61,37 @@ func firefoxExtractions() []extraction { } } -func writeAll(t *testing.T, dir string, f Format, extractions ...extraction) { +func writeAll(t *testing.T, dir string, format Format, extractions ...extraction) { t.Helper() - w, err := NewWriter(dir, f, false) + writer, err := NewWriter(dir, format, false) require.NoError(t, err) - for _, e := range extractions { - require.NoError(t, w.Write(e.c, e.records)) + for _, batch := range extractions { + require.NoError(t, writer.Write(batch.dataCategory, batch.records)) } - require.NoError(t, w.Close()) + require.NoError(t, writer.Close()) } func TestParseFormat(t *testing.T) { tests := []struct { - in string - want Format + input string + want Format }{ {"json", JSON}, {"csv", CSV}, {"cookie-editor", CookieEditor}, } - for _, tt := range tests { - got, err := ParseFormat(tt.in) + for _, testCase := range tests { + got, err := ParseFormat(testCase.input) require.NoError(t, err) - assert.Equal(t, tt.want, got) + assert.Equal(t, testCase.want, got) } _, err := ParseFormat("unknown") require.EqualError(t, err, "unsupported format: unknown") } func TestFormat_ZeroIsJSON(t *testing.T) { - var f Format - assert.Equal(t, JSON, f) + var format Format + assert.Equal(t, JSON, format) } func TestNewWriter_CreatesDir(t *testing.T) { @@ -291,10 +291,10 @@ func TestWrite_AppendsExtractionsInWriteOrder(t *testing.T) { func TestWrite_RejectsRecordOfAnotherCategory(t *testing.T) { dir := t.TempDir() - w, err := NewWriter(dir, JSON, false) + writer, err := NewWriter(dir, JSON, false) require.NoError(t, err) - require.EqualError(t, w.Write(category.Cookie, []record.Record{&record.Login{}}), "*record.Login is not a cookie record") - require.NoError(t, w.Close()) + require.EqualError(t, writer.Write(category.Cookie, []record.Record{&record.Login{}}), "*record.Login is not a cookie record") + require.NoError(t, writer.Close()) entries, err := os.ReadDir(dir) require.NoError(t, err) @@ -303,13 +303,13 @@ func TestWrite_RejectsRecordOfAnotherCategory(t *testing.T) { func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) { dir := t.TempDir() - w, err := NewWriter(dir, JSON, false) + writer, err := NewWriter(dir, JSON, false) require.NoError(t, err) - require.NoError(t, w.Write(category.Password, []record.Record{&record.Login{URL: "https://kept.example"}})) + require.NoError(t, writer.Write(category.Password, []record.Record{&record.Login{URL: "https://kept.example"}})) beyondJSON := time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC) - require.Error(t, w.Write(category.Cookie, []record.Record{&record.Cookie{Host: "bad.example", ExpireAt: beyondJSON}})) - require.NoError(t, w.Close()) + require.Error(t, writer.Write(category.Cookie, []record.Record{&record.Cookie{Host: "bad.example", ExpireAt: beyondJSON}})) + require.NoError(t, writer.Close()) var logins []record.Login readJSON(t, filepath.Join(dir, "password.json"), &logins) @@ -319,20 +319,20 @@ func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) { var cookies []record.Cookie readJSON(t, filepath.Join(dir, "cookie.json"), &cookies) assert.Empty(t, cookies) - assert.Zero(t, w.Output(), "a failed run lists nothing") + assert.Zero(t, writer.Output(), "a failed run lists nothing") } func TestClose_OutputListsTheFilesInCategoryOrder(t *testing.T) { dir := t.TempDir() - w, err := NewWriter(dir, JSON, false) + writer, err := NewWriter(dir, JSON, false) require.NoError(t, err) - require.NoError(t, w.Write(category.History, []record.Record{&record.History{URL: "https://a.example"}})) - require.NoError(t, w.Write(category.Password, []record.Record{ + require.NoError(t, writer.Write(category.History, []record.Record{&record.History{URL: "https://a.example"}})) + require.NoError(t, writer.Write(category.Password, []record.Record{ &record.Login{URL: "https://b.example"}, &record.Login{URL: "https://c.example"}, })) - require.NoError(t, w.Close()) + require.NoError(t, writer.Close()) - assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.json", Count: 2}, {Name: "history.json", Count: 1}}}, w.Output()) + assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.json", Count: 2}, {Name: "history.json", Count: 1}}}, writer.Output()) } func TestClose_ZipReplacesTheFilesWithOneArchive(t *testing.T) { @@ -346,7 +346,7 @@ func TestClose_ZipReplacesTheFilesWithOneArchive(t *testing.T) { assert.Equal(t, dirFiles(t, loose), zipFiles(t, filepath.Join(dir, "results.zip"))) } -// The output is the files this run wrote; anything else in the directory is not the writer's to pack or delete. +// TestClose_ZipLeavesOtherFilesAlone packs only this run's files; the rest of the directory is not the writer's. func TestClose_ZipLeavesOtherFilesAlone(t *testing.T) { dir := filepath.Join(t.TempDir(), "results") require.NoError(t, os.MkdirAll(dir, 0o755)) @@ -368,15 +368,15 @@ func TestClose_ZipFailureKeepsTheFiles(t *testing.T) { func TestClose_ZipOutputNamesTheArchive(t *testing.T) { dir := filepath.Join(t.TempDir(), "results") - w, err := NewWriter(dir, CSV, true) + writer, err := NewWriter(dir, CSV, true) require.NoError(t, err) - require.NoError(t, w.Write(category.Password, []record.Record{&record.Login{URL: "https://a.example"}})) - require.NoError(t, w.Close()) + require.NoError(t, writer.Write(category.Password, []record.Record{&record.Login{URL: "https://a.example"}})) + require.NoError(t, writer.Close()) - assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.csv", Count: 1}}, Zip: "results.zip"}, w.Output()) + assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.csv", Count: 1}}, Zip: "results.zip"}, writer.Output()) } -// The zip holds the same records as the category files, so it gets their owner-only mode. +// TestClose_ZipIsOwnerOnly gives the zip the category files' owner-only mode, since it holds the same records. func TestClose_ZipIsOwnerOnly(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Windows has no mode bits to check") @@ -396,16 +396,16 @@ func TestClose_ZipWithNothingWrittenFails(t *testing.T) { } func zipAll(dir string, extractions ...extraction) error { - w, err := NewWriter(dir, CSV, true) + writer, err := NewWriter(dir, CSV, true) if err != nil { return err } - for _, e := range extractions { - if err := w.Write(e.c, e.records); err != nil { - return errors.Join(err, w.Close()) + for _, batch := range extractions { + if err := writer.Write(batch.dataCategory, batch.records); err != nil { + return errors.Join(err, writer.Close()) } } - return w.Close() + return writer.Close() } func dirNames(t *testing.T, dir string) []string { @@ -413,8 +413,8 @@ func dirNames(t *testing.T, dir string) []string { entries, err := os.ReadDir(dir) require.NoError(t, err) names := make([]string, 0, len(entries)) - for _, e := range entries { - names = append(names, e.Name()) + for _, entry := range entries { + names = append(names, entry.Name()) } return names } @@ -432,16 +432,16 @@ func dirFiles(t *testing.T, dir string) map[string]string { func zipFiles(t *testing.T, path string) map[string]string { t.Helper() - r, err := zip.OpenReader(path) + zipReader, err := zip.OpenReader(path) require.NoError(t, err) - defer r.Close() - files := make(map[string]string, len(r.File)) - for _, f := range r.File { - rc, err := f.Open() + defer zipReader.Close() + files := make(map[string]string, len(zipReader.File)) + for _, zipFile := range zipReader.File { + entryReader, err := zipFile.Open() require.NoError(t, err) - data, err := io.ReadAll(rc) - require.NoError(t, errors.Join(err, rc.Close())) - files[f.Name] = string(data) + data, err := io.ReadAll(entryReader) + require.NoError(t, errors.Join(err, entryReader.Close())) + files[zipFile.Name] = string(data) } return files } @@ -460,9 +460,9 @@ func readCSV(t *testing.T, path string) [][]string { return records } -func readJSON(t *testing.T, path string, v any) { +func readJSON(t *testing.T, path string, value any) { t.Helper() raw, err := os.ReadFile(path) require.NoError(t, err) - require.NoError(t, json.Unmarshal(raw, v)) + require.NoError(t, json.Unmarshal(raw, value)) } diff --git a/internal/golden/golden.go b/internal/golden/golden.go index 9159e85..8644155 100644 --- a/internal/golden/golden.go +++ b/internal/golden/golden.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/require" ) -// An env var, not a test flag, reaches every package of go test ./... and, read at test time, keys its cache. +// updateEnv is an env var rather than a flag, so every package sees it and, read at test time, it keys the test cache. const updateEnv = "HBD_UPDATE_GOLDEN" const dir = "testdata" @@ -43,26 +43,26 @@ func Bundle(t testing.TB, dir string) string { entries, err := os.ReadDir(dir) require.NoError(t, err) names := make([]string, 0, len(entries)) - for _, e := range entries { - require.Truef(t, e.Type().IsRegular(), "unexpected non-regular entry %s in %s", e.Name(), dir) - names = append(names, e.Name()) + for _, entry := range entries { + require.Truef(t, entry.Type().IsRegular(), "unexpected non-regular entry %s in %s", entry.Name(), dir) + names = append(names, entry.Name()) } return BundleFiles(t, dir, names...) } func BundleFiles(t testing.TB, dir string, names ...string) string { t.Helper() - var b strings.Builder + var builder strings.Builder for _, name := range names { data, err := os.ReadFile(filepath.Join(dir, name)) require.NoError(t, err) - fmt.Fprintf(&b, "-- %s (%d bytes) --\n", name, len(data)) - b.Write(data) + fmt.Fprintf(&builder, "-- %s (%d bytes) --\n", name, len(data)) + builder.Write(data) if len(data) > 0 && data[len(data)-1] != '\n' { - b.WriteByte('\n') + builder.WriteByte('\n') } } - return b.String() + return builder.String() } func DirFiles(t testing.TB, dir string) map[string]string { @@ -70,15 +70,15 @@ func DirFiles(t testing.TB, dir string) map[string]string { entries, err := os.ReadDir(dir) require.NoError(t, err) files := make(map[string]string, len(entries)) - for _, e := range entries { - data, err := os.ReadFile(filepath.Join(dir, e.Name())) + for _, entry := range entries { + data, err := os.ReadFile(filepath.Join(dir, entry.Name())) require.NoError(t, err) - files[e.Name()] = string(data) + files[entry.Name()] = string(data) } return files } -// Cookie-Editor writes its own format for cookies only, so every other file must match the json output. +// AssertJSONFallback checks every file but cookie.json against the json output: Cookie-Editor formats only cookies. func AssertJSONFallback(t testing.TB, cookieEditorDir, jsonDir string) { t.Helper() got, want := DirFiles(t, cookieEditorDir), DirFiles(t, jsonDir) @@ -90,13 +90,13 @@ func AssertJSONFallback(t testing.TB, cookieEditorDir, jsonDir string) { func ZipListing(t testing.TB, path string) string { t.Helper() - r, err := zip.OpenReader(path) + zipReader, err := zip.OpenReader(path) require.NoError(t, err) - defer r.Close() - var b strings.Builder - for _, f := range r.File { - fmt.Fprintf(&b, "%s method=%d modified=%s size=%d crc32=%08x\n", - f.Name, f.Method, f.Modified.UTC().Format(time.RFC3339), f.UncompressedSize64, f.CRC32) + defer zipReader.Close() + var builder strings.Builder + for _, zipFile := range zipReader.File { + fmt.Fprintf(&builder, "%s method=%d modified=%s size=%d crc32=%08x\n", + zipFile.Name, zipFile.Method, zipFile.Modified.UTC().Format(time.RFC3339), zipFile.UncompressedSize64, zipFile.CRC32) } - return b.String() + return builder.String() } diff --git a/internal/keychain/keychain_darwin.go b/internal/keychain/keychain_darwin.go index e9a1db2..318ca70 100644 --- a/internal/keychain/keychain_darwin.go +++ b/internal/keychain/keychain_darwin.go @@ -23,7 +23,7 @@ type Keychain struct { password PasswordFunc openOnce sync.Once - kc *keychainbreaker.Keychain + opened *keychainbreaker.Keychain err error genericOnce sync.Once @@ -40,21 +40,21 @@ func (k *Keychain) GenericPassword(ctx context.Context, account string) ([]byte, if err := k.open(ctx); err != nil { return nil, err } - if !k.kc.Unlocked() { + if !k.opened.Unlocked() { if k.err != nil { return nil, k.err } return nil, ErrLocked } k.genericOnce.Do(func() { - k.generic, k.genericErr = k.kc.GenericPasswords() + k.generic, k.genericErr = k.opened.GenericPasswords() }) if k.genericErr != nil { return nil, fmt.Errorf("read generic passwords: %w", k.genericErr) } - for _, rec := range k.generic { - if rec.Account == account { - return rec.Password, nil + for _, genericPassword := range k.generic { + if genericPassword.Account == account { + return genericPassword.Password, nil } } return nil, fmt.Errorf("%q: %w", account, errNotFound) @@ -65,7 +65,7 @@ func (k *Keychain) InternetPasswords(ctx context.Context) ([]keychainbreaker.Int if err := k.open(ctx); err != nil { return nil, err } - passwords, err := k.kc.InternetPasswords() + passwords, err := k.opened.InternetPasswords() if err != nil { return nil, fmt.Errorf("read internet passwords: %w", err) } @@ -79,15 +79,15 @@ func (k *Keychain) Err() error { func (k *Keychain) open(ctx context.Context) error { k.openOnce.Do(func() { - kc, err := keychainbreaker.Open(keychainbreaker.WithFile(k.path)) + opened, err := keychainbreaker.Open(keychainbreaker.WithFile(k.path)) if err != nil { k.err = fmt.Errorf("open login keychain: %w", err) return } - k.kc = kc + k.opened = opened k.err = k.unlock(ctx) }) - if k.kc == nil { + if k.opened == nil { return k.err } return nil @@ -97,18 +97,18 @@ func (k *Keychain) open(ctx context.Context) error { func (k *Keychain) unlock(ctx context.Context) error { password, err := k.password(ctx) if err != nil { - if tryErr := k.kc.TryUnlock(); tryErr != nil { + if tryErr := k.opened.TryUnlock(); tryErr != nil { return fmt.Errorf("%w: read password: %w", ErrLocked, errors.Join(err, tryErr)) } return fmt.Errorf("%w: read password: %w", ErrLocked, err) } if password == "" { - if err := k.kc.TryUnlock(); err != nil { + if err := k.opened.TryUnlock(); err != nil { return fmt.Errorf("%w: %w", ErrLocked, err) } return ErrLocked } - if err := k.kc.TryUnlock(keychainbreaker.WithPassword(password)); err != nil { + if err := k.opened.TryUnlock(keychainbreaker.WithPassword(password)); err != nil { return fmt.Errorf("%w: %w", ErrLocked, err) } return nil diff --git a/internal/keychain/keychain_darwin_test.go b/internal/keychain/keychain_darwin_test.go index df6e796..65b9f92 100644 --- a/internal/keychain/keychain_darwin_test.go +++ b/internal/keychain/keychain_darwin_test.go @@ -10,26 +10,26 @@ import ( ) func TestNew_NeitherOpensNorPrompts(t *testing.T) { - kc := New(filepath.Join(t.TempDir(), "login.keychain-db"), func(context.Context) (string, error) { + loginKeychain := New(filepath.Join(t.TempDir(), "login.keychain-db"), func(context.Context) (string, error) { t.Fatal("building a keychain handle must not ask for the password") return "", nil }) - assert.NoError(t, kc.Err(), "a keychain that was never used has no error") + assert.NoError(t, loginKeychain.Err(), "a keychain that was never used has no error") } -// An unreadable keychain fails before any prompt, once, and every query reports the same reason. +// TestOpenFailure_IsReportedOnceWithoutPrompting fails an unreadable keychain once, before any prompt, for every query. func TestOpenFailure_IsReportedOnceWithoutPrompting(t *testing.T) { prompts := 0 - kc := New(filepath.Join(t.TempDir(), "missing.keychain-db"), func(context.Context) (string, error) { + loginKeychain := New(filepath.Join(t.TempDir(), "missing.keychain-db"), func(context.Context) (string, error) { prompts++ return "secret", nil }) - _, err := kc.GenericPassword(context.Background(), "Chrome Safe Storage") + _, err := loginKeychain.GenericPassword(context.Background(), "Chrome Safe Storage") require.ErrorContains(t, err, "open login keychain") - _, err2 := kc.InternetPasswords(context.Background()) - require.Equal(t, err, err2) + _, secondErr := loginKeychain.InternetPasswords(context.Background()) + require.Equal(t, err, secondErr) - assert.Equal(t, err, kc.Err()) + assert.Equal(t, err, loginKeychain.Err()) assert.Zero(t, prompts) } diff --git a/internal/log/logger.go b/internal/log/logger.go index ddef68f..4b47d53 100644 --- a/internal/log/logger.go +++ b/internal/log/logger.go @@ -24,25 +24,25 @@ type Logger struct { minLevel Level } -func (l *Logger) canLogAt(v Level) bool { - return v >= Level(atomic.LoadInt32((*int32)(&l.minLevel))) +func (l *Logger) canLogAt(level Level) bool { + return level >= Level(atomic.LoadInt32((*int32)(&l.minLevel))) } -func (l *Logger) SetLevel(v Level) { - if v < DebugLevel || v > WarnLevel { +func (l *Logger) SetLevel(level Level) { + if level < DebugLevel || level > WarnLevel { panic("log: invalid log level") } - atomic.StoreInt32((*int32)(&l.minLevel), int32(v)) + atomic.StoreInt32((*int32)(&l.minLevel), int32(level)) } -// Frames between runtime.Caller and the caller: base.Log, logMsg, and the exported Debugf/Infof/Warnf. +// baseCallerSkip skips the frames between runtime.Caller and the caller: base.Log, logMsg, and Debugf/Infof/Warnf. const baseCallerSkip = 3 -func (l *Logger) logMsg(lvl Level, msg string) { - if !l.canLogAt(lvl) { +func (l *Logger) logMsg(level Level, message string) { + if !l.canLogAt(level) { return } - l.base.Log(baseCallerSkip, lvl, msg) + l.base.Log(baseCallerSkip, level, message) } func (l *Logger) Debugf(format string, args ...any) { @@ -62,8 +62,8 @@ type Base interface { } type baseLogger struct { - out io.Writer - mu sync.Mutex + out io.Writer + mutex sync.Mutex } func newBase(out io.Writer) *baseLogger { @@ -73,32 +73,32 @@ func newBase(out io.Writer) *baseLogger { // continuation lines a message's later lines up under its first, past the "[DBG] " label. const continuation = " " -func (l *baseLogger) Log(callerSkip int, lvl Level, msg string) { - msg = strings.TrimRight(msg, "\n") - if strings.Contains(msg, "\n") { - msg = strings.ReplaceAll(msg, "\n", "\n"+continuation) +func (l *baseLogger) Log(callerSkip int, level Level, message string) { + message = strings.TrimRight(message, "\n") + if strings.Contains(message, "\n") { + message = strings.ReplaceAll(message, "\n", "\n"+continuation) } - label := l.formatLabel(lvl) + label := l.formatLabel(level) var line string - if lvl == DebugLevel { - _, file, num, ok := runtime.Caller(callerSkip) + if level == DebugLevel { + _, file, lineNumber, ok := runtime.Caller(callerSkip) if ok { file = filepath.Base(file) } else { file = "???" - num = 0 + lineNumber = 0 } - line = fmt.Sprintf("%s %s:%d: %s\n", label, file, num, msg) + line = fmt.Sprintf("%s %s:%d: %s\n", label, file, lineNumber, message) } else { - line = fmt.Sprintf("%s %s\n", label, msg) + line = fmt.Sprintf("%s %s\n", label, message) } - l.mu.Lock() + l.mutex.Lock() _, _ = io.WriteString(l.out, line) - l.mu.Unlock() + l.mutex.Unlock() } -func (l *baseLogger) formatLabel(lvl Level) string { - return "[" + lvl.String() + "]" +func (l *baseLogger) formatLabel(level Level) string { + return "[" + level.String() + "]" } diff --git a/internal/log/logger_test.go b/internal/log/logger_test.go index 64127ab..2f6a525 100644 --- a/internal/log/logger_test.go +++ b/internal/log/logger_test.go @@ -30,50 +30,50 @@ var baseTestCases = []baseTestCase{ } func TestLoggerDebug(t *testing.T) { - for _, tc := range baseTestCases { - tc := tc - tc.level = DebugLevel - message := tc.message + tc.suffix - tc.wantedPattern = fmt.Sprintf(`^\[DBG\] \w+\.go:\d+: %s\n$`, tc.message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + for _, testCase := range baseTestCases { + testCase := testCase + testCase.level = DebugLevel + message := testCase.message + testCase.suffix + testCase.wantedPattern = fmt.Sprintf(`^\[DBG\] \w+\.go:\d+: %s\n$`, testCase.message) + t.Run(testCase.description, func(t *testing.T) { + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.SetLevel(DebugLevel) logger.Debugf("%s", message) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) + got := buffer.String() + assert.Regexp(t, testCase.wantedPattern, got) }) } } func TestLoggerInfo(t *testing.T) { - for _, tc := range baseTestCases { - tc := tc - tc.level = InfoLevel - message := tc.message + tc.suffix - tc.wantedPattern = fmt.Sprintf(`^\[INF\] %s\n$`, tc.message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + for _, testCase := range baseTestCases { + testCase := testCase + testCase.level = InfoLevel + message := testCase.message + testCase.suffix + testCase.wantedPattern = fmt.Sprintf(`^\[INF\] %s\n$`, testCase.message) + t.Run(testCase.description, func(t *testing.T) { + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.Infof("%s", message) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) + got := buffer.String() + assert.Regexp(t, testCase.wantedPattern, got) }) } } func TestLoggerWarn(t *testing.T) { - for _, tc := range baseTestCases { - tc := tc - tc.level = WarnLevel - message := tc.message + tc.suffix - tc.wantedPattern = fmt.Sprintf(`^\[WRN\] %s\n$`, tc.message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + for _, testCase := range baseTestCases { + testCase := testCase + testCase.level = WarnLevel + message := testCase.message + testCase.suffix + testCase.wantedPattern = fmt.Sprintf(`^\[WRN\] %s\n$`, testCase.message) + t.Run(testCase.description, func(t *testing.T) { + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.Warnf("%s", message) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) + got := buffer.String() + assert.Regexp(t, testCase.wantedPattern, got) }) } } @@ -105,50 +105,50 @@ var formatTestCases = []formatTestCase{ } func TestLoggerDebugf(t *testing.T) { - for _, tc := range formatTestCases { - tc := tc - tc.level = DebugLevel - message := fmt.Sprintf(tc.format, tc.args...) - tc.wantedPattern = fmt.Sprintf(`^\[DBG\] \w+\.go:\d+: %s\n$`, message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + for _, testCase := range formatTestCases { + testCase := testCase + testCase.level = DebugLevel + message := fmt.Sprintf(testCase.format, testCase.args...) + testCase.wantedPattern = fmt.Sprintf(`^\[DBG\] \w+\.go:\d+: %s\n$`, message) + t.Run(testCase.description, func(t *testing.T) { + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.SetLevel(DebugLevel) - logger.Debugf(tc.format, tc.args...) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) + logger.Debugf(testCase.format, testCase.args...) + got := buffer.String() + assert.Regexp(t, testCase.wantedPattern, got) }) } } func TestLoggerInfof(t *testing.T) { - for _, tc := range formatTestCases { - tc := tc - tc.level = InfoLevel - message := fmt.Sprintf(tc.format, tc.args...) - tc.wantedPattern = fmt.Sprintf(`^\[INF\] %s\n$`, message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) - logger.Infof(tc.format, tc.args...) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) + for _, testCase := range formatTestCases { + testCase := testCase + testCase.level = InfoLevel + message := fmt.Sprintf(testCase.format, testCase.args...) + testCase.wantedPattern = fmt.Sprintf(`^\[INF\] %s\n$`, message) + t.Run(testCase.description, func(t *testing.T) { + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) + logger.Infof(testCase.format, testCase.args...) + got := buffer.String() + assert.Regexp(t, testCase.wantedPattern, got) }) } } func TestLoggerWarnf(t *testing.T) { - for _, tc := range formatTestCases { - tc := tc - tc.level = WarnLevel - message := fmt.Sprintf(tc.format, tc.args...) - tc.wantedPattern = fmt.Sprintf(`^\[WRN\] %s\n$`, message) - t.Run(tc.description, func(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) - logger.Warnf(tc.format, tc.args...) - got := buf.String() - assert.Regexp(t, tc.wantedPattern, got) + for _, testCase := range formatTestCases { + testCase := testCase + testCase.level = WarnLevel + message := fmt.Sprintf(testCase.format, testCase.args...) + testCase.wantedPattern = fmt.Sprintf(`^\[WRN\] %s\n$`, message) + t.Run(testCase.description, func(t *testing.T) { + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) + logger.Warnf(testCase.format, testCase.args...) + got := buffer.String() + assert.Regexp(t, testCase.wantedPattern, got) }) } } @@ -156,65 +156,65 @@ func TestLoggerWarnf(t *testing.T) { func TestLoggerWithLowerLevels(t *testing.T) { levels := []Level{DebugLevel, InfoLevel, WarnLevel} ops := []struct { - op string + name string level Level logFunc func(*Logger) }{ - {"Debugf", DebugLevel, func(l *Logger) { l.Debugf("hello") }}, - {"Infof", InfoLevel, func(l *Logger) { l.Infof("hello") }}, - {"Warnf", WarnLevel, func(l *Logger) { l.Warnf("hello") }}, + {"Debugf", DebugLevel, func(logger *Logger) { logger.Debugf("hello") }}, + {"Infof", InfoLevel, func(logger *Logger) { logger.Infof("hello") }}, + {"Warnf", WarnLevel, func(logger *Logger) { logger.Warnf("hello") }}, } for _, setLevel := range levels { - for _, op := range ops { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + for _, operation := range ops { + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.SetLevel(setLevel) - expectedOutput := op.level >= setLevel - op.logFunc(logger) + expectedOutput := operation.level >= setLevel + operation.logFunc(logger) - output := buf.String() + output := buffer.String() if expectedOutput { - assert.NotEmpty(t, output, "setLevel=%s op=%s should produce output", setLevel, op.op) + assert.NotEmpty(t, output, "setLevel=%s op=%s should produce output", setLevel, operation.name) } else { - assert.Empty(t, output, "setLevel=%s op=%s should be suppressed", setLevel, op.op) + assert.Empty(t, output, "setLevel=%s op=%s should be suppressed", setLevel, operation.name) } } } } func TestDefaultLevelIsInfo(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.Debugf("debug msg") - assert.Empty(t, buf.String(), "Debug should be suppressed at default InfoLevel") + assert.Empty(t, buffer.String(), "Debug should be suppressed at default InfoLevel") logger.Infof("info msg") - assert.Contains(t, buf.String(), "info msg") + assert.Contains(t, buffer.String(), "info msg") } func TestDebugIncludesFileLine(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.SetLevel(DebugLevel) logger.Debugf("test location") - got := buf.String() + got := buffer.String() assert.Regexp(t, `^\[DBG\] logger_test\.go:\d+: test location\n$`, got) } func TestInfoHasLabel(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.Infof("clean message") - assert.Equal(t, "[INF] clean message\n", buf.String()) + assert.Equal(t, "[INF] clean message\n", buffer.String()) } func TestMultilineMessageIndented(t *testing.T) { - var buf bytes.Buffer - logger := NewLogger(newBase(&buf)) + var buffer bytes.Buffer + logger := NewLogger(newBase(&buffer)) logger.Warnf("line1\nline2\nline3") - got := buf.String() + got := buffer.String() assert.Equal(t, "[WRN] line1\n line2\n line3\n", got) } diff --git a/internal/masterkey/dump.go b/internal/masterkey/dump.go index 7ba2f7d..977b149 100644 --- a/internal/masterkey/dump.go +++ b/internal/masterkey/dump.go @@ -28,7 +28,7 @@ type Host struct { User string `json:"user,omitempty"` } -// Kind names the engine, so a consumer can read a vault without the browser in its own table. +// Vault names its engine in Kind, so a consumer can read a vault without the browser in its own table. type Vault struct { Browser string `json:"browser"` // ID names a second user data dir of the same browser ("arc-2"); the first one's is Browser, so it is left out. @@ -49,34 +49,34 @@ func NewDump() Dump { } func currentHost() Host { - h := Host{OS: runtime.GOOS, Arch: runtime.GOARCH} + host := Host{OS: runtime.GOOS, Arch: runtime.GOARCH} if name, err := os.Hostname(); err == nil { - h.Hostname = name + host.Hostname = name } - if u, err := user.Current(); err == nil { - h.User = u.Username + if currentUser, err := user.Current(); err == nil { + host.User = currentUser.Username } - return h + return host } -func (d Dump) WriteJSON(w io.Writer) error { - enc := json.NewEncoder(w) - enc.SetIndent("", " ") - if err := enc.Encode(d); err != nil { +func (d Dump) WriteJSON(writer io.Writer) error { + encoder := json.NewEncoder(writer) + encoder.SetIndent("", " ") + if err := encoder.Encode(d); err != nil { return fmt.Errorf("encode dump: %w", err) } return nil } // ReadJSON rejects a version it cannot interpret, since a silent misparse is worse than an error. -func ReadJSON(r io.Reader) (Dump, error) { - var d Dump - dec := json.NewDecoder(r) - if err := dec.Decode(&d); err != nil { +func ReadJSON(reader io.Reader) (Dump, error) { + var dump Dump + decoder := json.NewDecoder(reader) + if err := decoder.Decode(&dump); err != nil { return Dump{}, fmt.Errorf("decode dump: %w", err) } - if d.Version != DumpVersion { - return Dump{}, fmt.Errorf("unsupported dump version %q (this build expects %q)", d.Version, DumpVersion) + if dump.Version != DumpVersion { + return Dump{}, fmt.Errorf("unsupported dump version %q (this build expects %q)", dump.Version, DumpVersion) } - return d, nil + return dump, nil } diff --git a/internal/masterkey/dump_test.go b/internal/masterkey/dump_test.go index 8c34cf4..221216d 100644 --- a/internal/masterkey/dump_test.go +++ b/internal/masterkey/dump_test.go @@ -26,12 +26,12 @@ func TestReadJSON_RejectsMissingVersion(t *testing.T) { } func TestReadJSON_AcceptsCurrentVersion(t *testing.T) { - d := NewDump() - var buf bytes.Buffer - if err := d.WriteJSON(&buf); err != nil { + dump := NewDump() + var buffer bytes.Buffer + if err := dump.WriteJSON(&buffer); err != nil { t.Fatalf("WriteJSON: %v", err) } - parsed, err := ReadJSON(&buf) + parsed, err := ReadJSON(&buffer) if err != nil { t.Fatalf("ReadJSON: %v", err) } @@ -41,8 +41,8 @@ func TestReadJSON_AcceptsCurrentVersion(t *testing.T) { } func TestDump_VaultKindRoundTrip(t *testing.T) { - d := NewDump() - d.Vaults = append(d.Vaults, Vault{ + dump := NewDump() + dump.Vaults = append(dump.Vaults, Vault{ Browser: "chrome", Kind: "chromium", UserDataDir: "/p", @@ -50,11 +50,11 @@ func TestDump_VaultKindRoundTrip(t *testing.T) { Keys: Set{V10: []byte{0x01}}, }) - var buf bytes.Buffer - if err := d.WriteJSON(&buf); err != nil { + var buffer bytes.Buffer + if err := dump.WriteJSON(&buffer); err != nil { t.Fatalf("WriteJSON: %v", err) } - parsed, err := ReadJSON(&buf) + parsed, err := ReadJSON(&buffer) if err != nil { t.Fatalf("ReadJSON: %v", err) } @@ -69,17 +69,17 @@ func TestDump_VaultKindRoundTrip(t *testing.T) { } } -// keys.json is a frozen format: present versions only, in key order, and {} for a vault without keys. +// TestDump_KeysWireForm pins the frozen keys.json form: present versions only, in key order, {} for no keys. func TestDump_KeysWireForm(t *testing.T) { - d := Dump{Version: DumpVersion, Vaults: []Vault{ + dump := Dump{Version: DumpVersion, Vaults: []Vault{ {Browser: "chrome", Keys: Set{V20: []byte{0x20}, V10: []byte{0x10}}}, {Browser: "opera", Keys: Set{}}, }} - var buf bytes.Buffer - if err := d.WriteJSON(&buf); err != nil { + var buffer bytes.Buffer + if err := dump.WriteJSON(&buffer); err != nil { t.Fatalf("WriteJSON: %v", err) } - out := buf.String() + out := buffer.String() for _, want := range []string{`"keys": {` + "\n" + ` "v10": "EA==",` + "\n" + ` "v20": "IA=="`, `"keys": {}`} { if !strings.Contains(out, want) { t.Errorf("WriteJSON output lacks %q:\n%s", want, out) @@ -89,11 +89,11 @@ func TestDump_KeysWireForm(t *testing.T) { func TestReadJSON_IgnoresUnknownKeyVersions(t *testing.T) { input := bytes.NewBufferString(`{"version":"2","vaults":[{"browser":"chrome","keys":{"v10":"EA==","v99":"AQ=="}}]}`) - d, err := ReadJSON(input) + dump, err := ReadJSON(input) if err != nil { t.Fatalf("ReadJSON: %v", err) } - if got := d.Vaults[0].Keys[V10]; !bytes.Equal(got, []byte{0x10}) { + if got := dump.Vaults[0].Keys[V10]; !bytes.Equal(got, []byte{0x10}) { t.Errorf("v10 = %x, want 10", got) } } diff --git a/internal/masterkey/gcoredump_stub_darwin.go b/internal/masterkey/gcoredump_stub_darwin.go index 26386ef..83b420d 100644 --- a/internal/masterkey/gcoredump_stub_darwin.go +++ b/internal/masterkey/gcoredump_stub_darwin.go @@ -8,7 +8,7 @@ import ( "github.com/moond4rk/keychainbreaker" ) -// Default builds leave out the securityd dump (built only with -tags keychain_gcore), so this tier steps aside. +// DecryptKeychainRecords steps aside in default builds, which leave out the securityd dump (-tags keychain_gcore). func DecryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { return nil, errors.New("keychain gcore dump not built in (rebuild with -tags keychain_gcore)") } diff --git a/internal/masterkey/keys_golden_test.go b/internal/masterkey/keys_golden_test.go index 786cdf5..ee2dbb1 100644 --- a/internal/masterkey/keys_golden_test.go +++ b/internal/masterkey/keys_golden_test.go @@ -19,10 +19,10 @@ import ( var keysGoldenCreatedAt = time.Date(2026, time.May, 16, 8, 30, 15, 123456789, time.UTC) -// Strict rejects non-canonical literals, so every key reads in keys.golden exactly as written here. -func keysFakeKey(t *testing.T, b64 string) []byte { +// keysFakeKey uses Strict, which rejects non-canonical literals, so keys.golden holds each key as written here. +func keysFakeKey(t *testing.T, encodedKey string) []byte { t.Helper() - key, err := base64.StdEncoding.Strict().DecodeString(b64) + key, err := base64.StdEncoding.Strict().DecodeString(encodedKey) require.NoError(t, err) return key } @@ -38,7 +38,7 @@ func keysFreeze(t *testing.T, dump masterkey.Dump, host masterkey.Host) masterke return dump } -// Two Chromium installs, the Opera and Yandex forks, and a vault that kept its v10 key when v20 failed. +// keysVaultsDump has two Chromium installs, the Opera and Yandex forks, and a vault that kept v10 when v20 failed. func keysVaultsDump(t *testing.T) masterkey.Dump { t.Helper() return masterkey.Dump{ @@ -98,12 +98,12 @@ func TestKeysGolden(t *testing.T) { {name: "vaults", golden: "keys.golden", dump: keysVaultsDump}, {name: "empty", golden: "keys-empty.golden", dump: keysEmptyDump}, } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - var buf bytes.Buffer - require.NoError(t, tt.dump(t).WriteJSON(&buf)) - golden.Assert(t, tt.golden, buf.String()) + for _, testCase := range tests { + testCase := testCase + t.Run(testCase.name, func(t *testing.T) { + var buffer bytes.Buffer + require.NoError(t, testCase.dump(t).WriteJSON(&buffer)) + golden.Assert(t, testCase.golden, buffer.String()) }) } } @@ -122,21 +122,21 @@ func TestKeysRead(t *testing.T) { {name: "older version", golden: "keys.golden", edit: keysSetVersion("1"), wantErr: "unsupported dump version"}, {name: "newer version", golden: "keys.golden", edit: keysSetVersion("3"), wantErr: "unsupported dump version"}, } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - data, err := os.ReadFile(filepath.Join("testdata", tt.golden)) + for _, testCase := range tests { + testCase := testCase + t.Run(testCase.name, func(t *testing.T) { + data, err := os.ReadFile(filepath.Join("testdata", testCase.golden)) require.NoError(t, err) - if tt.edit != nil { - data = keysEditJSON(t, data, tt.edit) + if testCase.edit != nil { + data = keysEditJSON(t, data, testCase.edit) } got, err := masterkey.ReadJSON(bytes.NewReader(data)) - if tt.wantErr != "" { - require.ErrorContains(t, err, tt.wantErr) + if testCase.wantErr != "" { + require.ErrorContains(t, err, testCase.wantErr) return } require.NoError(t, err) - assert.Equal(t, tt.want(t), got) + assert.Equal(t, testCase.want(t), got) }) } } @@ -156,8 +156,8 @@ func keysAddUnknownFields(t *testing.T, doc map[string]any) { vaults, ok := doc["vaults"].([]any) require.True(t, ok) require.NotEmpty(t, vaults) - for _, v := range vaults { - vault, ok := v.(map[string]any) + for _, value := range vaults { + vault, ok := value.(map[string]any) require.True(t, ok) vault["labels"] = []any{"work", "travel"} } diff --git a/internal/masterkey/masterkey.go b/internal/masterkey/masterkey.go index 3d1e80f..a97fa01 100644 --- a/internal/masterkey/masterkey.go +++ b/internal/masterkey/masterkey.go @@ -57,39 +57,39 @@ const ( ABEAvast ) -// Per version the first key wins, and an error is reported only when every retriever of that version fails. -func RetrieveAll(ctx context.Context, loc Locator) (Set, error) { - return retrieveAll(ctx, loc, platformRetrievers) +// RetrieveAll keeps the first key per version and reports an error only when every retriever of that version fails. +func RetrieveAll(ctx context.Context, locator Locator) (Set, error) { + return retrieveAll(ctx, locator, platformRetrievers) } -func retrieveAll(ctx context.Context, loc Locator, retrievers []Retriever) (Set, error) { +func retrieveAll(ctx context.Context, locator Locator, retrievers []Retriever) (Set, error) { keys := make(Set) var versions []Version failures := make(map[Version][]error) - for _, r := range retrievers { - v := r.Version() - if _, ok := keys[v]; ok { + for _, retriever := range retrievers { + version := retriever.Version() + if _, ok := keys[version]; ok { continue } - if _, ok := failures[v]; !ok { - versions = append(versions, v) - failures[v] = nil + if _, ok := failures[version]; !ok { + versions = append(versions, version) + failures[version] = nil } - key, err := r.Retrieve(ctx, loc) + key, err := retriever.Retrieve(ctx, locator) switch { case errors.Is(err, ErrNotApplicable): case err != nil: - log.Debugf("%s retriever %T failed: %v", v, r, err) - failures[v] = append(failures[v], err) + log.Debugf("%s retriever %T failed: %v", version, retriever, err) + failures[version] = append(failures[version], err) case len(key) > 0: - keys[v] = key + keys[version] = key } } var errs []error - for _, v := range versions { - if _, ok := keys[v]; !ok && len(failures[v]) > 0 { - errs = append(errs, fmt.Errorf("%s: %w", v, errors.Join(failures[v]...))) + for _, version := range versions { + if _, ok := keys[version]; !ok && len(failures[version]) > 0 { + errs = append(errs, fmt.Errorf("%s: %w", version, errors.Join(failures[version]...))) } } return keys, errors.Join(errs...) diff --git a/internal/masterkey/masterkey_test.go b/internal/masterkey/masterkey_test.go index 3d7f527..15ba9e2 100644 --- a/internal/masterkey/masterkey_test.go +++ b/internal/masterkey/masterkey_test.go @@ -22,16 +22,16 @@ type fakeRetriever struct { func (r *fakeRetriever) Version() Version { return r.version } -func (r *fakeRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { +func (r *fakeRetriever) Retrieve(_ context.Context, locator Locator) ([]byte, error) { r.calls++ - r.gotLoc = loc + r.gotLoc = locator return r.key, r.err } var ( - k10 = bytes.Repeat([]byte{0x10}, 32) - k11 = bytes.Repeat([]byte{0x11}, 32) - k20 = bytes.Repeat([]byte{0x20}, 32) + v10Key = bytes.Repeat([]byte{0x10}, 32) + v11Key = bytes.Repeat([]byte{0x11}, 32) + v20Key = bytes.Repeat([]byte{0x20}, 32) ) func TestRetrieveAll_OneKeyPerVersion(t *testing.T) { @@ -42,18 +42,18 @@ func TestRetrieveAll_OneKeyPerVersion(t *testing.T) { }{ { name: "Windows shape: v10 and v20", - retrievers: []*fakeRetriever{{version: V10, key: k10}, {version: V20, key: k20}}, - want: Set{V10: k10, V20: k20}, + retrievers: []*fakeRetriever{{version: V10, key: v10Key}, {version: V20, key: v20Key}}, + want: Set{V10: v10Key, V20: v20Key}, }, { name: "Linux shape: v10 and v11", - retrievers: []*fakeRetriever{{version: V10, key: k10}, {version: V11, key: k11}}, - want: Set{V10: k10, V11: k11}, + retrievers: []*fakeRetriever{{version: V10, key: v10Key}, {version: V11, key: v11Key}}, + want: Set{V10: v10Key, V11: v11Key}, }, { name: "macOS shape: v10 only", - retrievers: []*fakeRetriever{{version: V10, key: k10}}, - want: Set{V10: k10}, + retrievers: []*fakeRetriever{{version: V10, key: v10Key}}, + want: Set{V10: v10Key}, }, { name: "no retrievers", @@ -61,35 +61,35 @@ func TestRetrieveAll_OneKeyPerVersion(t *testing.T) { want: Set{}, }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := retrieveAll(context.Background(), Locator{}, asRetrievers(tt.retrievers)) + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + got, err := retrieveAll(context.Background(), Locator{}, asRetrievers(testCase.retrievers)) require.NoError(t, err) - assert.Equal(t, tt.want, got) + assert.Equal(t, testCase.want, got) }) } } func TestRetrieveAll_FirstKeyWinsAndStopsTheVersion(t *testing.T) { failing := &fakeRetriever{version: V10, err: errors.New("needs root")} - winner := &fakeRetriever{version: V10, key: k10} + winner := &fakeRetriever{version: V10, key: v10Key} later := &fakeRetriever{version: V10, key: bytes.Repeat([]byte{0xFF}, 16)} got, err := retrieveAll(context.Background(), Locator{}, []Retriever{failing, winner, later}) require.NoError(t, err, "a strategy that failed before a later one succeeded is not an error") - assert.Equal(t, Set{V10: k10}, got) + assert.Equal(t, Set{V10: v10Key}, got) assert.Equal(t, []int{1, 1, 0}, []int{failing.calls, winner.calls, later.calls}) } func TestRetrieveAll_VersionsAreIndependent(t *testing.T) { - v20 := &fakeRetriever{version: V20, err: errors.New("abe: inject failed")} + v20Retriever := &fakeRetriever{version: V20, err: errors.New("abe: inject failed")} got, err := retrieveAll(context.Background(), Locator{}, []Retriever{ - &fakeRetriever{version: V10, key: k10}, - v20, + &fakeRetriever{version: V10, key: v10Key}, + v20Retriever, }) require.Error(t, err) assert.Contains(t, err.Error(), "v20: abe: inject failed") - assert.Equal(t, Set{V10: k10}, got, "a v20 failure keeps the v10 key") + assert.Equal(t, Set{V10: v10Key}, got, "a v20 failure keeps the v10 key") } func TestRetrieveAll_ErrorOnlyWhenEveryRetrieverFails(t *testing.T) { @@ -115,17 +115,17 @@ func TestRetrieveAll_NotApplicableIsSilent(t *testing.T) { } func TestRetrieveAll_PassesTheLocator(t *testing.T) { - r := &fakeRetriever{version: V10, key: k10} - loc := Locator{LocalState: "/tmp/Local State", KeychainLabel: "Chrome", Exe: "chrome.exe", ABE: ABEChromeBase} - _, err := retrieveAll(context.Background(), loc, []Retriever{r}) + retriever := &fakeRetriever{version: V10, key: v10Key} + locator := Locator{LocalState: "/tmp/Local State", KeychainLabel: "Chrome", Exe: "chrome.exe", ABE: ABEChromeBase} + _, err := retrieveAll(context.Background(), locator, []Retriever{retriever}) require.NoError(t, err) - assert.Equal(t, loc, r.gotLoc) + assert.Equal(t, locator, retriever.gotLoc) } func asRetrievers(fakes []*fakeRetriever) []Retriever { - rs := make([]Retriever, 0, len(fakes)) - for _, f := range fakes { - rs = append(rs, f) + retrievers := make([]Retriever, 0, len(fakes)) + for _, fake := range fakes { + retrievers = append(retrievers, fake) } - return rs + return retrievers } diff --git a/internal/masterkey/retriever_darwin.go b/internal/masterkey/retriever_darwin.go index 017cbb5..6afade6 100644 --- a/internal/masterkey/retriever_darwin.go +++ b/internal/masterkey/retriever_darwin.go @@ -19,6 +19,7 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/log" ) +// darwinParams follow Chromium's os_crypt_mac.mm: // https://source.chromium.org/chromium/chromium/src/+/master:components/os_crypt/os_crypt_mac.mm;l=157 var darwinParams = pbkdf2Params{ salt: []byte("saltysalt"), @@ -29,14 +30,14 @@ var darwinParams = pbkdf2Params{ const securityCmdTimeout = 30 * time.Second -// First success wins; the security CLI goes last because it may prompt. +// platformRetrievers stop at the first success; the security CLI goes last because it may prompt. var platformRetrievers = []Retriever{ &gcoredumpRetriever{}, keychainRetriever{}, &securityRetriever{cache: make(map[string]securityResult)}, } -// Records are read once (sync.Once), so the dump runs a single time for all browsers. +// gcoredumpRetriever reads records once (sync.Once), so the dump runs a single time for all browsers. type gcoredumpRetriever struct { once sync.Once records []keychainbreaker.GenericPassword @@ -46,7 +47,7 @@ type gcoredumpRetriever struct { func (*gcoredumpRetriever) Version() Version { return V10 } // Retrieve steps aside on failure: the common "needs root" case isn't warning-worthy and would drown real warnings. -func (r *gcoredumpRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { +func (r *gcoredumpRetriever) Retrieve(_ context.Context, locator Locator) ([]byte, error) { r.once.Do(func() { r.records, r.err = DecryptKeychainRecords() }) @@ -55,7 +56,7 @@ func (r *gcoredumpRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, e return nil, ErrNotApplicable } - key, err := findStorageKey(r.records, loc.KeychainLabel) + key, err := findStorageKey(r.records, locator.KeychainLabel) if err != nil { log.Debugf("gcoredump: %v", err) return nil, ErrNotApplicable @@ -64,24 +65,24 @@ func (r *gcoredumpRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, e } func findStorageKey(records []keychainbreaker.GenericPassword, storage string) ([]byte, error) { - for _, rec := range records { - if rec.Account == storage { - return darwinParams.deriveKey(rec.Password), nil + for _, genericPassword := range records { + if genericPassword.Account == storage { + return darwinParams.deriveKey(genericPassword.Password), nil } } return nil, fmt.Errorf("%q: %w", storage, errStorageNotFound) } -// Without a keychain, or with a locked one, it steps aside: the keychain reports why once for the run. +// keychainRetriever steps aside without a keychain or with a locked one; the keychain reports why once for the run. type keychainRetriever struct{} func (keychainRetriever) Version() Version { return V10 } -func (keychainRetriever) Retrieve(ctx context.Context, loc Locator) ([]byte, error) { - if loc.Keychain == nil { +func (keychainRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, error) { + if locator.Keychain == nil { return nil, ErrNotApplicable } - secret, err := loc.Keychain.GenericPassword(ctx, loc.KeychainLabel) + secret, err := locator.Keychain.GenericPassword(ctx, locator.KeychainLabel) if errors.Is(err, keychain.ErrLocked) { return nil, ErrNotApplicable } @@ -91,9 +92,9 @@ func (keychainRetriever) Retrieve(ctx context.Context, loc Locator) ([]byte, err return darwinParams.deriveKey(secret), nil } -// Results are cached per storage name, so each browser's key is fetched, and prompted for, once. +// securityRetriever caches results per storage name, so each browser's key is fetched, and prompted for, once. type securityRetriever struct { - mu sync.Mutex + mutex sync.Mutex cache map[string]securityResult } @@ -104,13 +105,13 @@ type securityResult struct { func (*securityRetriever) Version() Version { return V10 } -func (r *securityRetriever) Retrieve(ctx context.Context, loc Locator) ([]byte, error) { - storage := loc.KeychainLabel - r.mu.Lock() - defer r.mu.Unlock() +func (r *securityRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, error) { + storage := locator.KeychainLabel + r.mutex.Lock() + defer r.mutex.Unlock() - if res, ok := r.cache[storage]; ok { - return res.key, res.err + if cached, ok := r.cache[storage]; ok { + return cached.key, cached.err } key, err := r.retrieveKeyOnce(ctx, storage) @@ -123,11 +124,11 @@ func (r *securityRetriever) retrieveKeyOnce(ctx context.Context, storage string) defer cancel() var stdout, stderr bytes.Buffer - cmd := exec.CommandContext(ctx, "security", "find-generic-password", "-wa", strings.TrimSpace(storage)) //nolint:gosec - cmd.Stdout = &stdout - cmd.Stderr = &stderr + command := exec.CommandContext(ctx, "security", "find-generic-password", "-wa", strings.TrimSpace(storage)) //nolint:gosec + command.Stdout = &stdout + command.Stderr = &stderr - if err := cmd.Run(); err != nil { + if err := command.Run(); err != nil { if errors.Is(ctx.Err(), context.DeadlineExceeded) { return nil, fmt.Errorf("security command timed out after %s", securityCmdTimeout) } diff --git a/internal/masterkey/retriever_darwin_test.go b/internal/masterkey/retriever_darwin_test.go index 4fa567a..21c145e 100644 --- a/internal/masterkey/retriever_darwin_test.go +++ b/internal/masterkey/retriever_darwin_test.go @@ -56,7 +56,9 @@ func (k *fakeKeychain) GenericPassword(_ context.Context, account string) ([]byt func TestKeychainRetriever(t *testing.T) { ctx := context.Background() - loc := func(kc LoginKeychain) Locator { return Locator{KeychainLabel: "Chrome", Keychain: kc} } + locatorFor := func(loginKeychain LoginKeychain) Locator { + return Locator{KeychainLabel: "Chrome", Keychain: loginKeychain} + } t.Run("no keychain steps aside", func(t *testing.T) { _, err := keychainRetriever{}.Retrieve(ctx, Locator{KeychainLabel: "Chrome"}) @@ -64,21 +66,21 @@ func TestKeychainRetriever(t *testing.T) { }) t.Run("locked keychain steps aside", func(t *testing.T) { - kc := &fakeKeychain{err: fmt.Errorf("%w: wrong password", keychain.ErrLocked)} - _, err := keychainRetriever{}.Retrieve(ctx, loc(kc)) + loginKeychain := &fakeKeychain{err: fmt.Errorf("%w: wrong password", keychain.ErrLocked)} + _, err := keychainRetriever{}.Retrieve(ctx, locatorFor(loginKeychain)) require.ErrorIs(t, err, ErrNotApplicable) }) t.Run("secret derives the v10 key", func(t *testing.T) { - kc := &fakeKeychain{secrets: map[string][]byte{"Chrome": []byte("mock-secret")}} - key, err := keychainRetriever{}.Retrieve(ctx, loc(kc)) + loginKeychain := &fakeKeychain{secrets: map[string][]byte{"Chrome": []byte("mock-secret")}} + key, err := keychainRetriever{}.Retrieve(ctx, locatorFor(loginKeychain)) require.NoError(t, err) assert.Equal(t, darwinParams.deriveKey([]byte("mock-secret")), key) - assert.Equal(t, []string{"Chrome"}, kc.asked) + assert.Equal(t, []string{"Chrome"}, loginKeychain.asked) }) t.Run("missing label is an error", func(t *testing.T) { - _, err := keychainRetriever{}.Retrieve(ctx, loc(&fakeKeychain{secrets: map[string][]byte{}})) + _, err := keychainRetriever{}.Retrieve(ctx, locatorFor(&fakeKeychain{secrets: map[string][]byte{}})) require.Error(t, err) assert.NotErrorIs(t, err, ErrNotApplicable) }) @@ -89,7 +91,7 @@ func TestPlatformRetrievers_Darwin(t *testing.T) { assert.IsType(t, &gcoredumpRetriever{}, platformRetrievers[0]) assert.IsType(t, keychainRetriever{}, platformRetrievers[1]) assert.IsType(t, &securityRetriever{}, platformRetrievers[2]) - for _, r := range platformRetrievers { - assert.Equal(t, V10, r.Version()) + for _, retriever := range platformRetrievers { + assert.Equal(t, V10, retriever.Version()) } } diff --git a/internal/masterkey/retriever_linux.go b/internal/masterkey/retriever_linux.go index f5cf31f..8db054a 100644 --- a/internal/masterkey/retriever_linux.go +++ b/internal/masterkey/retriever_linux.go @@ -11,7 +11,7 @@ import ( keyring "github.com/ppacher/go-dbus-keyring" ) -// https://source.chromium.org/chromium/chromium/src/+/main:components/os_crypt/os_crypt_linux.cc +// linuxParams follow https://source.chromium.org/chromium/chromium/src/+/main:components/os_crypt/os_crypt_linux.cc var linuxParams = pbkdf2Params{ salt: []byte("saltysalt"), iterations: 1, @@ -19,38 +19,38 @@ var linuxParams = pbkdf2Params{ hashFunc: sha1.New, } -// A profile holds both v10 and v11 values when its host moved between headless and keyring sessions. +// platformRetrievers run both: a profile holds v10 and v11 values once its host moved between headless and keyring. var platformRetrievers = []Retriever{posixRetriever{}, dbusRetriever{}} type dbusRetriever struct{} func (dbusRetriever) Version() Version { return V11 } -func (dbusRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { - storage := loc.KeychainLabel - conn, err := dbus.SessionBus() +func (dbusRetriever) Retrieve(_ context.Context, locator Locator) ([]byte, error) { + storage := locator.KeychainLabel + connection, err := dbus.SessionBus() if err != nil { return nil, fmt.Errorf("dbus session: %w", err) } - svc, err := keyring.GetSecretService(conn) + service, err := keyring.GetSecretService(connection) if err != nil { return nil, fmt.Errorf("secret service: %w", err) } - session, err := svc.OpenSession() + session, err := service.OpenSession() if err != nil { return nil, fmt.Errorf("open session: %w", err) } defer session.Close() - collections, err := svc.GetAllCollections() + collections, err := service.GetAllCollections() if err != nil { return nil, fmt.Errorf("get collections: %w", err) } - for _, col := range collections { - items, err := col.GetAllItems() + for _, collection := range collections { + items, err := collection.GetAllItems() if err != nil { continue } diff --git a/internal/masterkey/retriever_linux_test.go b/internal/masterkey/retriever_linux_test.go index 779d616..6ab4e70 100644 --- a/internal/masterkey/retriever_linux_test.go +++ b/internal/masterkey/retriever_linux_test.go @@ -11,16 +11,16 @@ import ( ) func TestPosixRetriever(t *testing.T) { - r := posixRetriever{} + retriever := posixRetriever{} - key, err := r.Retrieve(context.Background(), Locator{KeychainLabel: "Chrome"}) + key, err := retriever.Retrieve(context.Background(), Locator{KeychainLabel: "Chrome"}) require.NoError(t, err) assert.Equal(t, linuxParams.deriveKey([]byte("peanuts")), key) assert.Len(t, key, linuxParams.keySize) allZero := true - for _, b := range key { - if b != 0 { + for _, keyByte := range key { + if keyByte != 0 { allZero = false break } @@ -28,12 +28,12 @@ func TestPosixRetriever(t *testing.T) { assert.False(t, allZero, "derived key should not be all zeros") // The password is fixed, so the key is the same for any locator and on every call. - key2, err := r.Retrieve(context.Background(), Locator{KeychainLabel: "Brave"}) + braveKey, err := retriever.Retrieve(context.Background(), Locator{KeychainLabel: "Brave"}) require.NoError(t, err) - assert.Equal(t, key, key2, "kV10Key should be constant across any storage label") + assert.Equal(t, key, braveKey, "kV10Key should be constant across any storage label") } -// Pins the output to Chromium's kV10Key reference bytes. +// TestPosixRetriever_MatchesChromiumKV10Key pins the output to Chromium's kV10Key reference bytes. func TestPosixRetriever_MatchesChromiumKV10Key(t *testing.T) { want := []byte{ 0xfd, 0x62, 0x1f, 0xe5, 0xa2, 0xb4, 0x02, 0x53, diff --git a/internal/masterkey/retriever_windows.go b/internal/masterkey/retriever_windows.go index fec42fb..136710f 100644 --- a/internal/masterkey/retriever_windows.go +++ b/internal/masterkey/retriever_windows.go @@ -13,15 +13,15 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/winapi" ) -// Both run: a profile upgraded past Chrome 127 holds v10 and v20 values side by side. +// platformRetrievers run both: a profile upgraded past Chrome 127 holds v10 and v20 values side by side. var platformRetrievers = []Retriever{dpapiRetriever{}, abeRetriever{}} type dpapiRetriever struct{} func (dpapiRetriever) Version() Version { return V10 } -func (dpapiRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { - data, err := os.ReadFile(loc.LocalState) +func (dpapiRetriever) Retrieve(_ context.Context, locator Locator) ([]byte, error) { + data, err := os.ReadFile(locator.LocalState) if err != nil { return nil, fmt.Errorf("read Local State: %w", err) } diff --git a/internal/record/record.go b/internal/record/record.go index 9aecb0e..3fc6e17 100644 --- a/internal/record/record.go +++ b/internal/record/record.go @@ -6,18 +6,13 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/category" ) -// Record is sealed by the unexported stamp, so only this package's types are records. +// Record is one output row; the collector sets its Browser and Profile, so extractors leave both empty. type Record interface { Category() category.Category - stamp(browser, profile string) + SetBrowserAndProfile(browser, profile string) } -// Stamp is exported because the sealing method stamp cannot be called from other packages. -func Stamp(r Record, browser, profile string) { - r.stamp(browser, profile) -} - -// Named Login, not Password: the row holds a URL and a user name as well as the password. +// Login is named for the whole row, not Password: it holds a URL and a user name as well as the password. type Login struct { Browser string `json:"browser" csv:"browser"` Profile string `json:"profile" csv:"profile"` @@ -83,7 +78,7 @@ type Download struct { EndTime time.Time `json:"end_time" csv:"end_time"` } -// CreditCard's CVC and Comment are Yandex-specific; Chromium leaves them empty. +// CreditCard has Yandex-only CVC and Comment fields; Chromium leaves them empty. type CreditCard struct { Browser string `json:"browser" csv:"browser"` Profile string `json:"profile" csv:"profile"` @@ -138,12 +133,38 @@ func (r *Extension) Category() category.Category { return category.Extensio func (r *LocalStorage) Category() category.Category { return category.LocalStorage } func (r *SessionStorage) Category() category.Category { return category.SessionStorage } -func (r *Login) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } -func (r *Cookie) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } -func (r *Bookmark) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } -func (r *History) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } -func (r *Download) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } -func (r *CreditCard) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } -func (r *Extension) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } -func (r *LocalStorage) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } -func (r *SessionStorage) stamp(browser, profile string) { r.Browser, r.Profile = browser, profile } +func (r *Login) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} + +func (r *Cookie) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} + +func (r *Bookmark) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} + +func (r *History) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} + +func (r *Download) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} + +func (r *CreditCard) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} + +func (r *Extension) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} + +func (r *LocalStorage) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} + +func (r *SessionStorage) SetBrowserAndProfile(browser, profile string) { + r.Browser, r.Profile = browser, profile +} diff --git a/internal/record/record_test.go b/internal/record/record_test.go index 303b870..800d51e 100644 --- a/internal/record/record_test.go +++ b/internal/record/record_test.go @@ -28,52 +28,52 @@ func allRecords() map[category.Category]Record { func TestCategory_OneRecordTypePerCategory(t *testing.T) { records := allRecords() assert.Len(t, records, len(category.All())) - for _, c := range category.All() { - r, ok := records[c] - if assert.Truef(t, ok, "no record type for %s", c) { - assert.Equalf(t, c, r.Category(), "%T", r) + for _, dataCategory := range category.All() { + row, ok := records[dataCategory] + if assert.Truef(t, ok, "no record type for %s", dataCategory) { + assert.Equalf(t, dataCategory, row.Category(), "%T", row) } } } -func TestStamp(t *testing.T) { - for _, r := range allRecords() { - Stamp(r, "Microsoft Edge", "Profile 1") - v := reflect.ValueOf(r).Elem() - assert.Equalf(t, "Microsoft Edge", v.FieldByName("Browser").String(), "%T", r) - assert.Equalf(t, "Profile 1", v.FieldByName("Profile").String(), "%T", r) +func TestSetBrowserAndProfile(t *testing.T) { + for _, row := range allRecords() { + row.SetBrowserAndProfile("Microsoft Edge", "Profile 1") + value := reflect.ValueOf(row).Elem() + assert.Equalf(t, "Microsoft Edge", value.FieldByName("Browser").String(), "%T", row) + assert.Equalf(t, "Profile 1", value.FieldByName("Profile").String(), "%T", row) } } -// The tags are the output's field names and column headers, so they stay snake_case and lead with the stamp. +// TestTags_AreSnakeCaseFieldNames freezes the tags, the output's names: snake_case, led by Browser and Profile. func TestTags_AreSnakeCaseFieldNames(t *testing.T) { - for _, r := range allRecords() { - typ := reflect.TypeOf(r).Elem() - assert.Equalf(t, "Browser", typ.Field(0).Name, "%s", typ) - assert.Equalf(t, "Profile", typ.Field(1).Name, "%s", typ) - for i := 0; i < typ.NumField(); i++ { - f := typ.Field(i) - want := snakeCase(f.Name) - assert.Equalf(t, want, f.Tag.Get("json"), "%s.%s json tag", typ, f.Name) - assert.Equalf(t, want, f.Tag.Get("csv"), "%s.%s csv tag", typ, f.Name) + for _, row := range allRecords() { + recordType := reflect.TypeOf(row).Elem() + assert.Equalf(t, "Browser", recordType.Field(0).Name, "%s", recordType) + assert.Equalf(t, "Profile", recordType.Field(1).Name, "%s", recordType) + for i := 0; i < recordType.NumField(); i++ { + field := recordType.Field(i) + want := snakeCase(field.Name) + assert.Equalf(t, want, field.Tag.Get("json"), "%s.%s json tag", recordType, field.Name) + assert.Equalf(t, want, field.Tag.Get("csv"), "%s.%s csv tag", recordType, field.Name) } } } func snakeCase(name string) string { runes := []rune(name) - var b strings.Builder - for i, r := range runes { - if i > 0 && unicode.IsUpper(r) { + var builder strings.Builder + for i, character := range runes { + if i > 0 && unicode.IsUpper(character) { prevLower := unicode.IsLower(runes[i-1]) acronymEnds := unicode.IsUpper(runes[i-1]) && i+1 < len(runes) && unicode.IsLower(runes[i+1]) if prevLower || acronymEnds { - b.WriteByte('_') + builder.WriteByte('_') } } - b.WriteRune(unicode.ToLower(r)) + builder.WriteRune(unicode.ToLower(character)) } - return b.String() + return builder.String() } func TestSnakeCase(t *testing.T) { diff --git a/internal/snapshot/copy.go b/internal/snapshot/copy.go index 37ecb39..a6ff6cd 100644 --- a/internal/snapshot/copy.go +++ b/internal/snapshot/copy.go @@ -12,90 +12,90 @@ import ( ) // Copy copies a file together with its SQLite -wal and -shm sidecars, or a directory minus every entry named *lock. -func Copy(src, dst string, isDir bool) error { +func Copy(from, into string, isDir bool) error { if isDir { - return copyDir(src, dst) + return copyDir(from, into) } - if err := copyFile(src, dst); err != nil { + if err := copyFile(from, into); err != nil { // Chromium on Windows holds Cookies under an exclusive lock that a plain read cannot pass. if runtime.GOOS != "windows" { return fmt.Errorf("copy: %w", err) } - if lockedErr := copyLocked(src, dst); lockedErr != nil { + if lockedErr := copyLocked(from, into); lockedErr != nil { return errors.Join(fmt.Errorf("copy: %w", err), fmt.Errorf("locked copy: %w", lockedErr)) } } var sidecarErrs []error for _, suffix := range []string{"-wal", "-shm"} { - if !isFile(src + suffix) { + if !isFile(from + suffix) { continue } - if err := copyFile(src+suffix, dst+suffix); err != nil { + if err := copyFile(from+suffix, into+suffix); err != nil { sidecarErrs = append(sidecarErrs, fmt.Errorf("copy %s: %w", suffix, err)) } } return errors.Join(sidecarErrs...) } -func copyFile(src, dst string) error { - data, err := os.ReadFile(src) +func copyFile(from, into string) error { + data, err := os.ReadFile(from) if err != nil { return err } - return os.WriteFile(dst, data, 0o600) + return os.WriteFile(into, data, 0o600) } -func copyDir(src, dst string) error { - info, err := os.Lstat(src) +func copyDir(from, into string) error { + info, err := os.Lstat(from) if err != nil { return err } - return copyEntry(src, dst, info) + return copyEntry(from, into, info) } -func copyEntry(src, dst string, info fs.FileInfo) error { +func copyEntry(from, into string, info fs.FileInfo) error { switch { case info.Mode()&fs.ModeSymlink != 0: - target, err := os.Readlink(src) + target, err := os.Readlink(from) if err != nil { return err } - return os.Symlink(target, dst) + return os.Symlink(target, into) case info.IsDir(): - return copyChildren(src, dst) + return copyChildren(from, into) case info.Mode().IsRegular(): - return copyRegular(src, dst) + return copyRegular(from, into) default: return nil } } -func copyChildren(src, dst string) error { - if err := os.MkdirAll(dst, 0o700); err != nil { +func copyChildren(from, into string) error { + if err := os.MkdirAll(into, 0o700); err != nil { return err } - entries, err := os.ReadDir(src) + entries, err := os.ReadDir(from) if errors.Is(err, fs.ErrNotExist) { return nil } if err != nil { return err } - for _, e := range entries { - child := filepath.Join(src, e.Name()) + for _, entry := range entries { + child := filepath.Join(from, entry.Name()) // LevelDB's LOCK is held by the running browser and means nothing in a copy; any name ending in lock is skipped. if strings.HasSuffix(strings.ToLower(child), "lock") { continue } - info, err := e.Info() + info, err := entry.Info() if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return err } - if err := copyEntry(child, filepath.Join(dst, e.Name()), info); err != nil { + if err := copyEntry(child, filepath.Join(into, entry.Name()), info); err != nil { return err } } @@ -103,21 +103,21 @@ func copyChildren(src, dst string) error { } // copyRegular skips a file that vanished after its directory was listed: a live LevelDB compacts while it is copied. -func copyRegular(src, dst string) error { - in, err := os.Open(src) +func copyRegular(from, into string) error { + input, err := os.Open(from) if errors.Is(err, fs.ErrNotExist) { return nil } if err != nil { return err } - defer in.Close() + defer input.Close() - out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) + out, err := os.OpenFile(into, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) if err != nil { return err } - _, err = io.Copy(out, in) + _, err = io.Copy(out, input) return errors.Join(err, out.Close()) } diff --git a/internal/snapshot/copy_test.go b/internal/snapshot/copy_test.go index 69dd9aa..06e6efd 100644 --- a/internal/snapshot/copy_test.go +++ b/internal/snapshot/copy_test.go @@ -11,21 +11,21 @@ import ( ) func TestCopy_SkipsEveryEntryEndingInLock(t *testing.T) { - src := t.TempDir() + from := t.TempDir() for _, name := range []string{"LOCK", "db.lock", "Block", "LOCKED", "000003.log"} { - writeFile(t, filepath.Join(src, name), []byte(name)) + writeFile(t, filepath.Join(from, name), []byte(name)) } - writeFile(t, filepath.Join(src, "unlock", "inner"), []byte("inner")) + writeFile(t, filepath.Join(from, "unlock", "inner"), []byte("inner")) - dst := filepath.Join(t.TempDir(), "leveldb") - require.NoError(t, Copy(src, dst, true)) + into := filepath.Join(t.TempDir(), "leveldb") + require.NoError(t, Copy(from, into, true)) for _, skipped := range []string{"LOCK", "db.lock", "Block"} { - assert.NoFileExists(t, filepath.Join(dst, skipped)) + assert.NoFileExists(t, filepath.Join(into, skipped)) } - assert.NoDirExists(t, filepath.Join(dst, "unlock"), "a directory whose name ends in lock is skipped whole") - assert.FileExists(t, filepath.Join(dst, "LOCKED")) - assert.FileExists(t, filepath.Join(dst, "000003.log")) + assert.NoDirExists(t, filepath.Join(into, "unlock"), "a directory whose name ends in lock is skipped whole") + assert.FileExists(t, filepath.Join(into, "LOCKED")) + assert.FileExists(t, filepath.Join(into, "000003.log")) } func TestCopy_MissingSourceFails(t *testing.T) { @@ -35,40 +35,40 @@ func TestCopy_MissingSourceFails(t *testing.T) { } func TestCopy_FileWithoutSidecarsCopiesOnlyTheFile(t *testing.T) { - src := filepath.Join(t.TempDir(), "History") - writeFile(t, src, []byte("history")) + from := filepath.Join(t.TempDir(), "History") + writeFile(t, from, []byte("history")) - dst := filepath.Join(t.TempDir(), "History") - require.NoError(t, Copy(src, dst, false)) + into := filepath.Join(t.TempDir(), "History") + require.NoError(t, Copy(from, into, false)) - got, err := os.ReadFile(dst) + got, err := os.ReadFile(into) require.NoError(t, err) assert.Equal(t, "history", string(got)) - assert.NoFileExists(t, dst+"-wal") - assert.NoFileExists(t, dst+"-shm") + assert.NoFileExists(t, into+"-wal") + assert.NoFileExists(t, into+"-shm") } func TestCopy_SymlinkInADirectoryStaysALink(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("creating symlinks needs extra privileges on Windows") } - src := t.TempDir() - writeFile(t, filepath.Join(src, "target"), []byte("target")) - require.NoError(t, os.Symlink("target", filepath.Join(src, "link"))) + from := t.TempDir() + writeFile(t, filepath.Join(from, "target"), []byte("target")) + require.NoError(t, os.Symlink("target", filepath.Join(from, "link"))) - dst := filepath.Join(t.TempDir(), "copy") - require.NoError(t, Copy(src, dst, true)) + into := filepath.Join(t.TempDir(), "copy") + require.NoError(t, Copy(from, into, true)) - got, err := os.Readlink(filepath.Join(dst, "link")) + got, err := os.Readlink(filepath.Join(into, "link")) require.NoError(t, err) assert.Equal(t, "target", got) } -// A directory removed between its parent's listing and its own copy is copied as empty instead of failing the tree. +// TestCopyChildren_VanishedDirectoryCopiesAsEmpty copies a directory removed mid-copy as empty, not failing the tree. func TestCopyChildren_VanishedDirectoryCopiesAsEmpty(t *testing.T) { - dst := filepath.Join(t.TempDir(), "Origins") - require.NoError(t, copyChildren(filepath.Join(t.TempDir(), "gone"), dst)) - entries, err := os.ReadDir(dst) + into := filepath.Join(t.TempDir(), "Origins") + require.NoError(t, copyChildren(filepath.Join(t.TempDir(), "gone"), into)) + entries, err := os.ReadDir(into) require.NoError(t, err) assert.Empty(t, entries) } diff --git a/internal/snapshot/copy_windows.go b/internal/snapshot/copy_windows.go index d22b2fb..6efdf5e 100644 --- a/internal/snapshot/copy_windows.go +++ b/internal/snapshot/copy_windows.go @@ -8,10 +8,10 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/winapi" ) -func copyLocked(src, dst string) error { - data, err := winapi.ReadLockedFile(src) +func copyLocked(from, into string) error { + data, err := winapi.ReadLockedFile(from) if err != nil { return err } - return os.WriteFile(dst, data, 0o600) + return os.WriteFile(into, data, 0o600) } diff --git a/internal/snapshot/copy_windows_test.go b/internal/snapshot/copy_windows_test.go index 4e93642..4f6ab01 100644 --- a/internal/snapshot/copy_windows_test.go +++ b/internal/snapshot/copy_windows_test.go @@ -13,35 +13,35 @@ import ( ) func TestCopy_FallsBackToTheLockedRead(t *testing.T) { - src := filepath.Join(t.TempDir(), "cookies.db") + from := filepath.Join(t.TempDir(), "cookies.db") testData := []byte("cookie data") - require.NoError(t, os.WriteFile(src, testData, 0o644)) + require.NoError(t, os.WriteFile(from, testData, 0o644)) - handle := openExclusive(t, src) + handle := openExclusive(t, from) defer syscall.CloseHandle(handle) - dst := filepath.Join(t.TempDir(), "cookies.db") - require.NoError(t, Copy(src, dst, false), "Copy should succeed via the locked-file fallback") + into := filepath.Join(t.TempDir(), "cookies.db") + require.NoError(t, Copy(from, into, false), "Copy should succeed via the locked-file fallback") - copied, err := os.ReadFile(dst) + copied, err := os.ReadFile(into) require.NoError(t, err) assert.Equal(t, testData, copied) } func TestCopy_PlainWhenNotLocked(t *testing.T) { - src := filepath.Join(t.TempDir(), "unlocked.db") + from := filepath.Join(t.TempDir(), "unlocked.db") testData := []byte("unlocked data") - require.NoError(t, os.WriteFile(src, testData, 0o644)) + require.NoError(t, os.WriteFile(from, testData, 0o644)) - dst := filepath.Join(t.TempDir(), "unlocked.db") - require.NoError(t, Copy(src, dst, false)) + into := filepath.Join(t.TempDir(), "unlocked.db") + require.NoError(t, Copy(from, into, false)) - copied, err := os.ReadFile(dst) + copied, err := os.ReadFile(into) require.NoError(t, err) assert.Equal(t, testData, copied) } -// Share mode 0 locks the file the way Chrome's locking_mode=EXCLUSIVE does. +// openExclusive uses share mode 0, which locks the file the way Chrome's locking_mode=EXCLUSIVE does. func openExclusive(t *testing.T, path string) syscall.Handle { t.Helper() srcPtr, err := syscall.UTF16PtrFromString(path) diff --git a/internal/snapshot/manifest.go b/internal/snapshot/manifest.go index cc29567..2956645 100644 --- a/internal/snapshot/manifest.go +++ b/internal/snapshot/manifest.go @@ -32,8 +32,8 @@ type ManifestProfile struct { Dir string `json:"dir"` } -func (d *Dir) WriteManifest(m Manifest) error { - data, err := json.MarshalIndent(m, "", " ") +func (d *Dir) WriteManifest(manifest Manifest) error { + data, err := json.MarshalIndent(manifest, "", " ") if err != nil { return fmt.Errorf("encode manifest: %w", err) } @@ -52,12 +52,12 @@ func (d *Dir) ReadManifest() (Manifest, bool, error) { if err != nil { return Manifest{}, false, fmt.Errorf("read manifest: %w", err) } - var m Manifest - if err := json.Unmarshal(data, &m); err != nil { + var manifest Manifest + if err := json.Unmarshal(data, &manifest); err != nil { return Manifest{}, false, fmt.Errorf("decode manifest: %w", err) } - if m.Version != ManifestVersion { - return Manifest{}, false, fmt.Errorf("unsupported manifest version %d (this build reads %d)", m.Version, ManifestVersion) + if manifest.Version != ManifestVersion { + return Manifest{}, false, fmt.Errorf("unsupported manifest version %d (this build reads %d)", manifest.Version, ManifestVersion) } - return m, true, nil + return manifest, true, nil } diff --git a/internal/snapshot/manifest_test.go b/internal/snapshot/manifest_test.go index 268e2b7..0f59aef 100644 --- a/internal/snapshot/manifest_test.go +++ b/internal/snapshot/manifest_test.go @@ -10,15 +10,15 @@ import ( ) func TestManifest_RoundTrip(t *testing.T) { - d := Open(t.TempDir()) + snapshotDir := Open(t.TempDir()) want := Manifest{Version: ManifestVersion, Dirs: []ManifestDir{{ ID: "arc-2", Browser: "arc", Base: "chromium", Profiles: []ManifestProfile{{Name: "Default", Dir: "Default"}}, Files: []string{"Local State", "Default/Preferences"}, }}} - require.NoError(t, d.WriteManifest(want)) + require.NoError(t, snapshotDir.WriteManifest(want)) - got, ok, err := d.ReadManifest() + got, ok, err := snapshotDir.ReadManifest() require.NoError(t, err) assert.True(t, ok) assert.Equal(t, want, got) diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index b98a67a..2659d31 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -11,17 +11,17 @@ import ( ) type File struct { - DirID string // the user data dir's ID; also the snapshot it lands in - From string // absolute path of the user data dir it is copied from - Rel string // slash-separated path relative to From, and to the snapshot - IsDir bool + UserDataDirID string // the user data dir's ID; also the snapshot it lands in + UserDataDirPath string // absolute path of the user data dir it is copied from + RelativePath string // slash-separated path relative to UserDataDirPath, and to the snapshot + IsDir bool } -// Dir is a snapshot directory, laid out as //: one Snapshot per user data dir. +// Dir is a snapshot directory, laid out as //: one Snapshot per user data dir. type Dir struct { path string temp bool - failed map[string]error // keyed by the cleaned / path, so any spelling of a file finds its failure + failed map[string]error // keyed by the cleaned /, so any spelling of a file finds its failure } // Temp creates a private temporary snapshot directory, which Close removes. @@ -39,15 +39,15 @@ func Open(path string) *Dir { } // Unzip extracts an archive into a temporary snapshot directory, rejecting entries that would land outside it. -func Unzip(src string) (*Dir, error) { - d, err := Temp() +func Unzip(archivePath string) (*Dir, error) { + snapshotDir, err := Temp() if err != nil { return nil, err } - if err := unzip(src, d.path); err != nil { - return nil, errors.Join(err, d.Close()) + if err := unzip(archivePath, snapshotDir.path); err != nil { + return nil, errors.Join(err, snapshotDir.Close()) } - return d, nil + return snapshotDir, nil } func (d *Dir) Path() string { @@ -59,15 +59,15 @@ func (d *Dir) Capture(ctx context.Context, files []File) error { if err := os.MkdirAll(d.path, 0o700); err != nil { return fmt.Errorf("snapshot dir: %w", err) } - for _, f := range files { + for _, file := range files { if err := ctx.Err(); err != nil { return fmt.Errorf("capture: %w", err) } - local, err := localPath(f.DirID, f.Rel) + local, err := localPath(file.UserDataDirID, file.RelativePath) if err != nil { continue // Snapshot.Path reports the same error for this file } - if err := d.capture(local, f); err != nil { + if err := d.capture(local, file); err != nil { d.failed[local] = err } else { delete(d.failed, local) @@ -76,16 +76,16 @@ func (d *Dir) Capture(ctx context.Context, files []File) error { return nil } -func (d *Dir) capture(local string, f File) error { - dst := filepath.Join(d.path, local) - if err := os.MkdirAll(filepath.Dir(dst), 0o700); err != nil { - return fmt.Errorf("create %s: %w", filepath.Dir(dst), err) +func (d *Dir) capture(local string, file File) error { + target := filepath.Join(d.path, local) + if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { + return fmt.Errorf("create %s: %w", filepath.Dir(target), err) } - return Copy(filepath.Join(f.From, filepath.FromSlash(f.Rel)), dst, f.IsDir) + return Copy(filepath.Join(file.UserDataDirPath, filepath.FromSlash(file.RelativePath)), target, file.IsDir) } -func (d *Dir) Snapshot(dirID string) Snapshot { - return Snapshot{dirID: dirID, root: d.path, failed: d.failed} +func (d *Dir) Snapshot(userDataDirID string) Snapshot { + return Snapshot{userDataDirID: userDataDirID, root: d.path, failed: d.failed} } func (d *Dir) Close() error { @@ -99,32 +99,33 @@ func (d *Dir) Close() error { } type Snapshot struct { - dirID string - root string - failed map[string]error + userDataDirID string + root string + failed map[string]error } // Path reports fs.ErrNotExist for a file never captured or gone before Capture reached it, else the copy's error. -func (s Snapshot) Path(rel string) (string, error) { - local, err := localPath(s.dirID, rel) +func (s Snapshot) Path(relativePath string) (string, error) { + local, err := localPath(s.userDataDirID, relativePath) if err != nil { return "", err } if err, ok := s.failed[local]; ok { return "", err } - p := filepath.Join(s.root, local) - if _, err := os.Lstat(p); err != nil { + fullPath := filepath.Join(s.root, local) + if _, err := os.Lstat(fullPath); err != nil { return "", err } - return p, nil + return fullPath, nil } -// localPath keeps rel inside its own user data dir's snapshot, not merely inside the snapshot directory. -func localPath(dirID, rel string) (string, error) { - r := filepath.FromSlash(rel) - if !filepath.IsLocal(dirID) || dirID == "." || strings.ContainsAny(dirID, `/\`) || (r != "" && !filepath.IsLocal(r)) { - return "", fmt.Errorf("%q in %q is outside the snapshot directory", rel, dirID) +// localPath keeps relativePath inside its own user data dir's snapshot, not merely inside the snapshot directory. +func localPath(userDataDirID, relativePath string) (string, error) { + nativePath := filepath.FromSlash(relativePath) + if !filepath.IsLocal(userDataDirID) || userDataDirID == "." || strings.ContainsAny(userDataDirID, `/\`) || + (nativePath != "" && !filepath.IsLocal(nativePath)) { + return "", fmt.Errorf("%q in %q is outside the snapshot directory", relativePath, userDataDirID) } - return filepath.Join(dirID, r), nil + return filepath.Join(userDataDirID, nativePath), nil } diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index 90c96fe..2d0c3ff 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -16,7 +16,7 @@ import ( func userDataDir(t *testing.T) string { t.Helper() root := t.TempDir() - for rel, data := range map[string]string{ + for relativePath, data := range map[string]string{ "Local State": "{}", "Default/Network/Cookies": "db", "Default/Network/Cookies-wal": "wal", @@ -25,60 +25,60 @@ func userDataDir(t *testing.T) string { "Default/Local Storage/leveldb/LOCK": "", "Default/Local Storage/leveldb/000003.log": "log", } { - writeFile(t, filepath.Join(root, filepath.FromSlash(rel)), []byte(data)) + writeFile(t, filepath.Join(root, filepath.FromSlash(relativePath)), []byte(data)) } return root } func TestTemp_IsPrivateAndCloseRemovesIt(t *testing.T) { - d, err := Temp() + snapshotDir, err := Temp() require.NoError(t, err) - info, err := os.Stat(d.Path()) + info, err := os.Stat(snapshotDir.Path()) require.NoError(t, err) if runtime.GOOS != "windows" { assert.Equal(t, fs.FileMode(0o700), info.Mode().Perm()) } - require.NoError(t, d.Close()) - assert.NoDirExists(t, d.Path()) + require.NoError(t, snapshotDir.Close()) + assert.NoDirExists(t, snapshotDir.Path()) } func TestOpen_ReadsInPlaceAndCloseLeavesIt(t *testing.T) { dir := t.TempDir() writeFile(t, filepath.Join(dir, "chrome", "Local State"), []byte("{}")) - d := Open(dir) - p, err := d.Snapshot("chrome").Path("Local State") + snapshotDir := Open(dir) + capturedPath, err := snapshotDir.Snapshot("chrome").Path("Local State") require.NoError(t, err) - assert.Equal(t, filepath.Join(dir, "chrome", "Local State"), p) + assert.Equal(t, filepath.Join(dir, "chrome", "Local State"), capturedPath) - require.NoError(t, d.Close()) - assert.FileExists(t, p) + require.NoError(t, snapshotDir.Close()) + assert.FileExists(t, capturedPath) } func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) { from := userDataDir(t) - d, err := Temp() + snapshotDir, err := Temp() require.NoError(t, err) - defer d.Close() + defer snapshotDir.Close() - require.NoError(t, d.Capture(context.Background(), []File{ - {DirID: "chrome", From: from, Rel: "Local State"}, - {DirID: "chrome", From: from, Rel: "Default/Network/Cookies"}, - {DirID: "chrome", From: from, Rel: "Default/Local Storage/leveldb", IsDir: true}, + require.NoError(t, snapshotDir.Capture(context.Background(), []File{ + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Local State"}, + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Network/Cookies"}, + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Local Storage/leveldb", IsDir: true}, })) - s := d.Snapshot("chrome") - cookies, err := s.Path("Default/Network/Cookies") + dirSnapshot := snapshotDir.Snapshot("chrome") + cookies, err := dirSnapshot.Path("Default/Network/Cookies") require.NoError(t, err) - assert.Equal(t, filepath.Join(d.Path(), "chrome", "Default", "Network", "Cookies"), cookies) + assert.Equal(t, filepath.Join(snapshotDir.Path(), "chrome", "Default", "Network", "Cookies"), cookies) for suffix, want := range map[string]string{"-wal": "wal", "-shm": "shm"} { got, err := os.ReadFile(cookies + suffix) require.NoError(t, err) assert.Equal(t, want, string(got)) } - leveldb, err := s.Path("Default/Local Storage/leveldb") + leveldb, err := dirSnapshot.Path("Default/Local Storage/leveldb") require.NoError(t, err) assert.FileExists(t, filepath.Join(leveldb, "CURRENT")) assert.FileExists(t, filepath.Join(leveldb, "000003.log")) @@ -87,85 +87,85 @@ func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) { func TestCapture_KeepsGoingPastFailedFiles(t *testing.T) { from := userDataDir(t) - d, err := Temp() + snapshotDir, err := Temp() require.NoError(t, err) - defer d.Close() + defer snapshotDir.Close() - require.NoError(t, d.Capture(context.Background(), []File{ - {DirID: "chrome", From: from, Rel: "Default/History"}, // vanished before Capture reached it - {DirID: "chrome", From: from, Rel: "Default/Network"}, // a directory read as a file, so the copy fails - {DirID: "chrome", From: from, Rel: "Local State"}, + require.NoError(t, snapshotDir.Capture(context.Background(), []File{ + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/History"}, // vanished before Capture reached it + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Network"}, // a directory read as a file, so the copy fails + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Local State"}, })) - s := d.Snapshot("chrome") - _, err = s.Path("Default/History") + dirSnapshot := snapshotDir.Snapshot("chrome") + _, err = dirSnapshot.Path("Default/History") require.ErrorIs(t, err, fs.ErrNotExist) - _, err = s.Path("Default/Network") + _, err = dirSnapshot.Path("Default/Network") require.Error(t, err) require.NotErrorIs(t, err, fs.ErrNotExist, "a failed copy reads back as its own error") - _, err = s.Path("Local State") + _, err = dirSnapshot.Path("Local State") require.NoError(t, err, "one file's failure does not stop the rest") } func TestCapture_StopsWhenCancelled(t *testing.T) { from := userDataDir(t) - d, err := Temp() + snapshotDir, err := Temp() require.NoError(t, err) - defer d.Close() + defer snapshotDir.Close() ctx, cancel := context.WithCancel(context.Background()) cancel() - err = d.Capture(ctx, []File{{DirID: "chrome", From: from, Rel: "Local State"}}) + err = snapshotDir.Capture(ctx, []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Local State"}}) require.ErrorIs(t, err, context.Canceled) - _, err = d.Snapshot("chrome").Path("Local State") + _, err = snapshotDir.Snapshot("chrome").Path("Local State") require.ErrorIs(t, err, fs.ErrNotExist) } func TestCapture_StaysInsideItsOwnSnapshot(t *testing.T) { from := userDataDir(t) - d, err := Temp() + snapshotDir, err := Temp() require.NoError(t, err) - defer d.Close() + defer snapshotDir.Close() - require.NoError(t, d.Capture(context.Background(), []File{ - {DirID: "chrome", From: from, Rel: "../edge/Local State"}, - {DirID: "../chrome", From: from, Rel: "Local State"}, - {DirID: "chrome/sub", From: from, Rel: "Local State"}, - {DirID: ".", From: from, Rel: "Local State"}, - {DirID: "", From: from, Rel: "Local State"}, + require.NoError(t, snapshotDir.Capture(context.Background(), []File{ + {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "../edge/Local State"}, + {UserDataDirID: "../chrome", UserDataDirPath: from, RelativePath: "Local State"}, + {UserDataDirID: "chrome/sub", UserDataDirPath: from, RelativePath: "Local State"}, + {UserDataDirID: ".", UserDataDirPath: from, RelativePath: "Local State"}, + {UserDataDirID: "", UserDataDirPath: from, RelativePath: "Local State"}, })) - _, err = d.Snapshot("chrome").Path("../edge/Local State") + _, err = snapshotDir.Snapshot("chrome").Path("../edge/Local State") require.Error(t, err) - entries, err := os.ReadDir(d.Path()) + entries, err := os.ReadDir(snapshotDir.Path()) require.NoError(t, err) assert.Empty(t, entries, "nothing may be written outside a file's own snapshot") } func TestSnapshot_UncapturedFileIsNotExist(t *testing.T) { - d, err := Temp() + snapshotDir, err := Temp() require.NoError(t, err) - defer d.Close() + defer snapshotDir.Close() - _, err = d.Snapshot("chrome").Path("Default/Login Data") + _, err = snapshotDir.Snapshot("chrome").Path("Default/Login Data") require.ErrorIs(t, err, fs.ErrNotExist) } func TestCapture_ALaterCaptureReplacesAnEarlierFailure(t *testing.T) { from := t.TempDir() - d, err := Temp() + snapshotDir, err := Temp() require.NoError(t, err) - defer d.Close() + defer snapshotDir.Close() - require.NoError(t, d.Capture(context.Background(), []File{{DirID: "chrome", From: from, Rel: "Default/History"}})) - _, err = d.Snapshot("chrome").Path("Default/./History") + require.NoError(t, snapshotDir.Capture(context.Background(), []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/History"}})) + _, err = snapshotDir.Snapshot("chrome").Path("Default/./History") require.ErrorIs(t, err, fs.ErrNotExist, "a failure is found under any spelling of the path") writeFile(t, filepath.Join(from, "Default", "History"), []byte("history")) - require.NoError(t, d.Capture(context.Background(), []File{{DirID: "chrome", From: from, Rel: "Default/./History"}})) - _, err = d.Snapshot("chrome").Path("Default/History") + require.NoError(t, snapshotDir.Capture(context.Background(), []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/./History"}})) + _, err = snapshotDir.Snapshot("chrome").Path("Default/History") require.NoError(t, err) } diff --git a/internal/snapshot/zip.go b/internal/snapshot/zip.go index 03c9f98..1b22450 100644 --- a/internal/snapshot/zip.go +++ b/internal/snapshot/zip.go @@ -11,43 +11,43 @@ import ( "strings" ) -// Zip writes the snapshot directory to dst through a temp file beside it, so a failed archive leaves no partial file. -func (d *Dir) Zip(dst string) (err error) { - target, existing, err := zipTarget(dst) +// Zip writes to archivePath through a temp file beside it, so a failed archive leaves no partial file. +func (d *Dir) Zip(archivePath string) (err error) { + target, existing, err := zipTarget(archivePath) if err != nil { return err } - tmp, err := createBeside(target) + temporary, err := createBeside(target) if err != nil { return err } defer func() { if err != nil { - os.Remove(tmp.Name()) + os.Remove(temporary.Name()) } }() - if err := writeZip(tmp, d.path); err != nil { - return errors.Join(err, tmp.Close()) + if err := writeZip(temporary, d.path); err != nil { + return errors.Join(err, temporary.Close()) } if existing != nil { - if err := tmp.Chmod(existing.Mode().Perm()); err != nil { - return errors.Join(fmt.Errorf("keep the mode of %s: %w", dst, err), tmp.Close()) + if err := temporary.Chmod(existing.Mode().Perm()); err != nil { + return errors.Join(fmt.Errorf("keep the mode of %s: %w", archivePath, err), temporary.Close()) } } - if err := tmp.Close(); err != nil { - return fmt.Errorf("close zip %s: %w", tmp.Name(), err) + if err := temporary.Close(); err != nil { + return fmt.Errorf("close zip %s: %w", temporary.Name(), err) } - if err := os.Rename(tmp.Name(), target); err != nil { + if err := os.Rename(temporary.Name(), target); err != nil { return fmt.Errorf("move zip into place: %w", err) } return nil } -// Replacing an archive through a symlinked dst keeps the link and the mode os.Create would have kept. -func zipTarget(dst string) (string, fs.FileInfo, error) { - target := dst - if resolved, err := filepath.EvalSymlinks(dst); err == nil { +// zipTarget follows a symlinked archivePath, so the replaced archive keeps the link and the mode os.Create would keep. +func zipTarget(archivePath string) (string, fs.FileInfo, error) { + target := archivePath + if resolved, err := filepath.EvalSymlinks(archivePath); err == nil { target = resolved } info, err := os.Stat(target) @@ -55,83 +55,83 @@ func zipTarget(dst string) (string, fs.FileInfo, error) { return target, nil, nil } if err != nil { - return "", nil, fmt.Errorf("create %s: %w", dst, err) + return "", nil, fmt.Errorf("create %s: %w", archivePath, err) } if info.IsDir() { - return "", nil, fmt.Errorf("create %s: is a directory", dst) + return "", nil, fmt.Errorf("create %s: is a directory", archivePath) } return target, info, nil } // createBeside keeps os.Create's umask-governed mode for a new archive, which os.CreateTemp would force to 0600. -func createBeside(dst string) (*os.File, error) { - dir, base := filepath.Split(dst) +func createBeside(target string) (*os.File, error) { + dir, base := filepath.Split(target) for i := 0; i < 100; i++ { name := filepath.Join(dir, fmt.Sprintf("%s.%d-%d.tmp", base, os.Getpid(), i)) - f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o666) + file, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o666) if errors.Is(err, fs.ErrExist) { continue } if err != nil { - return nil, fmt.Errorf("create %s: %w", dst, err) + return nil, fmt.Errorf("create %s: %w", target, err) } - return f, nil + return file, nil } - return nil, fmt.Errorf("create %s: no free temp name beside it", dst) + return nil, fmt.Errorf("create %s: no free temp name beside it", target) } -func writeZip(w io.Writer, root string) error { - zw := zip.NewWriter(w) - walkErr := filepath.WalkDir(root, func(p string, e fs.DirEntry, err error) error { +func writeZip(writer io.Writer, root string) error { + zipWriter := zip.NewWriter(writer) + walkErr := filepath.WalkDir(root, func(walkedPath string, entry fs.DirEntry, err error) error { if err != nil { return err } - if e.IsDir() { + if entry.IsDir() { return nil } - rel, err := filepath.Rel(root, p) + relativePath, err := filepath.Rel(root, walkedPath) if err != nil { return err } - return addZipEntry(zw, p, filepath.ToSlash(rel)) + return addZipEntry(zipWriter, walkedPath, filepath.ToSlash(relativePath)) }) if walkErr != nil { - return errors.Join(fmt.Errorf("zip %s: %w", root, walkErr), zw.Close()) + return errors.Join(fmt.Errorf("zip %s: %w", root, walkErr), zipWriter.Close()) } - if err := zw.Close(); err != nil { + if err := zipWriter.Close(); err != nil { return fmt.Errorf("close zip: %w", err) } return nil } -func addZipEntry(zw *zip.Writer, path, name string) error { - w, err := zw.Create(name) +func addZipEntry(zipWriter *zip.Writer, path, name string) error { + writer, err := zipWriter.Create(name) if err != nil { return err } - src, err := os.Open(path) + file, err := os.Open(path) if err != nil { return err } - defer src.Close() - _, err = io.Copy(w, src) + defer file.Close() + _, err = io.Copy(writer, file) return err } -func unzip(src, destDir string) error { - r, err := zip.OpenReader(src) +func unzip(archivePath, destDir string) error { + zipReader, err := zip.OpenReader(archivePath) if err != nil { - return fmt.Errorf("open zip %s: %w", src, err) + return fmt.Errorf("open zip %s: %w", archivePath, err) } - defer r.Close() + defer zipReader.Close() root := filepath.Clean(destDir) - for _, f := range r.File { - target := filepath.Join(root, filepath.FromSlash(f.Name)) + for _, zipFile := range zipReader.File { + target := filepath.Join(root, filepath.FromSlash(zipFile.Name)) if target != root && !strings.HasPrefix(target, root+string(os.PathSeparator)) { - return fmt.Errorf("zip entry %q escapes destination", f.Name) + return fmt.Errorf("zip entry %q escapes destination", zipFile.Name) } - if f.FileInfo().IsDir() { + if zipFile.FileInfo().IsDir() { if err := os.MkdirAll(target, 0o700); err != nil { return err } @@ -140,19 +140,19 @@ func unzip(src, destDir string) error { if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { return err } - if err := writeZipEntry(f, target); err != nil { + if err := writeZipEntry(zipFile, target); err != nil { return err } } return nil } -func writeZipEntry(f *zip.File, target string) (err error) { - rc, err := f.Open() +func writeZipEntry(zipFile *zip.File, target string) (err error) { + entryReader, err := zipFile.Open() if err != nil { return err } - defer rc.Close() + defer entryReader.Close() out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) if err != nil { @@ -161,7 +161,7 @@ func writeZipEntry(f *zip.File, target string) (err error) { defer func() { err = errors.Join(err, out.Close()) }() for { - _, err := io.CopyN(out, rc, 1<<20) + _, err := io.CopyN(out, entryReader, 1<<20) if errors.Is(err, io.EOF) { return nil } diff --git a/internal/snapshot/zip_test.go b/internal/snapshot/zip_test.go index 992db97..597050d 100644 --- a/internal/snapshot/zip_test.go +++ b/internal/snapshot/zip_test.go @@ -20,39 +20,39 @@ func TestZipUnzip_RoundTrip(t *testing.T) { "chrome/Default/Network/Cookies": []byte("cookie-bytes"), "sub/big.bin": bytes.Repeat([]byte("A"), 3<<20), // exercises the chunked copy loop } - src := t.TempDir() - for rel, data := range files { - writeFile(t, filepath.Join(src, filepath.FromSlash(rel)), data) + snapshotRoot := t.TempDir() + for relativePath, data := range files { + writeFile(t, filepath.Join(snapshotRoot, filepath.FromSlash(relativePath)), data) } archive := filepath.Join(t.TempDir(), "out.zip") - require.NoError(t, Open(src).Zip(archive)) + require.NoError(t, Open(snapshotRoot).Zip(archive)) - zr, err := zip.OpenReader(archive) + zipReader, err := zip.OpenReader(archive) require.NoError(t, err) - for _, f := range zr.File { - assert.NotContains(t, f.Name, `\`, "zip entry names are forward-slash") + for _, zipFile := range zipReader.File { + assert.NotContains(t, zipFile.Name, `\`, "zip entry names are forward-slash") } - require.NoError(t, zr.Close()) + require.NoError(t, zipReader.Close()) - d, err := Unzip(archive) + snapshotDir, err := Unzip(archive) require.NoError(t, err) - for rel, want := range files { - got, err := os.ReadFile(filepath.Join(d.Path(), filepath.FromSlash(rel))) - require.NoError(t, err, rel) - assert.True(t, bytes.Equal(want, got), "%s: got %d bytes, want %d", rel, len(got), len(want)) + for relativePath, want := range files { + got, err := os.ReadFile(filepath.Join(snapshotDir.Path(), filepath.FromSlash(relativePath))) + require.NoError(t, err, relativePath) + assert.True(t, bytes.Equal(want, got), "%s: got %d bytes, want %d", relativePath, len(got), len(want)) } - require.NoError(t, d.Close()) - assert.NoDirExists(t, d.Path()) + require.NoError(t, snapshotDir.Close()) + assert.NoDirExists(t, snapshotDir.Path()) } func TestUnzip_RejectsZipSlipAndCleansUp(t *testing.T) { - tmp := privateTempRoot(t) + tempRoot := privateTempRoot(t) archive := zipWith(t, "../escape.txt") _, err := Unzip(archive) require.Error(t, err) - entries, err := os.ReadDir(tmp) + entries, err := os.ReadDir(tempRoot) require.NoError(t, err) assert.Empty(t, entries, "a rejected archive leaves neither the escaped file nor the snapshot directory behind") } @@ -90,7 +90,7 @@ func TestZip_FailureKeepsAnExistingArchive(t *testing.T) { func TestZip_IntoADirectoryFailsBeforeWriting(t *testing.T) { out := t.TempDir() - require.Error(t, Open(snapshotSource(t)).Zip(out)) + require.Error(t, Open(snapshotFixture(t)).Zip(out)) entries, err := os.ReadDir(out) require.NoError(t, err) assert.Empty(t, entries) @@ -100,7 +100,7 @@ func TestZip_ModeMatchesOSCreateAndSurvivesReplacement(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("POSIX permission bits") } - src := snapshotSource(t) + snapshotRoot := snapshotFixture(t) out := t.TempDir() probe, err := os.Create(filepath.Join(out, "probe")) require.NoError(t, err) @@ -109,7 +109,7 @@ func TestZip_ModeMatchesOSCreateAndSurvivesReplacement(t *testing.T) { require.NoError(t, err) fresh := filepath.Join(out, "fresh.zip") - require.NoError(t, Open(src).Zip(fresh)) + require.NoError(t, Open(snapshotRoot).Zip(fresh)) got, err := os.Stat(fresh) require.NoError(t, err) assert.Equal(t, want.Mode().Perm(), got.Mode().Perm(), "a new archive gets the mode os.Create gives a file") @@ -117,7 +117,7 @@ func TestZip_ModeMatchesOSCreateAndSurvivesReplacement(t *testing.T) { private := filepath.Join(out, "private.zip") writeFile(t, private, []byte("old")) require.NoError(t, os.Chmod(private, 0o600)) - require.NoError(t, Open(src).Zip(private)) + require.NoError(t, Open(snapshotRoot).Zip(private)) got, err = os.Stat(private) require.NoError(t, err) assert.Equal(t, fs.FileMode(0o600), got.Mode().Perm(), "a replaced archive keeps its mode") @@ -133,37 +133,37 @@ func TestZip_WritesThroughASymlinkedArchive(t *testing.T) { link := filepath.Join(out, "link.zip") require.NoError(t, os.Symlink("real.zip", link)) - require.NoError(t, Open(snapshotSource(t)).Zip(link)) + require.NoError(t, Open(snapshotFixture(t)).Zip(link)) info, err := os.Lstat(link) require.NoError(t, err) assert.NotZero(t, info.Mode()&fs.ModeSymlink, "the link stays a link") - zr, err := zip.OpenReader(target) + zipReader, err := zip.OpenReader(target) require.NoError(t, err) - defer zr.Close() - assert.Len(t, zr.File, 1, "the archive lands in the link's target") + defer zipReader.Close() + assert.Len(t, zipReader.File, 1, "the archive lands in the link's target") } -func snapshotSource(t *testing.T) string { +func snapshotFixture(t *testing.T) string { t.Helper() - src := t.TempDir() - writeFile(t, filepath.Join(src, "chrome", "Local State"), []byte("{}")) - return src + root := t.TempDir() + writeFile(t, filepath.Join(root, "chrome", "Local State"), []byte("{}")) + return root } func zipWith(t *testing.T, names ...string) string { t.Helper() archive := filepath.Join(t.TempDir(), "test.zip") - f, err := os.Create(archive) + file, err := os.Create(archive) require.NoError(t, err) - zw := zip.NewWriter(f) + zipWriter := zip.NewWriter(file) for _, name := range names { - w, err := zw.Create(name) + writer, err := zipWriter.Create(name) require.NoError(t, err) - _, err = w.Write([]byte(name)) + _, err = writer.Write([]byte(name)) require.NoError(t, err) } - require.NoError(t, zw.Close()) - require.NoError(t, f.Close()) + require.NoError(t, zipWriter.Close()) + require.NoError(t, file.Close()) return archive } @@ -171,20 +171,20 @@ func TestZip_ReplacesAnExistingArchive(t *testing.T) { archive := filepath.Join(t.TempDir(), "browser-data.zip") writeFile(t, archive, []byte("stale")) - require.NoError(t, Open(snapshotSource(t)).Zip(archive)) - zr, err := zip.OpenReader(archive) + require.NoError(t, Open(snapshotFixture(t)).Zip(archive)) + zipReader, err := zip.OpenReader(archive) require.NoError(t, err) - defer zr.Close() - require.Len(t, zr.File, 1) - assert.Equal(t, "chrome/Local State", zr.File[0].Name) + defer zipReader.Close() + require.Len(t, zipReader.File, 1) + assert.Equal(t, "chrome/Local State", zipReader.File[0].Name) } // privateTempRoot points os.TempDir at a fresh directory, so a test can see everything Temp leaves behind. func privateTempRoot(t *testing.T) string { t.Helper() dir := t.TempDir() - for _, env := range []string{"TMPDIR", "TMP", "TEMP"} { - t.Setenv(env, dir) + for _, variable := range []string{"TMPDIR", "TMP", "TEMP"} { + t.Setenv(variable, dir) } return dir } diff --git a/internal/sqlitex/query.go b/internal/sqlitex/query.go index 360a1af..bc4ec59 100644 --- a/internal/sqlitex/query.go +++ b/internal/sqlitex/query.go @@ -11,26 +11,26 @@ func CountRows(dbPath string, journalOff bool, query string) (int, error) { if _, err := os.Stat(dbPath); err != nil { return 0, fmt.Errorf("database file: %w", err) } - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) if err != nil { return 0, err } - defer db.Close() + defer database.Close() if journalOff { - if _, err := db.Exec("PRAGMA journal_mode=off"); err != nil { + if _, err := database.Exec("PRAGMA journal_mode=off"); err != nil { return 0, err } } var count int - if err := db.QueryRow(query).Scan(&count); err != nil { + if err := database.QueryRow(query).Scan(&count); err != nil { return 0, fmt.Errorf("count rows: %w", err) } return count, nil } -// Rows that fail to scan are skipped and logged at debug level. +// QueryRows skips rows that fail to scan and logs them at debug level. func QueryRows[T any](dbPath string, journalOff bool, query string, scanRow func(*sql.Rows) (T, error)) ([]T, error) { var items []T err := eachRow(dbPath, journalOff, query, func(rows *sql.Rows) error { diff --git a/internal/sqlitex/sqlite.go b/internal/sqlitex/sqlite.go index 041d735..f01ff19 100644 --- a/internal/sqlitex/sqlite.go +++ b/internal/sqlitex/sqlite.go @@ -11,25 +11,25 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/log" ) -// journalOff is for Firefox databases; the file is checked first so sql.Open never creates an empty one. +// eachRow takes journalOff for Firefox databases; the file is checked first so sql.Open never creates an empty one. // A row whose scanFn returns an error is skipped and logged at debug level. func eachRow(dbPath string, journalOff bool, query string, scanFn func(*sql.Rows) error) error { if _, err := os.Stat(dbPath); err != nil { return fmt.Errorf("database file: %w", err) } - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) if err != nil { return err } - defer db.Close() + defer database.Close() if journalOff { - if _, err := db.Exec("PRAGMA journal_mode=off"); err != nil { + if _, err := database.Exec("PRAGMA journal_mode=off"); err != nil { return err } } - rows, err := db.Query(query) + rows, err := database.Query(query) if err != nil { return err } diff --git a/internal/sqlitex/sqlite_test.go b/internal/sqlitex/sqlite_test.go index c4e8127..4efd4d8 100644 --- a/internal/sqlitex/sqlite_test.go +++ b/internal/sqlitex/sqlite_test.go @@ -13,14 +13,14 @@ func TestEachRow(t *testing.T) { dir := t.TempDir() dbPath := filepath.Join(dir, "test.db") - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) require.NoError(t, err) - _, err = db.Exec("CREATE TABLE items (id INTEGER, name TEXT)") + _, err = database.Exec("CREATE TABLE items (id INTEGER, name TEXT)") require.NoError(t, err) - _, err = db.Exec("INSERT INTO items VALUES (1, 'alpha'), (2, 'beta'), (3, 'gamma')") + _, err = database.Exec("INSERT INTO items VALUES (1, 'alpha'), (2, 'beta'), (3, 'gamma')") require.NoError(t, err) - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) var names []string err = eachRow(dbPath, false, "SELECT name FROM items ORDER BY id", func(rows *sql.Rows) error { @@ -40,21 +40,21 @@ func TestEachRow_JournalOff(t *testing.T) { dir := t.TempDir() dbPath := filepath.Join(dir, "test.db") - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) require.NoError(t, err) - _, err = db.Exec("CREATE TABLE t (v TEXT)") + _, err = database.Exec("CREATE TABLE t (v TEXT)") require.NoError(t, err) - _, err = db.Exec("INSERT INTO t VALUES ('ok')") + _, err = database.Exec("INSERT INTO t VALUES ('ok')") require.NoError(t, err) - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) var values []string err = eachRow(dbPath, true, "SELECT v FROM t", func(rows *sql.Rows) error { - var v string - if err := rows.Scan(&v); err != nil { + var value string + if err := rows.Scan(&value); err != nil { return err } - values = append(values, v) + values = append(values, value) return nil }) require.NoError(t, err) @@ -72,11 +72,11 @@ func TestEachRow_BadQuery(t *testing.T) { dir := t.TempDir() dbPath := filepath.Join(dir, "test.db") - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) require.NoError(t, err) - _, err = db.Exec("CREATE TABLE t (v TEXT)") + _, err = database.Exec("CREATE TABLE t (v TEXT)") require.NoError(t, err) - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) err = eachRow(dbPath, false, "SELECT nonexistent FROM t", func(rows *sql.Rows) error { return nil @@ -128,31 +128,31 @@ func TestCountRows(t *testing.T) { }, } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { var dbPath string - if tt.schema != "" { + if testCase.schema != "" { dbPath = filepath.Join(t.TempDir(), "test.db") - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) require.NoError(t, err) - _, err = db.Exec(tt.schema) + _, err = database.Exec(testCase.schema) require.NoError(t, err) - if tt.inserts != "" { - _, err = db.Exec(tt.inserts) + if testCase.inserts != "" { + _, err = database.Exec(testCase.inserts) require.NoError(t, err) } - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) } else { dbPath = "/nonexistent/path.db" } - count, err := CountRows(dbPath, tt.journalOff, tt.query) - if tt.wantErr { + count, err := CountRows(dbPath, testCase.journalOff, testCase.query) + if testCase.wantErr { require.Error(t, err) return } require.NoError(t, err) - assert.Equal(t, tt.wantCount, count) + assert.Equal(t, testCase.wantCount, count) }) } } @@ -161,13 +161,13 @@ func TestQueryRows(t *testing.T) { dir := t.TempDir() dbPath := filepath.Join(dir, "test.db") - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) require.NoError(t, err) - _, err = db.Exec("CREATE TABLE users (name TEXT, age INTEGER)") + _, err = database.Exec("CREATE TABLE users (name TEXT, age INTEGER)") require.NoError(t, err) - _, err = db.Exec("INSERT INTO users VALUES ('alice', 30), ('bob', 25)") + _, err = database.Exec("INSERT INTO users VALUES ('alice', 30), ('bob', 25)") require.NoError(t, err) - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) type user struct { Name string @@ -176,9 +176,9 @@ func TestQueryRows(t *testing.T) { users, err := QueryRows(dbPath, false, "SELECT name, age FROM users ORDER BY name", func(rows *sql.Rows) (user, error) { - var u user - err := rows.Scan(&u.Name, &u.Age) - return u, err + var found user + err := rows.Scan(&found.Name, &found.Age) + return found, err }) require.NoError(t, err) @@ -189,19 +189,19 @@ func TestQueryRows_Empty(t *testing.T) { dir := t.TempDir() dbPath := filepath.Join(dir, "test.db") - db, err := sql.Open("sqlite", dbPath) + database, err := sql.Open("sqlite", dbPath) require.NoError(t, err) - _, err = db.Exec("CREATE TABLE empty (v TEXT)") + _, err = database.Exec("CREATE TABLE empty (v TEXT)") require.NoError(t, err) - require.NoError(t, db.Close()) + require.NoError(t, database.Close()) results, err := QueryRows(dbPath, false, "SELECT v FROM empty", func(rows *sql.Rows) (string, error) { - var v string - if err := rows.Scan(&v); err != nil { + var value string + if err := rows.Scan(&value); err != nil { return "", err } - return v, nil + return value, nil }) require.NoError(t, err) diff --git a/internal/timeconv/timeconv.go b/internal/timeconv/timeconv.go index 7f90faf..7744bfb 100644 --- a/internal/timeconv/timeconv.go +++ b/internal/timeconv/timeconv.go @@ -4,57 +4,57 @@ package timeconv import "time" const ( - // Chromium's base::Time::kTimeTToMicrosecondsOffset, from 1601-01-01 to the Unix epoch. + // chromiumEpochOffsetMicros is Chromium's base::Time::kTimeTToMicrosecondsOffset, from 1601-01-01 to the Unix epoch. chromiumEpochOffsetMicros = 11644473600000000 coreDataEpochOffset = 978307200 - // Keeps CoreData inside int64 and below year 9999 before the float conversion. + // maxCoreDataSeconds keeps CoreData inside int64 and below year 9999 before the float conversion. maxCoreDataSeconds = 252423993600 ) // Chromium converts base::Time, microseconds since 1601-01-01 UTC. -func Chromium(us int64) time.Time { - if us <= 0 { +func Chromium(microseconds int64) time.Time { + if microseconds <= 0 { return time.Time{} } - return jsonSafe(time.UnixMicro(us - chromiumEpochOffsetMicros).UTC()) + return jsonSafe(time.UnixMicro(microseconds - chromiumEpochOffsetMicros).UTC()) } -func UnixMicro(us int64) time.Time { - if us <= 0 { +func UnixMicro(microseconds int64) time.Time { + if microseconds <= 0 { return time.Time{} } - return jsonSafe(time.UnixMicro(us).UTC()) + return jsonSafe(time.UnixMicro(microseconds).UTC()) } -func UnixMilli(ms int64) time.Time { - if ms <= 0 { +func UnixMilli(milliseconds int64) time.Time { + if milliseconds <= 0 { return time.Time{} } - return jsonSafe(time.UnixMilli(ms).UTC()) + return jsonSafe(time.UnixMilli(milliseconds).UTC()) } -func Unix(s int64) time.Time { - if s <= 0 { +func Unix(seconds int64) time.Time { + if seconds <= 0 { return time.Time{} } - return jsonSafe(time.Unix(s, 0).UTC()) + return jsonSafe(time.Unix(seconds, 0).UTC()) } // CoreData converts CFAbsoluteTime, seconds since 2001-01-01 UTC. -func CoreData(s float64) time.Time { - if s <= 0 || s > maxCoreDataSeconds { +func CoreData(seconds float64) time.Time { + if seconds <= 0 || seconds > maxCoreDataSeconds { return time.Time{} } - whole := int64(s) - frac := s - float64(whole) - nanos := int64(frac * 1e9) + whole := int64(seconds) + fraction := seconds - float64(whole) + nanos := int64(fraction * 1e9) return time.Unix(whole+coreDataEpochOffset, nanos).UTC() } -// time.Time.MarshalJSON rejects years outside [1, 9999], so such values export as the zero time. -func jsonSafe(t time.Time) time.Time { - if t.Year() < 1 || t.Year() > 9999 { +// jsonSafe turns years outside [1, 9999], which time.Time.MarshalJSON rejects, into the zero time. +func jsonSafe(timestamp time.Time) time.Time { + if timestamp.Year() < 1 || timestamp.Year() > 9999 { return time.Time{} } - return t + return timestamp } diff --git a/internal/timeconv/timeconv_test.go b/internal/timeconv/timeconv_test.go index 4f1525e..8b6ecc4 100644 --- a/internal/timeconv/timeconv_test.go +++ b/internal/timeconv/timeconv_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" ) -// Anchor: 2024-01-15T10:30:00Z. +// anchorUnixSeconds is 2024-01-15T10:30:00Z. const anchorUnixSeconds = int64(1705314600) const anchorCoreDataSeconds = anchorUnixSeconds - 978307200 @@ -93,15 +93,15 @@ func TestUnixUnits_AlwaysUTC(t *testing.T) { } func TestUnixUnits_SameMomentAcrossUnits(t *testing.T) { - us := UnixMicro(anchorUnixSeconds * 1_000_000) - ms := UnixMilli(anchorUnixSeconds * 1_000) - s := Unix(anchorUnixSeconds) - assert.True(t, us.Equal(ms)) - assert.True(t, ms.Equal(s)) + fromMicros := UnixMicro(anchorUnixSeconds * 1_000_000) + fromMillis := UnixMilli(anchorUnixSeconds * 1_000) + fromSeconds := Unix(anchorUnixSeconds) + assert.True(t, fromMicros.Equal(fromMillis)) + assert.True(t, fromMillis.Equal(fromSeconds)) } func TestUnixUnits_OutOfJSONRangeReturnsZero(t *testing.T) { - for _, tc := range []struct { + for _, testCase := range []struct { name string got time.Time }{ @@ -109,10 +109,10 @@ func TestUnixUnits_OutOfJSONRangeReturnsZero(t *testing.T) { {"millis", UnixMilli(1 << 60)}, {"micros", UnixMicro(1 << 62)}, } { - t.Run(tc.name, func(t *testing.T) { - b, err := tc.got.MarshalJSON() + t.Run(testCase.name, func(t *testing.T) { + encoded, err := testCase.got.MarshalJSON() require.NoError(t, err) - assert.JSONEq(t, `"0001-01-01T00:00:00Z"`, string(b)) + assert.JSONEq(t, `"0001-01-01T00:00:00Z"`, string(encoded)) }) } } diff --git a/rfcs/000-goals-and-constraints.md b/rfcs/000-goals-and-constraints.md index 173dcde..cde98ea 100644 --- a/rfcs/000-goals-and-constraints.md +++ b/rfcs/000-goals-and-constraints.md @@ -38,12 +38,12 @@ The external interface is frozen at v1.1.0: every item below behaves exactly as | Output files | one `.` per non-empty category (`password.csv`, `cookie.json`, …); `--zip` packs them into `/.zip` | | Formats | `csv` (UTF-8 BOM), `json` (two-space indent, v1.1.0's HTML escaping), `cookie-editor` | | Fields | snake_case keys and columns, `browser` and `profile` first, then v1.1.0's fields in v1.1.0's order | -| Stamp values | `browser` = the display name (`Chrome`, `Microsoft Edge`); `profile` = v1.1.0's profile name ([RFC-003](003-core-types.md)) | +| Browser, profile | `browser` = the display name (`Chrome`, `Microsoft Edge`); `profile` = v1.1.0's profile name ([RFC-003](003-core-types.md)) | | `keys.json` | dump version `"2"`, v1.1.0's schema, readable by v1.1.0 | | Archive | zip layout `/`, readable by v1.1.0 `restore` | | Exit status | `0` when the run completes (including partial results and "no browsers found"); `1` when it cannot start or finish | -Not part of the contract: log lines and the human-readable summary on stderr, and row order where v1.1.0's order is unspecified or wrong. Output differs from v1.1.0 only for listed bug fixes where v1.1.0's output was wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, Firefox logins from a profile whose key cannot be recovered, Yandex logins and cards whose data key cannot be recovered, the `browser` value `restore` stamps, CocCoc cookies on a Windows machine that also has Yandex, and the `--zip` archive's file mode ([RFC-008](008-output-and-export.md)); each is called out where it is fixed. +Not part of the contract: log lines and the human-readable summary on stderr, and row order where v1.1.0's order is unspecified or wrong. Output differs from v1.1.0 only for listed bug fixes where v1.1.0's output was wrong — Firefox history order, Firefox bookmark fields, Safari bookmark IDs, Firefox logins from a profile whose key cannot be recovered, Yandex logins and cards whose data key cannot be recovered, the `browser` value `restore` sets, CocCoc cookies on a Windows machine that also has Yandex, and the `--zip` archive's file mode ([RFC-008](008-output-and-export.md)); each is called out where it is fixed. ## Hard constraints diff --git a/rfcs/001-architecture-and-pipeline.md b/rfcs/001-architecture-and-pipeline.md index e5441df..19d7805 100644 --- a/rfcs/001-architecture-and-pipeline.md +++ b/rfcs/001-architecture-and-pipeline.md @@ -6,7 +6,7 @@ A run is a one-way pipeline of seven stages. Each stage takes the previous stage ``` ┌───────────┐ - argv ───▶ │ Validate │ flags → app.Request; no browser files touched, nothing created + argv ───▶ │ Validate │ flags → app.Options; no browser files touched, nothing created └─────┬─────┘ ▼ ┌───────────┐ @@ -40,23 +40,23 @@ A run is a one-way pipeline of seven stages. Each stage takes the previous stage ### 1. Validate -Turns parsed flags into a typed `app.Request`: which categories, which browser, the `-p` override, output directory, format, `--zip`, and how the keychain password is supplied. Rejects bad input here — an unknown format, category, or browser ID, or an output directory that cannot be created, fails now with exit status `1` (v1.1.0's status, except for an unknown browser ID, which there found nothing and exited `0`; [RFC-009](009-cli-surface.md)), **before** any browser is discovered and **before** any keychain prompt. v1.1.0 checked `-c` and `-f` only after discovery and the prompt; validating first designs that ordering bug out. +Turns parsed flags into a typed `app.Options`: which categories, which browser, the `-p` override, output directory, format, `--zip`, and how the keychain password is supplied. Rejects bad input here — an unknown format, category, or browser ID, or an output directory that cannot be created, fails now with exit status `1` (v1.1.0's status, except for an unknown browser ID, which there found nothing and exited `0`; [RFC-009](009-cli-surface.md)), **before** any browser is discovered and **before** any keychain prompt. v1.1.0 checked `-c` and `-f` only after discovery and the prompt; validating first designs that ordering bug out. Validate touches no browser files and creates nothing: the output-directory check only confirms that `-d` is a directory or that its nearest existing ancestor is a writable directory. For `restore`, reading `--keys` is part of Validate, because `-b` there is checked against the dump's vaults ([RFC-009](009-cli-surface.md)). `-p` combined with `-b all` is ignored, as in v1.1.0, but with a warning rather than silently. -**In:** parsed flags. **Out:** a validated `app.Request`. **Owner:** `cmd/hack-browser-data` (flag wiring) + `app.Validate` (rules). +**In:** parsed flags. **Out:** a validated `app.Options`. **Owner:** `cmd/hack-browser-data` (flag wiring) + `app.Validate` (rules). ### 2. Discover Enumerates which supported browsers are present and which profiles each one has, on this OS. Produces `browser.UserDataDir` values — one per data directory found, so two Arc packages are two user data dirs — each holding its `Profile` list. Discovery is read-only metadata work: it stats files and directories; it does not open databases or touch secrets. The one exception is Safari, which lists its named profiles only inside `SafariTabs.db`: its Discover captures that single file into a temporary snapshot and reads the copy, never the live database ([RFC-005](005-browser-definitions.md)). A user data dir that exists but cannot be read is not dropped: it comes back as an `error` result for that browser ([RFC-005](005-browser-definitions.md)). -**In:** `app.Request` + `browser.Supported()`, this OS's rows. **Out:** an `app.Discovery` — the user data dirs found, plus the failures. **Owner:** `app.Discover`, which dispatches on `Def.Base` to `internal/browser/{chromium,firefox,safari}`. +**In:** `app.Options` + `browser.Supported()`, this OS's rows. **Out:** an `app.Discovery` — the user data dirs found, plus the failures. **Owner:** `app.Discover`, which dispatches on `Browser.Base` to `internal/browser/{chromium,firefox,safari}`. ### 3. Plan The cross product. For each user data dir, each profile, and each requested category, the profile's `Extractors` say whether the category is supported and which source files it needs. Plan turns that into a flat list of `Extraction`s, a `Skipped` list with a reason for every requested pair that can't run (`unsupported` by this browser, `absent` on disk, `error` when a file cannot be checked) plus Discover's failures, and the union of files to capture, deduplicated by user data dir and path — so a file two categories share (Chromium `History` feeds both history and downloads) is copied once (v1.1.0 copied it twice). Plan only stats files; it opens nothing. A `Plan` is plain data, with no functions inside, so `list` prints it and tests compare it. -**In:** an `app.Discovery` + `app.Request`. **Out:** `app.Plan{Dirs, Files, Extractions, Skipped}`. **Owner:** `app.NewPlan`. +**In:** an `app.Discovery` + `app.Options`. **Out:** `app.Plan{Dirs, Files, Extractions, Skipped}`. **Owner:** `app.NewPlan`. ### 4–6. Capture, Extract, Export — once per user data dir @@ -80,7 +80,7 @@ A record whose secret can't be recovered is still emitted with that field empty Appends each extraction's records, as it finishes, to the frozen output files and formats ([RFC-008](008-output-and-export.md)): one file per non-empty category, field names frozen, rows in a deterministic order defined once per category. -**In:** records + `app.Request`. **Out:** files on disk (and the `--zip` archive). **Owner:** `internal/export`. +**In:** records + `app.Options`. **Out:** files on disk (and the `--zip` archive). **Owner:** `internal/export`. ### 7. Report diff --git a/rfcs/002-package-layout.md b/rfcs/002-package-layout.md index 631ebba..5b815ea 100644 --- a/rfcs/002-package-layout.md +++ b/rfcs/002-package-layout.md @@ -5,16 +5,16 @@ Everything except the command entrypoint lives under `internal/`. The entrypoint stays thin — the frozen cobra command tree and a call into `app`. ``` -cmd/hack-browser-data/ main; cobra commands and flags (the frozen CLI surface); flags → app.Request +cmd/hack-browser-data/ main; cobra commands and flags (the frozen CLI surface); flags → app.Options internal/ app/ Validate, Discover, NewPlan, Execute, Report; dispatches on browser.Base to the base packages - browser/ Def, Base, Platform (Supported, Lookup); UserDataDir, DirID, Profile, DiscoverOptions; - Source, Extractor, ProfileSnapshot, Collector - chromium/ Chromium discovery, extractors, key input, archive sources, per-fork overrides (Yandex, Opera family) + browser/ Browser, Base, Platform (Supported, Lookup); UserDataDir, UserDataDirID, Profile, DiscoverOptions; + FileSpec, Extractor, ProfileSnapshot, Collector + chromium/ Chromium discovery, extractors, key input, archive files, per-fork overrides (Yandex, Opera family) firefox/ Firefox discovery, extractors, per-profile key derivation safari/ Safari discovery and extractors category/ Category: the data categories (the -c values and the output file names) - record/ record types (Login, Cookie, …), the sealed Record, Stamp; field names frozen by the output contract + record/ record types (Login, Cookie, …) and the Record interface; field names frozen by the output contract masterkey/ Chromium key Set, Retriever, RetrieveAll, keys.json Dump; OS secret stores by build tag crypto/ pure decrypt primitives over bytes (AES-CBC/GCM, 3DES, PBKDF2, ASN.1 PBE) snapshot/ snapshot Dir and Snapshot, Capture, manifest, zip transport, the copier @@ -37,7 +37,7 @@ Dependencies point downward and are listed exhaustively; anything not listed is | Package | May import (project-internal) | | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -| `cmd/hack-browser-data` | `app`, plus `browser` and `category` for help-text vocabulary (`-b` IDs, `-c` categories), `log` | +| `cmd/hack-browser-data` | `app`, plus `browser` and `category` for help-text vocabulary (`-b` names, `-c` categories), `log` | | `app` | every package below | | `browser/chromium`, `browser/firefox`, `browser/safari` | `browser`, `category`, `record`, `masterkey`, `crypto`, `snapshot`, `sqlitex`, `timeconv`, `log` | | `export` | `category`, `record` | @@ -53,8 +53,8 @@ Dependencies point downward and are listed exhaustively; anything not listed is Four rules keep the graph acyclic and its seams honest: -- **The base dispatch lives in `app`.** The base packages import `browser` for `Def`, `UserDataDir`, and `Extractor`, so `browser` cannot call them back; `app` switches on `Def.Base`. Init-time self-registration is ruled out by the `gochecknoinits` linter, and an explicit switch reads better on stage anyway. -- **`snapshot` speaks strings.** A `snapshot.File` names its user data dir by ID (`DirID`, a plain string) and its path relative to that directory; it never holds a `browser.UserDataDir`, because `browser.ProfileSnapshot` holds a `snapshot.Snapshot`. +- **The base dispatch lives in `app`.** The base packages import `browser` for `Browser`, `UserDataDir`, and `Extractor`, so `browser` cannot call them back; `app` switches on `Browser.Base`. Init-time self-registration is ruled out by the `gochecknoinits` linter, and an explicit switch reads better on stage anyway. +- **`snapshot` speaks strings.** A `snapshot.File` names its user data dir by ID (`UserDataDirID`, a plain string) and its path relative to that directory; it never holds a `browser.UserDataDir`, because `browser.ProfileSnapshot` holds a `snapshot.Snapshot`. - **`crypto` takes bytes.** Primitives receive raw keys and blobs; they never see a `masterkey.Set`, because `masterkey` is the package that calls them. - **Interfaces live with their consumer.** `browser` declares the `Collector` its extractors use, and `app` implements it; `masterkey` and `browser/safari` each declare the one-method `LoginKeychain` they read. Constructors elsewhere return concrete types (`*snapshot.Dir`, `*export.Writer`). diff --git a/rfcs/003-core-types.md b/rfcs/003-core-types.md index 3f7e047..7637c09 100644 --- a/rfcs/003-core-types.md +++ b/rfcs/003-core-types.md @@ -16,16 +16,16 @@ type DiscoverOptions struct { ProfilePath string // the -p value, already validated; "" when not given (RFC-009) } -// DirID names one user data dir: Def.ID for the first one of a Def, then "-2", "-3"… appended for further -// ones, in Path order. It is its own type so that it cannot be passed where a Def.ID belongs. -type DirID string +// UserDataDirID names one user data dir: Browser.Name for the first one of a Browser, then "-2", "-3"… appended +// for further ones, in Path order. It is its own type so that it cannot be passed where a Browser.Name belongs. +type UserDataDirID string // UserDataDir is one browser data directory found on this machine: Chromium's "User Data", // Firefox's Profiles directory, Safari's data under ~/Library. type UserDataDir struct { - ID DirID // "chrome", "arc", "arc-2" — also the snapshot and archive directory name - Def Def // which browser it belongs to (RFC-005) - Path string // absolute path; every Source path resolves under it + ID UserDataDirID // "chrome", "arc", "arc-2" — also the snapshot and archive directory name + Browser Browser // which browser it belongs to (RFC-005) + Path string // absolute path; every FileSpec path resolves under it Profiles []Profile } @@ -36,9 +36,9 @@ type Profile struct { } ``` -`UserDataDir` is Chromium's own term (`--user-data-dir`): the directory holding `Local State` and the profile directories, as opposed to the program installation that holds the executable. HBD uses it for every base's data root — the directory a base's sources resolve under — even where the browser has no such word: Firefox's `Profiles` directory, and Safari's `~/Library` (below). A machine can have several for one browser — Arc's two MSIX packages on Windows each have one — and `restore` works on a copied one that was never installed here, which is why the type is not called `Installation` ([RFC-004](004-naming-decisions.md)). +`UserDataDir` is Chromium's own term (`--user-data-dir`): the directory holding `Local State` and the profile directories, as opposed to the program installation that holds the executable. HBD uses it for every base's data root — the directory a base's file specs resolve under — even where the browser has no such word: Firefox's `Profiles` directory, and Safari's `~/Library` (below). A machine can have several for one browser — Arc's two MSIX packages on Windows each have one — and `restore` works on a copied one that was never installed here, which is why the type is not called `Installation` ([RFC-004](004-naming-decisions.md)). -Two IDs sit side by side and must not be confused: `dir.ID` (`arc-2`) names the directory, `dir.Def.ID` (`arc`) names the browser. The `-b` value, a `keys.json` vault's `browser` key, and the per-fork overrides use `Def.ID`; the snapshot and archive layout use the `DirID`. On a machine with one Arc the two are equal, so a mix-up would pass every test there — the separate type makes it a compile error instead. +An ID and a name sit side by side and must not be confused: `dir.ID` (`arc-2`) names the directory, `dir.Browser.Name` (`arc`) names the browser. The `-b` value, a `keys.json` vault's `browser` key, and the per-fork overrides use `Browser.Name`; the snapshot and archive layout use the `UserDataDirID`. On a machine with one Arc the two are equal, so a mix-up would pass every test there — the separate type makes it a compile error instead. `Profile.Name` is frozen by the output contract ([RFC-000](000-goals-and-constraints.md)): for Chromium the directory's base name (`Default`, `Profile 1` — what Chromium's `Profile::GetBaseName()` returns, not the display name `Local State` keeps in `profile.info_cache`); for Firefox the directory name (`97nszz88.default-release`); for Safari, `default` or the named profile's title (deduplicated with a `-N` suffix, the UUID when untitled). It is never a path. @@ -47,30 +47,30 @@ Safari has no single data directory — History lives under `~/Library/Safari`, ## Extractor contract — `internal/browser` ```go -// Source is one file or directory an extractor needs. -type Source struct { +// FileSpec is one file or directory an extractor needs: where to look for it, not the file itself. +type FileSpec struct { Paths []string // candidates in priority order, relative to the profile dir — or to the user data dir when Shared IsDir bool // a directory (LevelDB, Session Storage), copied whole Shared bool // belongs to the whole user data dir, not one profile: Local State Optional bool // the extraction still runs without it } -// Candidates are the Paths for profile p, relative to the user data dir, in priority order. -func (s Source) Candidates(p Profile) []string +// CandidatePaths are the Paths for a profile, relative to the user data dir, in priority order. +func (s FileSpec) CandidatePaths(profile Profile) []string -// Extractor declares the sources a category needs and how to parse them. +// Extractor declares the file specs a category needs and how to parse them. type Extractor struct { - Sources []Source - Extract func(ctx context.Context, ps ProfileSnapshot, out Collector) error + FileSpecs []FileSpec + Extract func(ctx context.Context, profileSnapshot ProfileSnapshot, out Collector) error } // Extractors maps each category a profile supports to its extractor. type Extractors map[category.Category]Extractor ``` -Sources are static data: a base package declares them once per category and never rewrites them per profile. `Source.Candidates` joins a profile-scoped path with the profile's `Dir` and leaves a `Shared` one as it is, for Plan and `ProfileSnapshot.Path` alike; Plan captures the union once per user data dir — so `Local State`, or the Chromium `History` file that feeds both history and downloads, is copied once however many extractions need it. Safari is the exception: a named profile's files sit under two directories named for its UUID, so `safari.Extractors` builds each profile's sources from its `Dir`, and reaches files elsewhere under `~/Library` with `..` from there. +File specs are static data: a base package declares them once per category and never rewrites them per profile. `FileSpec.CandidatePaths` joins a profile-scoped path with the profile's `Dir` and leaves a `Shared` one as it is, for Plan and `ProfileSnapshot.Path` alike; Plan captures the union once per user data dir — so `Local State`, or the Chromium `History` file that feeds both history and downloads, is copied once however many extractions need it. Safari is the exception: a named profile's files sit under two directories named for its UUID, so `safari.Extractors` builds each profile's file specs from its `Dir`, and reaches files elsewhere under `~/Library` with `..` from there. -An extraction is `absent` when a required source has no candidate on disk, or when all its sources are optional and none of the profile's own is there: a shared source such as `Local State` never makes an extraction present by itself. A candidate that cannot be checked — permission denied — makes the extraction an `error` instead, and its profile stays through discovery so the error is reported. An extractor that reads no file — Safari's passwords, which come from the login keychain — always runs. Chromium passwords are two optional sources — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces v1.1.0's output, including a profile that only ever synced passwords, without a special case. +An extraction is `absent` when a required file spec has no candidate on disk, or when all its file specs are optional and none of the profile's own is there: a shared one such as `Local State` never makes an extraction present by itself. A candidate that cannot be checked — permission denied — makes the extraction an `error` instead, and its profile stays through discovery so the error is reported. An extractor that reads no file — Safari's passwords, which come from the login keychain — always runs. Chromium passwords are two optional file specs — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces v1.1.0's output, including a profile that only ever synced passwords, without a special case. `Extractor` / `Extractors` are **DECIDED**. @@ -80,31 +80,31 @@ An extraction is `absent` when a required source has no candidate on disk, or wh // ProfileSnapshot is what an extractor is handed for one extraction: its profile's view of the user data dir's // snapshot, and the dir's keys. type ProfileSnapshot struct { - Profile Profile // the extraction's profile; profile-scoped sources resolve under its Dir - snap snapshot.Snapshot + Profile Profile // the extraction's profile; profile-scoped file specs resolve under its Dir + snapshot snapshot.Snapshot masterKeys func(ctx context.Context) masterkey.Set } // NewProfileSnapshot is how app hands a profile its share; tests pass a fixture Snapshot and a fake masterKeys. -func NewProfileSnapshot(snap snapshot.Snapshot, p Profile, masterKeys func(context.Context) masterkey.Set) ProfileSnapshot +func NewProfileSnapshot(dirSnapshot snapshot.Snapshot, profile Profile, masterKeys func(context.Context) masterkey.Set) ProfileSnapshot -// Path returns the captured path of src: its first candidate present in the snapshot. A candidate that was +// Path returns the captured path of fileSpec: its first candidate present in the snapshot. A candidate that was // never captured is skipped; one whose copy failed returns that copy's error. -func (ps ProfileSnapshot) Path(src Source) (string, error) +func (ps ProfileSnapshot) Path(fileSpec FileSpec) (string, error) // MasterKeys returns the user data dir's Chromium keys, one per version. The first call in a dir retrieves them and // later calls reuse the result; a version that could not be retrieved is absent from the Set. func (ps ProfileSnapshot) MasterKeys(ctx context.Context) masterkey.Set -// Collector receives one extraction's output. It stamps Browser and Profile on every record, so no extractor can omit +// Collector receives one extraction's output. It sets Browser and Profile on every record, so no extractor can omit // them. type Collector interface { - Add(r record.Record) // one parsed record - Fail(err error) // one record-level problem: a secret that could not be recovered, or a row dropped as unparseable + Add(row record.Record) // one parsed record + Fail(err error) // one record-level problem: a secret that could not be recovered, or a row dropped as unparseable } ``` -An extractor reads from its `Source`s and hands its records to the `Collector`. It emits records as it reads them; it does not accumulate slices. A record whose secret can't be recovered is emitted anyway with that field empty, as in v1.1.0, and reported through `Fail`, which records the problem and lets the extraction continue, like `testing.T.Error`; the extraction ends `partial`. An extractor never logs errors: it returns extraction-level errors and reports record-level ones. Base-specific context an extractor needs (Safari's profile UUID for filtering downloads and the run's login keychain, the Yandex override) is captured when the base package builds the profile's `Extractors`, not passed through the `ProfileSnapshot`. +An extractor reads from its `FileSpecs` and hands its records to the `Collector`. It emits records as it reads them; it does not accumulate slices. A record whose secret can't be recovered is emitted anyway with that field empty, as in v1.1.0, and reported through `Fail`, which records the problem and lets the extraction continue, like `testing.T.Error`; the extraction ends `partial`. An extractor never logs errors: it returns extraction-level errors and reports record-level ones. Base-specific context an extractor needs (Safari's profile UUID for filtering downloads and the run's login keychain, the Yandex override) is captured when the base package builds the profile's `Extractors`, not passed through the `ProfileSnapshot`. `MasterKeys` takes a context because its first call may block — on a secret-store lookup, or on macOS on the login keychain's no-echo password prompt — and Ctrl-C cancels the run's context ([RFC-009](009-cli-surface.md)). It returns no error: the dir's call-once in `app` keeps the retrieval error and reports it once, as the user data dir's `error` result ([RFC-001](001-architecture-and-pipeline.md)), and a record whose key is missing is emitted with that field empty and reported through `Fail`. Every `ProfileSnapshot` of one user data dir shares that call-once; `masterKeys` is nil for Firefox and Safari, whose extractors never call it. @@ -116,9 +116,9 @@ There is no separate `Secrets` handle ([RFC-004](004-naming-decisions.md)), and // Extraction is one unit of work: one category of data from one profile of one user data dir. It is pure data — // the extractor is looked up when it runs — so a Plan prints as it is and compares with reflect.DeepEqual in tests. type Extraction struct { - DirID browser.DirID // which user data dir - Profile string // Profile.Name; "" in a result about a whole browser or user data dir - Category category.Category // zero in a result about a whole browser or user data dir + UserDataDirID browser.UserDataDirID // which user data dir + Profile string // Profile.Name; "" in a result about a whole browser or user data dir + Category category.Category // zero in a result about a whole browser or user data dir } // Discovery is what Discover found: the user data dirs, plus an error result for each browser whose data could @@ -135,8 +135,8 @@ type Plan struct { Skipped []Result // requested but can't run: unsupported, absent, unreadable, or Discovery.Failed } -func Discover(req Request) Discovery -func NewPlan(d Discovery, req Request) Plan +func Discover(options Options) Discovery +func NewPlan(discovery Discovery, options Options) Plan ``` `Plan` is a plain value: printable, testable, and all `list` prints. `restore` builds its `Discovery` from the snapshot directory it opens instead of from the machine ([RFC-007](007-snapshot-and-acquisition.md)). @@ -169,14 +169,14 @@ type Summary struct { // Execute runs Capture, Extract, and Export one user data dir at a time (RFC-001). Its error means the run could // not finish — an output write failure; every other failure is a Result. -func Execute(ctx context.Context, p Plan, req Request) (Summary, error) +func Execute(ctx context.Context, plan Plan, options Options) (Summary, error) ``` -The outcome follows from the counts: `OutcomeOK` when nothing failed — zero records included, since an empty source is not absent; `OutcomePartial` when records were emitted and some failed; `OutcomeError` when the extractor returned an error, a source failed to copy, or failures were reported with no record emitted. `Summary` starts with `Plan.Skipped`, so the report covers what never ran as well as what did. +The outcome follows from the counts: `OutcomeOK` when nothing failed — zero records included, since an empty file is not absent; `OutcomePartial` when records were emitted and some failed; `OutcomeError` when the extractor returned an error, a file failed to copy, or failures were reported with no record emitted. `Summary` starts with `Plan.Skipped`, so the report covers what never ran as well as what did. The exit status is not derived from `Summary`: it is `0` whenever the run completes and `1` when it cannot start or finish ([RFC-001](001-architecture-and-pipeline.md)). `Summary` feeds the report only. -The stage functions are `Validate`, `Discover`, `NewPlan`, `Execute`, and `Report`; the values they produce are `Request`, `Discovery`, `Plan`, and `Summary`. No function shares a name with a type, which Go would reject. +The stage functions are `Validate`, `Discover`, `NewPlan`, `Execute`, and `Report`; the values they produce are `Options`, `Discovery`, `Plan`, and `Summary`. No function shares a name with a type, which Go would reject. ## Categories — `internal/category` @@ -234,16 +234,12 @@ const ( StoreAccount Store = "account" // Login Data For Account ) -// Record is a record of any category: one row of output. It is sealed: only this package's record types implement it. +// Record is a record of any category: one row of output. The pipeline's Collector calls SetBrowserAndProfile on each +// record it is handed, so the two fields every record starts with are never left to an extractor. type Record interface { Category() category.Category - stamp(browser, profile string) + SetBrowserAndProfile(browser, profile string) } - -// Stamp sets the two source fields every record starts with. The pipeline's Collector calls it on each record it is -// handed; it is exported because the sealing method stamp is not, and an unexported method can only be called from -// its own package. -func Stamp(r Record, browser, profile string) ``` | Category | Record type | v1.1.0 type | @@ -258,7 +254,7 @@ func Stamp(r Record, browser, profile string) | `category.LocalStorage` | `record.LocalStorage` | `types.StorageEntry` | | `category.SessionStorage` | `record.SessionStorage` | `types.StorageEntry` | -Every record type starts with two flat source fields, `Browser string` (the display name) and `Profile string` (`Profile.Name`), followed by v1.1.0's fields with v1.1.0's names, tags, and order. `LocalStorage` and `SessionStorage` declare the same fields separately, so each is its own type with its own category. Records are used by pointer — `out.Add(&record.Cookie{…})` — because `stamp` sets the fields in place. There is no `Origin`/`Owner` umbrella type ([RFC-004](004-naming-decisions.md)). +Every record type starts with two flat source fields, `Browser string` (the display name) and `Profile string` (`Profile.Name`), followed by v1.1.0's fields with v1.1.0's names, tags, and order. `LocalStorage` and `SessionStorage` declare the same fields separately, so each is its own type with its own category. Records are used by pointer — `out.Add(&record.Cookie{…})` — because `SetBrowserAndProfile` sets the fields in place. There is no `Origin`/`Owner` umbrella type ([RFC-004](004-naming-decisions.md)). Only the type names changed from v1.1.0. Field names are wire names — each field's snake_case form, enforced by lint — and because the output is frozen, so are they ([RFC-008](008-output-and-export.md)). `Store` is a named string type with v1.1.0's two values, which changes nothing on the wire. @@ -320,10 +316,10 @@ The login keychain belongs to the user, not to a profile or a user data dir, so ```go // File is one file or directory a plan wants captured. type File struct { - DirID string // the user data dir's ID ("chrome", "arc-2"); also the snapshot it lands in - From string // absolute path of the user data dir it is copied from - Rel string // slash-separated path relative to From, and to the snapshot - IsDir bool + UserDataDirID string // the user data dir's ID ("chrome", "arc-2"); also the snapshot it lands in + UserDataDirPath string // absolute path of the user data dir it is copied from + RelativePath string // slash-separated path relative to UserDataDirPath, and to the snapshot + IsDir bool } // Dir is a snapshot directory: one Snapshot per user data dir. @@ -331,11 +327,11 @@ type Dir struct{ /* unexported */ } func Temp() (*Dir, error) // a new temporary snapshot directory, mode 0700 func Open(path string) (*Dir, error) // an existing one, used in place (restore --data-dir) -func Unzip(src string) (*Dir, error) // restore transport into a temporary snapshot directory; rejects entries that escape it +func Unzip(archivePath string) (*Dir, error) // restore transport into a temporary snapshot directory; rejects entries that escape it func (d *Dir) Capture(ctx context.Context, files []File) error // copies what it can; per-file failures surface through Snapshot.Path -func (d *Dir) Snapshot(dirID string) Snapshot -func (d *Dir) Zip(dst string) error // archive: temp file beside dst, renamed into place on success +func (d *Dir) Snapshot(userDataDirID string) Snapshot +func (d *Dir) Zip(archivePath string) error // archive: temp file beside it, renamed into place on success func (d *Dir) Close() error // removes a temporary snapshot directory; leaves an opened one in place // Snapshot is one user data dir's snapshot: the read-only view of the files captured from it. @@ -346,7 +342,7 @@ type Snapshot struct{ /* unexported */ } func (s Snapshot) Path(rel string) (string, error) ``` -`Capture` returns an error only when it cannot go on — a cancelled context, an unwritable snapshot directory. A single file's failure is kept and handed back by `Snapshot.Path`, so it ends that file's extractions as `error` without stopping the rest. `snapshot` cannot import `browser` (`browser.ProfileSnapshot` holds a `snapshot.Snapshot`), so a `File` names its user data dir with a plain string, `DirID`. `Snapshot` hands out real paths because `modernc.org/sqlite` and `goleveldb` open files by path, and SQLite needs its `-wal` file beside the database. The snapshot is therefore always a directory; zip is only a transport format ([RFC-007](007-snapshot-and-acquisition.md)). +`Capture` returns an error only when it cannot go on — a cancelled context, an unwritable snapshot directory. A single file's failure is kept and handed back by `Snapshot.Path`, so it ends that file's extractions as `error` without stopping the rest. `snapshot` cannot import `browser` (`browser.ProfileSnapshot` holds a `snapshot.Snapshot`), so a `File` names its user data dir with a plain string, `UserDataDirID`. `Snapshot` hands out real paths because `modernc.org/sqlite` and `goleveldb` open files by path, and SQLite needs its `-wal` file beside the database. The snapshot is therefore always a directory; zip is only a transport format ([RFC-007](007-snapshot-and-acquisition.md)). ## Export — `internal/export` diff --git a/rfcs/004-naming-decisions.md b/rfcs/004-naming-decisions.md index 3021754..98937c1 100644 --- a/rfcs/004-naming-decisions.md +++ b/rfcs/004-naming-decisions.md @@ -7,8 +7,9 @@ Go naming principles applied throughout: - **The package name is part of the identifier.** `category.Cookie` already says "the cookie category," so a `Category` prefix or a `record.Record`-style stutter is redundant. Names are judged at the call site, not in isolation. - **A qualified name reads as what it is.** `category.Cookie` is a category and `record.Cookie` is a cookie record; neither needs a suffix to tell it from the other, because each lives in the package that means it. - **A name says what a thing is, not how it is built or used, or what it resembles.** `ProfileSnapshot`, not `Input`; `Snapshot`, not `Tree`. -- **One concept, one name.** A user data dir's location is a `Path`, its identity a `DirID`, a ciphertext's prefix a `Version` — in code and in prose alike. +- **One concept, one name.** A user data dir's location is a `Path`, its identity a `UserDataDirID`, a ciphertext's prefix a `Version` — in code and in prose alike. - **Values are nouns, stages are verbs.** A Go package cannot hold a type and a function of the same name, so the pipeline's values (`Plan`, `Summary`) and the stages that produce them (`NewPlan`, `Execute`) never share a word. +- **Names are spelled out.** A variable is named for what it holds — `extractors`, `snapshotDir`, `profile` — never `ex`, `d`, or `p` (item 10). Internal Go names are free to change; anything the user can see — commands, flags, file names, field names, `keys.json` keys — is frozen by the compatibility contract ([RFC-000](000-goals-and-constraints.md)), whatever the Go name behind it. @@ -17,7 +18,7 @@ Internal Go names are free to change; anything the user can see — commands, fl | Name | Decision | | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `internal/` for all non-`cmd` code | [RFC-002](002-package-layout.md). | -| `browser.Extractor` / `browser.Extractors` | The thing that declares sources and parses them. | +| `browser.Extractor` / `browser.Extractors` | The thing that declares its files and parses them. | | `masterkey.Set` / `masterkey.RetrieveAll` | The key collection and the function that fills it. | | Wire names = snake_case of Go field names | No second vocabulary; lint-enforced; frozen with the output. [RFC-008](008-output-and-export.md). | | `browser` stays `browser` (not `engine`) | "Engine" means a web rendering engine (Blink/Gecko/WebKit) and misleads. | @@ -28,9 +29,13 @@ Internal Go names are free to change; anything the user can see — commands, fl | `keychain.Keychain` | The run's macOS login keychain: one handle, opened on first use; consumers get the handle, never the password. | | `browser.Collector` (`Add`, `Fail`) | What an extractor hands its records and record-level problems to; not `Sink`, not `Emit`. | | `masterkey.Locator` / `chromium.KeyLocator` | Where one user data dir's keys are found, and the function that builds it; not `RetrieveInput`. | -| `Base` enum; product identity in `Def.ID` | No `Variant` enum; channel is folded into rows, not modelled. | -| `browser.UserDataDir` with a `DirID` | Not `Installation`; the ID has its own type. | -| `app` stages and values | `Validate`, `Discover`, `NewPlan`, `Execute`, `Report`; `Request`, `Discovery`, `Plan`, `Extraction`, `Summary`. | +| `Base` enum; product identity in `Browser.Name` | No `Variant` enum; channel is folded into rows, not modelled. | +| `browser.UserDataDir` with a `UserDataDirID` | Not `Installation`; the ID has its own type, named for the directory it identifies. | +| `app` stages and values | `Validate`, `Discover`, `NewPlan`, `Execute`, `Report`; `Options`, `Discovery`, `Plan`, `Extraction`, `Summary`. | +| `browser.Browser` with `Name` and `DisplayName` | A row of the browser table, named for its package as `category.Category` is; not `Def`, and not `ID` for the `-b` value. | +| `browser.FileSpec` | Where an extractor looks for one file; it becomes a `snapshot.File` once found. Not `Source`. | +| `Record.SetBrowserAndProfile` | An exported method on every record; no sealed `stamp` method and no `record.Stamp` wrapper. | +| Spelled-out names | Only Go's fixed idioms stay short; a name that would shadow its package takes its role (item 10). | | `snapshot.Dir` / `snapshot.Snapshot` | A snapshot directory and one user data dir's snapshot inside it, a snapshot being one user data dir's copy as in Chromium; not `FS`, `Tree`, or `Copy`. | | `winapi`, `abe`; `log` and `crypto` kept | Windows-only packages; not `platform/windows`. | | `timeconv` and `sqlitex` functions | `timeconv.Chromium`, `UnixMicro`, `UnixMilli`, `Unix`, `CoreData`, each named for the encoding it reads; `sqlitex` exports `CountRows` and `QueryRows` only. | @@ -43,11 +48,13 @@ Internal Go names are free to change; anything the user can see — commands, fl **Decision.** The table lives in `browser`, where it belongs; there is no `catalog` package. ```go -browser.Supported() []browser.Def // the browsers HBD supports on the running OS, in table order -browser.Lookup(id string) (Def, bool) // any row of the whole table, whatever the OS +browser.Supported() []browser.Browser // the browsers HBD supports on the running OS, in table order +browser.Lookup(name string) (Browser, bool) // any row of the whole table, whatever the OS ``` -`Supported()` is exactly what its callers need: Discover walks it, `-b` is validated against it, and the help text lists it. It reads as "the browsers that are supported," and on macOS that list must not contain `qq` or `sogou`, which have no macOS row. `restore` needs the other view — a vault taken on Windows can name a Windows-only fork — so it resolves IDs with `Lookup`, which searches the whole table. No caller needs the whole table as a list; tests that do read the package's unexported table. +`Supported()` is exactly what its callers need: Discover walks it, `-b` is validated against it, and the help text lists it. It reads as "the browsers that are supported," and on macOS that list must not contain `qq` or `sogou`, which have no macOS row. `restore` needs the other view — a vault taken on Windows can name a Windows-only fork — so it resolves names with `Lookup`, which searches the whole table. No caller needs the whole table as a list; tests that do read the package's unexported table. + +**`Browser`, not `Def`.** A row of the table is a browser, so the type is `browser.Browser`, named for its package as `category.Category` and `snapshot.Snapshot` are. `Def` was an abbreviation a reader had to decode, and `Definition` would still name the table entry rather than the thing it describes. Outside the package a variable holding one cannot be called `browser`, which would shadow the package, so it is named for its role: `supportedBrowser`, `chromiumBrowser`, `restoredBrowser`. **Alternatives rejected.** @@ -61,13 +68,13 @@ browser.Lookup(id string) (Def, bool) // any row of the whole table, whatever t ### 2. Per-record source — flat `Browser` + `Profile`, no umbrella type -**Decision.** Each record carries two flat fields — `Browser string` and `Profile string` — not a wrapper type. `Browser` holds `Def.Name`, the display name (`Chrome`, `Microsoft Edge`), and `Profile` holds `Profile.Name` (`Default`, or a Safari profile's title) — exactly the values v1.1.0's `browser` and `profile` columns carry. Putting `Def.ID` (`chrome`) in `Browser` would change every row, which the compatibility contract rules out. +**Decision.** Each record carries two flat fields — `Browser string` and `Profile string` — not a wrapper type. `Browser` holds `Browser.DisplayName` (`Chrome`, `Microsoft Edge`), and `Profile` holds `Profile.Name` (`Default`, or a Safari profile's title) — exactly the values v1.1.0's `browser` and `profile` columns carry. Putting `Browser.Name` (`chrome`) there would change every row, which the compatibility contract rules out. -**Why no umbrella type.** `Owner` is wrong (it implies possession/ACLs). `Origin` is worse in this domain: "origin" is already the Web-platform term (`scheme://host:port`), so `cookie.Origin` reads as "the site this cookie belongs to," not "where I pulled it from" — the same collision that got `engine` rejected. `Provenance` is the DFIR term but reads heavy. The browser domain has no clean single noun for "(browser, profile) a datum came from", so the record stamps a `browser` and a `profile` column, as v1.1.0's output already did. +**Why no umbrella type.** `Owner` is wrong (it implies possession/ACLs). `Origin` is worse in this domain: "origin" is already the Web-platform term (`scheme://host:port`), so `cookie.Origin` reads as "the site this cookie belongs to," not "where I pulled it from" — the same collision that got `engine` rejected. `Provenance` is the DFIR term but reads heavy. The browser domain has no clean single noun for "(browser, profile) a datum came from", so the record carries a `browser` and a `profile` column, as v1.1.0's output already did. **`Profile` holds the name, never a path.** This keeps local absolute paths out of exported data and keeps archives portable across hosts. It does not collide with the `browser.Profile` type or with `Profile.Dir` (the path) — a field named `Profile` of type `string` lives in a different namespace from the type. -**Stamping.** The fields are exported so `encoding/json` serializes them, but extractors don't set them: the pipeline's `Collector` calls `record.Stamp` on every record it is handed. `Stamp` is exported because `Record`'s sealing method `stamp` is not, and Go only lets the declaring package call an unexported method. +**Setting them.** The fields are exported so `encoding/json` serializes them, but extractors don't set them: the pipeline's `Collector` calls `SetBrowserAndProfile` on every record it is handed. The method is exported, so `Record` is not sealed: the packages are internal and have no library API, so an unexported sealing method protected nothing, and it needed an exported `Stamp` wrapper just to be callable. On the wire: `browser` and `profile` keys in JSON; leading `browser` / `profile` columns in CSV. @@ -77,14 +84,14 @@ On the wire: `browser` and `profile` keys in JSON; leading `browser` / `profile` | ----------------- | ---------------------------------------------------------------- | | `Origin` type | collides with Web-platform "origin" in a browser-data tool. | | `Provenance` type | accurate (DFIR) but heavy, and still an invented umbrella. | -| `Source` type | `browser.Source` is the extractor's file set; two "Source"s mix. | +| `Source` type | says nothing about what it holds, the fault that also renamed the extractor's files to `FileSpec`. | ### 3. The extractor's input — `browser.ProfileSnapshot` **Decision.** An extractor is handed a `browser.ProfileSnapshot`: its profile's view of the user data dir's snapshot, plus the dir's Chromium keys. It is a concrete type with two methods, built by `app` through `NewProfileSnapshot`: ```go -func (ps ProfileSnapshot) Path(src Source) (string, error) // where src was captured in the snapshot +func (ps ProfileSnapshot) Path(fileSpec FileSpec) (string, error) // where fileSpec was captured in the snapshot func (ps ProfileSnapshot) MasterKeys(ctx context.Context) masterkey.Set // this user data dir's Chromium keys; the first call retrieves ``` @@ -103,15 +110,16 @@ func (ps ProfileSnapshot) MasterKeys(ctx context.Context) masterkey.Set // this | `masterkey.Lazy` | names a strategy, not what the extractor holds. | | `masterkey.Keys{Set()}` | `in.Keys.Set()` reads as a setter in Go (`flag.Value.Set`, `http.Header.Set`), and `masterkey.Keys` stutters. | -### 4. Browser classification — `Base`, with product identity in `ID` +### 4. Browser classification — `Base`, with product identity in `Name` Anchored in Chromium's own vocabulary (`install_modes.h` calls the product axis _brand_; the older `BrowserDistribution` called it _distribution_). **Decision.** - **`Base`** is the single classification enum: `Chromium`, `Firefox`, `Safari`. It is the "what is this built on" axis — "Chromium-based" — and it decides the storage/decryption model and which base package handles it. What these browsers share is the **Chromium platform/codebase**, not the rendering engine (Blink), which is exactly why `engine` would be both a collision and imprecise. -- **Product/brand identity lives in `Def.ID`** (a string, e.g. `"chrome"`, `"edge"`). There is **no `Variant` enum.** Modelling the product axis as an enum would force a code change for every new fork, which fights the "add a fork = add a data row" goal ([RFC-005](005-browser-definitions.md)); a string `ID` keeps forks as pure data. The few forks with their own on-disk format (Yandex, the Opera family) get an override inside the Chromium package keyed by `Def.ID` — still no enum, and a plain fork stays a pure row. -- **Channel** (stable/beta/dev/canary) is a separate axis in Chromium (install modes), but HBD gives it no field, because nothing dispatches on it: a channel that keeps its own user data dir is simply its own row, whose `ID` names product and channel together (`chrome-beta`). +- **Product/brand identity lives in `Browser.Name`** (a string, e.g. `"chrome"`, `"edge"`). There is **no `Variant` enum.** Modelling the product axis as an enum would force a code change for every new fork, which fights the "add a fork = add a data row" goal ([RFC-005](005-browser-definitions.md)); a string `ID` keeps forks as pure data. The few forks with their own on-disk format (Yandex, the Opera family) get an override inside the Chromium package keyed by `Browser.Name` — still no enum, and a plain fork stays a pure row. +- **Channel** (stable/beta/dev/canary) is a separate axis in Chromium (install modes), but HBD gives it no field, because nothing dispatches on it: a channel that keeps its own user data dir is simply its own row, whose `Name` names product and channel together (`chrome-beta`). +- **`Name` and `DisplayName`, not `ID` and `Name`.** The `-b` value (`chrome`) is the browser's name as the CLI and `keys.json` spell it, and `browser.Names()` lists them for `-b` as `category.Names()` does for `-c`; what records carry (`Microsoft Edge`) is the `DisplayName`. `ID` said nothing about what the string was, beside a `UserDataDir.ID` it often equals. **Alternatives rejected.** @@ -119,9 +127,9 @@ Anchored in Chromium's own vocabulary (`install_modes.h` calls the product axis | ------- | ------------------------ | --------------------------------------------------------------------------------- | | base | `Family` | common informal word, but not domain-native; `Base` reads "Chromium-based". | | base | `Engine` | rejected project-wide; also imprecise (renderer ≠ storage model). | -| base | `Platform` | means OS, not codebase — it is the per-OS half of a `Def` (item 6), not the base. | -| product | `Variant` / `Brand` enum | a per-fork enum fights "fork = data row"; identity belongs in `ID`. | -| channel | a `Channel` field | nothing reads it; the row and its `ID` already say it. | +| base | `Platform` | means OS, not codebase — it is the per-OS half of a `Browser` (item 6), not the base. | +| product | `Variant` / `Brand` enum | a per-fork enum fights "fork = data row"; identity belongs in `Name`. | +| channel | a `Channel` field | nothing reads it; the row and its `Name` already say it. | ### 5. Data categories and records — `category` and `record` @@ -158,7 +166,7 @@ A category says what kind of data is meant; a record is one row of that data. Th ### 6. The data-directory type — `browser.UserDataDir`, not `Installation` -**Decision.** The type for one browser data directory found on a machine is `browser.UserDataDir`, identified by a `browser.DirID`. +**Decision.** The type for one browser data directory found on a machine is `browser.UserDataDir`, identified by a `browser.UserDataDirID`. **Why not `Installation`.** In both Chromium and Firefox, an "installation" is the _program_ — the executable and its files. The thing this type holds is the _data_ directory: Chromium's `User Data` (the `--user-data-dir` the browser documents), Firefox's `Profiles` directory, Safari's data under `~/Library`. Three reasons `Installation` is wrong for it: @@ -166,21 +174,21 @@ A category says what kind of data is meant; a record is one row of that data. Th 2. A machine can have several data directories for one installed program (Arc's two MSIX packages), so "one installation" misdescribes the count. 3. In `restore` the directory was copied from another host and was never installed here at all. -`UserDataDir` is Chromium's own term, and it already appeared in v1.1.0's code (`BrowserConfig.UserDataDir`) and in the frozen `keys.json` field `user_data_dir` — so the type name aligns with a word the codebase and the output already use. Firefox and Safari have no such word; for them it means the directory their sources resolve under ([RFC-003](003-core-types.md)). +`UserDataDir` is Chromium's own term, and it already appeared in v1.1.0's code (`BrowserConfig.UserDataDir`) and in the frozen `keys.json` field `user_data_dir` — so the type name aligns with a word the codebase and the output already use. Firefox and Safari have no such word; for them it means the directory their files resolve under ([RFC-003](003-core-types.md)). -**Why `DirID` is its own type.** A user data dir's ID (`arc-2`) and its browser's `Def.ID` (`arc`) are equal for the first directory of every browser, so code that passes one where the other belongs passes every test on a machine with one Arc. As distinct types, the mix-up does not compile. +**Why `UserDataDirID` is its own type, spelled out.** A user data dir's ID (`arc-2`) and its browser's `Name` (`arc`) are equal for the first directory of every browser, so code that passes one where the other belongs passes every test on a machine with one Arc. As distinct types, the mix-up does not compile. The name says which directory it identifies: `DirID` could as well have meant a `Profile.Dir`, a `snapshot.Dir`, or the output directory. **Supporting names.** | Name | What it names | Why this name | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `UserDataDir.ID` (`DirID`) | `chrome`, `arc`, `arc-2` — one per data directory found | Distinguishes two user data dirs of one `Def`; also the snapshot and archive directory name. | -| `UserDataDir.Def` | the directory's `Def` | A field named for its type, the Go norm; `Browser` would clash with the record's `Browser string`. | +| `UserDataDir.ID` (`UserDataDirID`) | `chrome`, `arc`, `arc-2` — one per data directory found | Distinguishes two user data dirs of one `Browser`; also the snapshot and archive directory name. | +| `UserDataDir.Browser` | the directory's `Browser` | A field named for its type, the Go norm. The record's `Browser string` is another package's field and holds this one's `DisplayName`. | | `UserDataDir.Path` | its absolute path | The one word for a user data dir's location; `Root` was rejected as a second word for it. | | `Platform.UserDataDirs` | where one browser's user data dirs live on one OS | Each match becomes a `UserDataDir`; `Roots` would be another word for the same thing. | -| `Platform` fields | `UserDataDirs`, `KeychainLabel`, `Exe`, `ExeFallbacks`, `ABE` | The per-OS half of a `Def`; absorbs `winutil.Entry`. `Platform` means OS here (where `Base` means codebase), so the two never collide. | -| `browser.Source` / `browser.Collector` | the files an extractor reads / what it hands its records to | Says what it does with records, where `Sink` is dataflow jargon. `Add` is Go's verb for putting something into a container (`Emit` is event-framework vocabulary); `Collector.Fail` is what makes `partial` countable. | -| `Source.Shared` | a source of the whole user data dir (`Local State`) | Explicit data; the alternative made correctness depend on the order of builder calls ([RFC-005](005-browser-definitions.md)). | +| `Platform` fields | `UserDataDirs`, `KeychainLabel`, `Exe`, `ExeFallbacks`, `ABE` | The per-OS half of a `Browser`; absorbs `winutil.Entry`. `Platform` means OS here (where `Base` means codebase), so the two never collide. | +| `browser.FileSpec` / `browser.Collector` | where an extractor's file is looked for / what it hands its records to | `FileSpec` describes a file, candidate paths and flags, that becomes a `snapshot.File` once found, as `ast.TypeSpec` describes a type; `Source`, `DataFile`, `InputFile`, and `Artifact` named nothing specific, a role, or a build output. `Collector` says what it does with records, where `Sink` is dataflow jargon. `Add` is Go's verb for putting something into a container (`Emit` is event-framework vocabulary); `Collector.Fail` is what makes `partial` countable. | +| `FileSpec.Shared` | a file of the whole user data dir (`Local State`) | Explicit data; the alternative made correctness depend on the order of builder calls ([RFC-005](005-browser-definitions.md)). | | `browser.DiscoverOptions` | the home dir and `-p` handed to Discover | v1.1.0's name; kept. | | `masterkey.Version` | `v10`, `v11`, `v20` | Chromium's own word (`kEncryptionVersionPrefix`); a string type, so a `Set` marshals to the same `"v10"` keys as v1.1.0 with no extra code. "Tier" is not used. | | `masterkey.ABEKind` | `ABENone`, `ABEChromeBase`, `ABEEdge`, `ABEAvast` | v1.1.0's `winutil.ABEKind`, moved to the package that consumes it. | @@ -188,11 +196,13 @@ A category says what kind of data is meant; a record is one row of that data. Th ### 7. Pipeline and package names — `app`, `snapshot`, `winapi` -**`app`: nouns for values, verbs for stages.** `Validate` produces a `Request`, `Discover` a `Discovery`, `NewPlan` a `Plan`, `Execute` a `Summary`, and `Report` writes the summary out. `Run` is not used as a type name: in Go it reads as a verb (`cmd.Run`, `t.Run`). +**`app`: nouns for values, verbs for stages.** `Validate` produces `Options`, `Discover` a `Discovery`, `NewPlan` a `Plan`, `Execute` a `Summary`, and `Report` writes the summary out. `Run` is not used as a type name: in Go it reads as a verb (`cmd.Run`, `t.Run`). + +**`Options`, not `Request`.** `Validate` turns the raw `Flags` into typed values, so its result is the run's options, as `browser.DiscoverOptions` holds discovery's; in Go, `Request` reads as `http.Request`. **`Extraction`, not `Job`.** A plan's unit of work is one extraction: one category of data from one profile of one user data dir. `Job` beside `Result` is the vocabulary of Go's worker-pool idiom — `jobs` and `results` channels — so a reader looks for goroutines and a queue that do not exist. `Extraction` names what HBD does, extract browser data, and pairs with `Extract` and `Extractor` without suggesting concurrency. It sits one package away from `browser.Extractors`, a near-homonym, which the package names keep apart. -**`snapshot.Dir` and `snapshot.Snapshot`, not `snapshot.FS`, `snapshot.Tree`, or `snapshot.Copy`.** A Go reader takes `FS` for `io/fs.FS`; this type is not one, and it returns operating-system paths because SQLite and LevelDB open files by path. A `Snapshot` is one user data dir's snapshot, in Chromium's own sense of the word: its `downgrade::SnapshotManager` takes a snapshot by copying selected files of one user data dir. A `Dir` is the snapshot directory that holds one `Snapshot` per user data dir, and `Dir.Snapshot(dirID)` returns one — a method named for what it returns, as `http.Request.Cookie(name)` is. `ProfileSnapshot` is then one profile's share of a `Snapshot`, so the vocabulary closes. Both are concrete types, and the snapshot directory's lifecycle — created with mode `0700`, removed by `Close` — lives in `Dir`'s methods rather than in free functions over a named string. `Zip` and `Unzip` are the transport pair. +**`snapshot.Dir` and `snapshot.Snapshot`, not `snapshot.FS`, `snapshot.Tree`, or `snapshot.Copy`.** A Go reader takes `FS` for `io/fs.FS`; this type is not one, and it returns operating-system paths because SQLite and LevelDB open files by path. A `Snapshot` is one user data dir's snapshot, in Chromium's own sense of the word: its `downgrade::SnapshotManager` takes a snapshot by copying selected files of one user data dir. A `Dir` is the snapshot directory that holds one `Snapshot` per user data dir, and `Dir.Snapshot(userDataDirID)` returns one — a method named for what it returns, as `http.Request.Cookie(name)` is. `ProfileSnapshot` is then one profile's share of a `Snapshot`, so the vocabulary closes. Both are concrete types, and the snapshot directory's lifecycle — created with mode `0700`, removed by `Close` — lives in `Dir`'s methods rather than in free functions over a named string. `Zip` and `Unzip` are the transport pair. **`winapi` and `abe`, not `platform/windows`.** A package named `windows` would collide with `golang.org/x/sys/windows`, which it imports, so every file would need an alias. `winapi` is v1.1.0's name; the ABE bridge is its own unit, `abe`. @@ -204,6 +214,7 @@ A category says what kind of data is meant; a record is one row of that data. Th | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type Plan` + `func Plan`, `type Run` | a type and a function can't share a name; `Run` reads as a verb. | | `Job`, `Task` | Go's worker-pool vocabulary (`jobs` / `results` channels); readers look for a queue. | +| `Request` | reads as `http.Request`; the value is the validated flags. | | `Target` | reads as an attack target in a security tool. | | `Unit`, `Item`, `Entry` | `Unit` and `Item` say nothing; `…Entry` named v1.1.0's record types. | | `snapshot.FS` | reads as `io/fs.FS`. | @@ -236,24 +247,36 @@ A category says what kind of data is meant; a record is one row of that data. Th **`sqlitex` exports `CountRows` and `QueryRows` only.** The row-callback helper behind them, v1.1.0's `sqliteutil.QuerySQLite`, has no other caller, and as an export it would read `sqlitex.QuerySQLite`. +### 10. Spelled-out names + +**Decision.** A variable, parameter, or field is named for what it holds: `for dataCategory, extractor := range defaultExtractors`, `snapshotDir, err := snapshot.Temp()`. Go's own guidance prefers short names in short scopes, but a reader of this code, human or agent, should not have to decode `c`, `e`, `ex`, or `d`, whose type is often not on the same line. + +- **What stays short.** The idioms every Go reader knows: `i` and `j` as indexes, `err`, `ctx`, `ok`, `t` and `tb` in tests, the terms `id` and `iv`, and one-letter method receivers, whose type is on the same line. +- **Package names.** A variable cannot take the name of its package — `browser`, `category`, `record`, `keychain` — without shadowing it, so it takes its role: `supportedBrowser`, `dataCategory`, `row`, `loginKeychain`. +- **Enforcement.** `varnamelen` rejects a one- or two-letter name used beyond the next line; `max-distance: 1` is the strictest it allows. The Windows API and ABE packages are excluded until they get their own pass. + ## Summary table | Concept | Decision | Rejected | | ----------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | Supported-browser table | `browser.Supported()` (this OS) + `browser.Lookup` (whole table) | `catalog.All()`, `registry.All()`, `browser.Known()` | -| Per-record source | flat `Browser` + `Profile`, set by `record.Stamp` | `Owner`, `Origin`, `Provenance`, `Source` types | +| Per-record source | flat `Browser` + `Profile`, set by `SetBrowserAndProfile` | `Owner`, `Origin`, `Provenance`, `Source` types | | Extractor input | `browser.ProfileSnapshot{Path, MasterKeys}` | `browser.Input`, `browser.Secrets`, `masterkey.Lazy`, `masterkey.Keys{Set}` | | macOS login keychain | `keychain.Keychain`: one per run, opened on first use | `ProfileSnapshot.KeychainPassword`, a password function in the `Locator`, `keychain.Login`, `masterkey.Keychain` | | Browser base | `Base` (Chromium / Firefox / Safari) | `Family`, `Engine`, `Platform` | -| Browser product | `Def.ID` (no enum); format overrides keyed by ID | `Variant` / `Brand` enum | +| Browser product | `Browser.Name` (no enum); format overrides keyed by name | `Variant` / `Brand` enum | | Data categories | `category.Category` + bare `category.Cookie`…; zero is "none" | `record.Kind`, `CategoryCookie`…, `model` | | Records | `record.Login`, `record.Cookie`…; sealed `record.Record` | `record.CookieItem`, `record.Password`, `record.Item` | -| Data directory | `browser.UserDataDir`, identified by a `DirID` | `Installation` | +| Data directory | `browser.UserDataDir`, identified by a `UserDataDirID` | `Installation` | | Extractor output | `browser.Collector` (`Add` + `Fail`) | `browser.Sink`, `Emit`, an `Emit` func, `Output`, `Recorder` | | Key retrieval input | `masterkey.Locator`, built by `chromium.KeyLocator` | `masterkey.RetrieveInput`, `Hints` | -| Pipeline values | `Discovery`, `Plan`, `Summary` | `type Run` | -| Unit of work | `app.Extraction{DirID, Profile, Category}` | `Job`, `Task`, `Target`, `Unit` | -| Snapshot | `snapshot.Dir` + `snapshot.Snapshot`, returned by `Dir.Snapshot(dirID)` | `snapshot.FS`, `snapshot.Tree`, `snapshot.Copy`, `snapshot.Files`, `Dir.CopyOf`, `type Dir string` | +| Pipeline values | `Options`, `Discovery`, `Plan`, `Summary` | `type Run` | +| Unit of work | `app.Extraction{UserDataDirID, Profile, Category}` | `Job`, `Task`, `Target`, `Unit` | +| Snapshot | `snapshot.Dir` + `snapshot.Snapshot`, returned by `Dir.Snapshot(userDataDirID)` | `snapshot.FS`, `snapshot.Tree`, `snapshot.Copy`, `snapshot.Files`, `Dir.CopyOf`, `type Dir string` | +| Browser row | `browser.Browser` (`Name`, `DisplayName`) | `Def`, `Definition`, `ID` | +| Extractor's file | `browser.FileSpec` | `Source`, `DataFile`, `InputFile`, `Artifact`, `File` | +| Validated flags | `app.Options` | `Request` | +| Variable names | spelled out; only Go's fixed idioms stay short | `c`, `e`, `ex`, `d`, `def` | | Windows packages | `winapi`, `abe` | `platform/windows` | | Leaf helpers | `timeconv.Chromium`…`CoreData`; `sqlitex.CountRows`, `QueryRows` | `timeconv.WebKit`, an exported `sqlitex.QuerySQLite` | diff --git a/rfcs/005-browser-definitions.md b/rfcs/005-browser-definitions.md index de9ea8e..2a05b7b 100644 --- a/rfcs/005-browser-definitions.md +++ b/rfcs/005-browser-definitions.md @@ -2,17 +2,17 @@ ## The table -HBD knows a fixed set of browsers. Each is a `browser.Def`: a static description of how the browser is classified and how it appears on each OS. The table is data, not code — adding a plain fork is adding a row. +HBD knows a fixed set of browsers. Each is a `browser.Browser`: a static description of how the browser is classified and how it appears on each OS. The table is data, not code — adding a plain fork is adding a row. ```go -type Def struct { - ID string // CLI -b value and keys.json vault key; also the first user data dir's DirID: "chrome" - Name string // display name, stamped on every record: "Chrome" - Base Base // Chromium | Firefox | Safari — the only classification enum (RFC-004) +type Browser struct { + Name string // CLI -b value and keys.json vault key; also the first user data dir's UserDataDirID: "chrome" + DisplayName string // set on every record: "Chrome" + Base Base // Chromium | Firefox | Safari — the only classification enum (RFC-004) - Darwin Platform // no UserDataDirs ⇒ not supported on that OS - Linux Platform - Windows Platform + Darwin Platform // no UserDataDirs ⇒ not supported on that OS + Linux Platform + Windows Platform } type Base int @@ -37,7 +37,7 @@ A row, for scale: ```go { - ID: "chrome", Name: "Chrome", Base: Chromium, + Name: "chrome", DisplayName: "Chrome", Base: Chromium, Darwin: Platform{UserDataDirs: []string{"Library/Application Support/Google/Chrome"}, KeychainLabel: "Chrome"}, Linux: Platform{UserDataDirs: []string{".config/google-chrome"}, KeychainLabel: "Chrome Safe Storage"}, Windows: Platform{ @@ -49,45 +49,45 @@ A row, for scale: }, ``` -The per-OS fields are what v1.1.0's code spread across three places: the `KeychainLabel` of each `types.BrowserConfig`, the `WindowsABE` flag, and the separate `winutil.Table` entry joined to it by key. Each fork's label differs per OS (Edge uses `Microsoft Edge` on macOS but `Chromium Safe Storage` on Linux), which is why the label lives in `Platform`, not on `Def`. `UserDataDirs` names data directories; `Exe` and `ExeFallbacks` name the program installation — two different things, kept apart in name as well ([RFC-004](004-naming-decisions.md)). +The per-OS fields are what v1.1.0's code spread across three places: the `KeychainLabel` of each `types.BrowserConfig`, the `WindowsABE` flag, and the separate `winutil.Table` entry joined to it by key. Each fork's label differs per OS (Edge uses `Microsoft Edge` on macOS but `Chromium Safe Storage` on Linux), which is why the label lives in `Platform`, not on `Browser`. `UserDataDirs` names data directories; `Exe` and `ExeFallbacks` name the program installation — two different things, kept apart in name as well ([RFC-004](004-naming-decisions.md)). -One table serves every OS. `Def.Platform()` returns the running OS's entry (a build-tagged one-liner). `Supported()` returns the rows whose entry has `UserDataDirs` — the per-OS list the help text shows, and exactly what `-b` accepts. `Lookup` searches the whole table, so `restore` resolves a vault's `Def` whatever the host OS and a Windows-only fork restores on macOS ([RFC-007](007-snapshot-and-acquisition.md)). +One table serves every OS. `Browser.Platform()` returns the running OS's entry (a build-tagged one-liner). `Supported()` returns the rows whose entry has `UserDataDirs` — the per-OS list the help text shows, and exactly what `-b` accepts. `Lookup` searches the whole table, so `restore` resolves a vault's `Browser` whatever the host OS and a Windows-only fork restores on macOS ([RFC-007](007-snapshot-and-acquisition.md)). -Two axes, kept apart ([RFC-004](004-naming-decisions.md)). `Base` is the only enum and answers "what is this built on" — it selects the base package and the key path. Product/brand identity is just `ID` (a string), so a new fork is a new row, not a new enum constant. Release channel (stable/beta/dev/canary) gets no field, because nothing dispatches on it: each installed channel that keeps its own user data dir is its own `Def`, with an `ID` that names product and channel together (`chrome-beta`). +Two axes, kept apart ([RFC-004](004-naming-decisions.md)). `Base` is the only enum and answers "what is this built on" — it selects the base package and the key path. Product/brand identity is just `Name` (a string), so a new fork is a new row, not a new enum constant. Release channel (stable/beta/dev/canary) gets no field, because nothing dispatches on it: each installed channel that keeps its own user data dir is its own `Browser`, with a `Name` that names product and channel together (`chrome-beta`). Accessors (names per [RFC-004](004-naming-decisions.md)): ```go -browser.Supported() []Def // this OS's rows, in table order -browser.Lookup(id string) (Def, bool) // any row, whatever the OS -browser.IDs() []string // this OS's IDs, sorted, for -b's help and errors +browser.Supported() []Browser // this OS's rows, in table order +browser.Lookup(name string) (Browser, bool) // any row, whatever the OS +browser.Names() []string // this OS's names, sorted, for -b's help and errors ``` ## How a browser produces data -`Def` says _where_. `Base` says _how_. Each base package supplies two functions: +`Browser` says _where_. `Base` says _how_. Each base package supplies two functions: ```go // one per base, in internal/browser/{chromium,firefox,safari} -func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) -func Extractors(dir browser.UserDataDir, p browser.Profile) browser.Extractors +func Discover(supportedBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) +func Extractors(dir browser.UserDataDir, profile browser.Profile) browser.Extractors ``` -`app` calls them through a `switch def.Base`. The dispatch cannot live in `browser`: the base packages import `browser` for these very types, so `browser` calling them would be an import cycle, and `gochecknoinits` rules out init-time registration. These are plain functions, not an interface named `Engine` — that word is rejected project-wide. +`app` calls them through a `switch supportedBrowser.Base`. The dispatch cannot live in `browser`: the base packages import `browser` for these very types, so `browser` calling them would be an import cycle, and `gochecknoinits` rules out init-time registration. These are plain functions, not an interface named `Engine` — that word is rejected project-wide. The Chromium base supplies two more, for the files no single category owns (below): ```go // internal/browser/chromium only -func KeyLocator(dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Locator, error) -func ArchiveSources(dir browser.UserDataDir) []browser.Source +func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterkey.Locator, error) +func ArchiveFileSpecs(dir browser.UserDataDir) []browser.FileSpec ``` Safari's `Extractors` takes one more argument, the run's login keychain, which its password extractor captures. Only the default profile's map gets a password extractor, because the keychain belongs to the user, not to one profile ([RFC-006](006-key-retrieval-and-crypto.md)). `LoginKeychain` is the one-method interface Safari declares; `*keychain.Keychain` satisfies it. ```go // internal/browser/safari only -func Extractors(dir browser.UserDataDir, p browser.Profile, kc LoginKeychain) browser.Extractors +func Extractors(dir browser.UserDataDir, profile browser.Profile, loginKeychain LoginKeychain) browser.Extractors ``` ## Discovery @@ -95,39 +95,39 @@ func Extractors(dir browser.UserDataDir, p browser.Profile, kc LoginKeychain) br Discovery answers one question — which user data dirs and profiles exist — and nothing else. Its rules: - **Explicit inputs.** Everything comes in through `DiscoverOptions`. `app` resolves the home directory once; if that fails the run stops with status `1`. v1.1.0 resolved it in a package-level variable with the error discarded, so a failure silently turned every path into a wrong absolute one, and tests could not substitute a home directory. -- **Every match counts.** Every `UserDataDirs` entry is expanded, globs included, and **every** existing match becomes its own `UserDataDir` — as in v1.1.0, which is what keeps the user data dirs of both of a machine's Arc MSIX packages. The first one of a `Def` gets the `DirID` `Def.ID`, later ones `-2`, `-3`… in path order, so IDs are stable from run to run. +- **Every match counts.** Every `UserDataDirs` entry is expanded, globs included, and **every** existing match becomes its own `UserDataDir` — as in v1.1.0, which is what keeps the user data dirs of both of a machine's Arc MSIX packages. The first one of a `Browser` gets its `Name` as the `UserDataDirID`, later ones `-2`, `-3`… in path order, so IDs are stable from run to run. - **Errors are not absence.** A user data dir that does not exist yields nothing. Any other failure — permission denied, a malformed glob — is returned (joined across entries, next to whatever was found) and becomes an `error` result for that browser in the summary. In v1.1.0 both the Chromium and the Firefox profile scans returned nothing on any read error, and glob errors were dropped while an unmatched pattern was kept as a literal path, so "unreadable" looked exactly like "not installed". - **Profiles by v1.1.0's rules.** Chromium directories holding `Preferences` or `Preferences_02` (Tencent forks), with flat-layout and copied-tree fallbacks; Firefox directories holding known data files; Safari's default profile plus its named profiles (macOS 14+). Whatever the base, a profile counts only when it holds a file some category reads, so a profile created and never used is not listed, archived, or keyed. The named profiles are listed only inside `SafariTabs.db`, so Safari's Discover captures that one file into a temporary snapshot with the snapshot copier and reads the copy, never the live database. -- **No source checks.** Whether a category's file exists is Plan's question, answered as `absent`, or as `error` when the file cannot be checked. v1.1.0 checked every source while constructing the browser and silently dropped a profile that had none; `list` keeps that display rule (profiles with at least one source), but the decision lives outside discovery. -- **`-p` replaces `UserDataDirs` for one `Def`.** When `DiscoverOptions.ProfilePath` is set, discovery reads that path instead of the table's entries, and each base interprets it by the rules in [RFC-009](009-cli-surface.md). +- **No file checks.** Whether a category's file exists is Plan's question, answered as `absent`, or as `error` when the file cannot be checked. v1.1.0 checked every file while constructing the browser and silently dropped a profile that had none; `list` keeps that display rule (profiles with at least one data file), but the decision lives outside discovery. +- **`-p` replaces `UserDataDirs` for one `Browser`.** When `DiscoverOptions.ProfilePath` is set, discovery reads that path instead of the table's entries, and each base interprets it by the rules in [RFC-009](009-cli-surface.md). ## Per-fork overrides — data stays data Most Chromium forks are pure rows. A few store data their own way; v1.1.0 gave them their own `types.BrowserKind` values with `if kind == …` checks across files: -| Fork IDs | What differs | Override | +| Fork names | What differs | Override | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- | -| `yandex` | `Ya Passman Data` and `Ya Credit Cards`, with Yandex's own key wrapping and row format; no account-store passwords | password and credit-card sources and extractors | +| `yandex` | `Ya Passman Data` and `Ya Credit Cards`, with Yandex's own key wrapping and row format; no account-store passwords | password and credit-card file specs, extractors | | `opera`, `opera-gx`, `vought` | extensions under `extensions.opsettings` | extension extractor | -These overrides live inside `internal/browser/chromium`, in one unexported table keyed by `Def.ID` — never by the `DirID`, which differs for a second user data dir — applied when `Extractors` builds a profile's map. No enum is involved and the browser table stays free of code. A unit test asserts that every override key resolves through `Lookup` to a Chromium `Def`, so a typo cannot silently drop an override. +These overrides live inside `internal/browser/chromium`, in one unexported table keyed by `Browser.Name` — never by the `UserDataDirID`, which differs for a second user data dir — applied when `Extractors` builds a profile's map. No enum is involved and the browser table stays free of code. A unit test asserts that every override key resolves through `Lookup` to a Chromium `Browser`, so a typo cannot silently drop an override. -`keys.json` keeps writing v1.1.0's `kind` values (`chromium`, `chromium-yandex`, `chromium-opera`), derived from the same table, so v1.1.0 can still read a new dump. When reading, `restore` resolves the `Def` from the vault's `browser` ID and falls back to `kind` only for an ID this build doesn't know. +`keys.json` keeps writing v1.1.0's `kind` values (`chromium`, `chromium-yandex`, `chromium-opera`), derived from the same table, so v1.1.0 can still read a new dump. When reading, `restore` resolves the `Browser` from the vault's `browser` name and falls back to `kind` only for a name this build doesn't know. ## Shared and per-profile files -Most sources belong to one profile (cookies, history) and are declared relative to the profile directory. A few belong to the whole user data dir — `Local State` above all — and are marked `Shared`, relative to the user data dir itself ([RFC-003](003-core-types.md)). Plan resolves both into paths under the user data dir and captures the union once per user data dir, so `Local State` is copied once however many profiles and categories need it. The flag is explicit on purpose: rewriting every source path per profile while remembering to leave the shared ones alone would make correctness depend on the order of two builder calls. +Most file specs belong to one profile (cookies, history) and are declared relative to the profile directory. A few belong to the whole user data dir — `Local State` above all — and are marked `Shared`, relative to the user data dir itself ([RFC-003](003-core-types.md)). Plan resolves both into paths under the user data dir and captures the union once per user data dir, so `Local State` is copied once however many profiles and categories need it. The flag is explicit on purpose: rewriting every file spec's path per profile while remembering to leave the shared ones alone would make correctness depend on the order of two builder calls. Two Chromium facts concern a whole user data dir rather than one category, and both stay in the Chromium base, so `app` never spells a Chromium file name: -- **Key material.** The extractors that decrypt — passwords, cookies, credit cards — list `Local State` as a `Shared` source, so it is captured only when a decrypting category is requested. `KeyLocator` builds the dir's `masterkey.Locator` from the captured `Local State` and the `Platform` fields; on macOS `app` adds the run's login keychain, then wraps retrieval in the dir's call-once, which every `ProfileSnapshot` of the dir shares as its `MasterKeys` ([RFC-006](006-key-retrieval-and-crypto.md)). -- **Layout markers.** `archive` also captures `Local State` and each profile's `Preferences` (or `Preferences_02`) marker, so a reader without the manifest can still find every profile; `ArchiveSources` names them. +- **Key material.** The extractors that decrypt — passwords, cookies, credit cards — list `Local State` as a `Shared` file spec, so it is captured only when a decrypting category is requested. `KeyLocator` builds the dir's `masterkey.Locator` from the captured `Local State` and the `Platform` fields; on macOS `app` adds the run's login keychain, then wraps retrieval in the dir's call-once, which every `ProfileSnapshot` of the dir shares as its `MasterKeys` ([RFC-006](006-key-retrieval-and-crypto.md)). +- **Layout markers.** `archive` also captures `Local State` and each profile's `Preferences` (or `Preferences_02`) marker, so a reader without the manifest can still find every profile; `ArchiveFileSpecs` names them. ## Adding a browser (the whole motion) For a new Chromium fork: -1. **Add a row** to the table in `internal/browser`: `ID`, `Name`, `Base: Chromium`, and a `Platform` per OS (user data dirs, keychain label; on Windows `Exe`, `ExeFallbacks`, `ABE`). +1. **Add a row** to the table in `internal/browser`: `Name`, `DisplayName`, `Base: Chromium`, and a `Platform` per OS (user data dirs, keychain label; on Windows `Exe`, `ExeFallbacks`, `ABE`). 2. **If `ABE` is not `ABENone`**, add the fork's row to the payload's `com_iid.c` — the CLSID/IIDs and vtable slot the injected payload needs. The technique and how to mine those identifiers are in [RFC-016](016-chrome-abe-integration.md). 3. **Only for a fork with its own on-disk format**, add an override in the Chromium package. 4. **Nothing else.** The fork inherits the entire Chromium base: discovery, every extractor, the key path, snapshot, export, reporting. diff --git a/rfcs/007-snapshot-and-acquisition.md b/rfcs/007-snapshot-and-acquisition.md index 5ff45eb..015a6a2 100644 --- a/rfcs/007-snapshot-and-acquisition.md +++ b/rfcs/007-snapshot-and-acquisition.md @@ -12,9 +12,9 @@ No parser ever reads a live browser profile. Capture copies the files a plan nee ```go type File struct { - DirID string // the user data dir's ID; also the snapshot it lands in - From string // absolute path of the user data dir it is copied from - Rel string // slash-separated path relative to From, and to the snapshot + UserDataDirID string // the user data dir's ID; also the snapshot it lands in + UserDataDirPath string // absolute path of the user data dir it is copied from + RelativePath string // slash-separated path relative to UserDataDirPath, and to the snapshot IsDir bool } @@ -25,7 +25,7 @@ func Open(path string) (*Dir, error) // an existing one, used in place func Unzip(src string) (*Dir, error) // into a temporary snapshot directory func (d *Dir) Capture(ctx context.Context, files []File) error -func (d *Dir) Snapshot(dirID string) Snapshot // one user data dir's snapshot +func (d *Dir) Snapshot(userDataDirID string) Snapshot // one user data dir's snapshot func (d *Dir) Zip(dst string) error // archive transport func (d *Dir) Close() error @@ -46,15 +46,15 @@ Because it holds those copies, a temporary snapshot directory is created with mo ## Layout and user data dir identity -A snapshot directory is `//`: one subdirectory, one snapshot, per user data dir. For the first user data dir of a browser the ID is its `Def.ID`, so the layout is exactly v1.1.0's archive layout (`/`) and v1.1.0's `restore` reads new archives unchanged. A second one of the same browser — the second of Arc's two MSIX packages on Windows — gets `arc-2/`, where v1.1.0's archive keyed every file by browser key alone and silently dropped it. +A snapshot directory is `//`: one subdirectory, one snapshot, per user data dir. For the first user data dir of a browser the ID is its `Browser.Name`, so the layout is exactly v1.1.0's archive layout (`/`) and v1.1.0's `restore` reads new archives unchanged. A second one of the same browser — the second of Arc's two MSIX packages on Windows — gets `arc-2/`, where v1.1.0's archive keyed every file by browser key alone and silently dropped it. -An archive captures what v1.1.0's did — `Local State` and each profile's `Preferences` marker (both named by the Chromium base, [RFC-005](005-browser-definitions.md)), the requested categories' sources, and the account-synced `Login Data For Account` — so a reader without the manifest can still find every profile. +An archive captures what v1.1.0's did — `Local State` and each profile's `Preferences` marker (both named by the Chromium base, [RFC-005](005-browser-definitions.md)), the requested categories' files, and the account-synced `Login Data For Account` — so a reader without the manifest can still find every profile. -`keys.json` joins to the archive by the vault's `browser` key, as in v1.1.0. A vault for a second user data dir carries an extra optional `id` field (`"arc-2"`) — the `DirID` on the wire, per the wire-name rule; readers that don't know the field, including v1.1.0, ignore it and restore the first one. The dump version stays `"2"`. +`keys.json` joins to the archive by the vault's `browser` key, as in v1.1.0. A vault for a second user data dir carries an extra optional `id` field (`"arc-2"`) — the `UserDataDirID` on the wire, per the wire-name rule; readers that don't know the field, including v1.1.0, ignore it and restore the first one. The dump version stays `"2"`. ## Manifest -A new snapshot directory carries `manifest.json` at its root: a schema version, and per user data dir its ID, `Def.ID`, `Base`, profiles, and captured paths. `restore` uses it, when present, to rebuild user data dirs and profiles without re-discovering anything — that is its `Discovery` ([RFC-003](003-core-types.md)) — and then runs Extract → Export → Report exactly as a live run would. Restore trusts no manifest path that would leave its own directory of the archive. Archives without a manifest — every archive v1.1.0 made — still restore through the keys.json vaults plus the directory layout. v1.1.0 ignores the extra file. +A new snapshot directory carries `manifest.json` at its root: a schema version, and per user data dir its ID, `Browser.Name`, `Base`, profiles, and captured paths. `restore` uses it, when present, to rebuild user data dirs and profiles without re-discovering anything — that is its `Discovery` ([RFC-003](003-core-types.md)) — and then runs Extract → Export → Report exactly as a live run would. Restore trusts no manifest path that would leave its own directory of the archive. Archives without a manifest — every archive v1.1.0 made — still restore through the keys.json vaults plus the directory layout. v1.1.0 ignores the extra file. ## Copy semantics diff --git a/rfcs/008-output-and-export.md b/rfcs/008-output-and-export.md index 2e75ae0..d92dacc 100644 --- a/rfcs/008-output-and-export.md +++ b/rfcs/008-output-and-export.md @@ -1,6 +1,6 @@ # RFC-008: Output & Export -Everything a user can see in the output — file names, formats, field names, stamp values — is frozen by the compatibility contract ([RFC-000](000-goals-and-constraints.md)). This RFC describes how the exporter reproduces it byte for byte, and the few places where v1.1.0's output was wrong and is fixed. +Everything a user can see in the output — file names, formats, field names, browser and profile values — is frozen by the compatibility contract ([RFC-000](000-goals-and-constraints.md)). This RFC describes how the exporter reproduces it byte for byte, and the few places where v1.1.0's output was wrong and is fixed. ## Contract @@ -39,9 +39,9 @@ JSON keys and CSV headers are the snake_case form of the Go field names: `Cookie The consequence is stated plainly: since the output is frozen, **the record field names are frozen too** — a rename would change a column. A field can only be renamed together with a deliberate, announced output change, and the lint makes such a change impossible to miss in review. -### Source stamp +### Browser and profile fields -Every record starts with two flat source fields — `Browser` and `Profile` ([RFC-003](003-core-types.md)) — serialized as the leading `browser` and `profile` keys in JSON and the leading columns in CSV, exactly as in v1.1.0. `browser` is the display name (`Chrome`, `Microsoft Edge`); `profile` is the profile name (`Default`, `Profile 1`, a Safari profile's title), never a path. The pipeline's `Collector` sets both through `record.Stamp`, so no extractor can leave them out. +Every record starts with two flat source fields — `Browser` and `Profile` ([RFC-003](003-core-types.md)) — serialized as the leading `browser` and `profile` keys in JSON and the leading columns in CSV, exactly as in v1.1.0. `browser` is the display name (`Chrome`, `Microsoft Edge`); `profile` is the profile name (`Default`, `Profile 1`, a Safari profile's title), never a path. The pipeline's `Collector` sets both through `SetBrowserAndProfile`, so no extractor can leave them out. ## Deterministic ordering diff --git a/rfcs/009-cli-surface.md b/rfcs/009-cli-surface.md index 21607ff..74de686 100644 --- a/rfcs/009-cli-surface.md +++ b/rfcs/009-cli-surface.md @@ -71,7 +71,7 @@ After a run, the reporter prints a per-browser, per-profile, per-category summar ## `restore` specifics (unchanged) -`restore`'s universe is its `keys.json`, not the local table: `-b` filters the dump's vaults, and a vault's `Def` is resolved with `browser.Lookup`, which searches the whole table whatever the host OS ([RFC-005](005-browser-definitions.md)), so a Windows-only fork restores on macOS. Exactly one of `--data-dir` and `--data-zip` is required. A zip is extracted into a temporary snapshot directory (`snapshot.Unzip`), rejecting entries that escape it, and removed when the run ends; a `--data-dir` is opened in place (`snapshot.Open`) and never removed ([RFC-007](007-snapshot-and-acquisition.md)). The data has two layouts, as in v1.1.0: `/` subdirectories (the archive layout), from which every selected vault restores, or one browser's hand-copied `User Data`, which is unambiguous only when `-b` selects a single vault. +`restore`'s universe is its `keys.json`, not the local table: `-b` filters the dump's vaults, and a vault's `Browser` is resolved with `browser.Lookup`, which searches the whole table whatever the host OS ([RFC-005](005-browser-definitions.md)), so a Windows-only fork restores on macOS. Exactly one of `--data-dir` and `--data-zip` is required. A zip is extracted into a temporary snapshot directory (`snapshot.Unzip`), rejecting entries that escape it, and removed when the run ends; a `--data-dir` is opened in place (`snapshot.Open`) and never removed ([RFC-007](007-snapshot-and-acquisition.md)). The data has two layouts, as in v1.1.0: `/` subdirectories (the archive layout), from which every selected vault restores, or one browser's hand-copied `User Data`, which is unambiguous only when `-b` selects a single vault. ## DEFERRED diff --git a/rfcs/011-testing-and-quality.md b/rfcs/011-testing-and-quality.md index e7e9d9c..5304e9d 100644 --- a/rfcs/011-testing-and-quality.md +++ b/rfcs/011-testing-and-quality.md @@ -8,7 +8,7 @@ The pipeline split ([RFC-001](001-architecture-and-pipeline.md)) exists partly s | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `crypto` primitives | Pure functions over bytes; fixed known-answer vectors. No OS, no files. | | `category` | `String` / `Parse` round-trip over `All()`; the zero `Category` is "none". | -| `record` | `Stamp` sets `Browser` and `Profile`; every record type's tags equal snake_case(field name); each type's `Category()` matches the table in [RFC-003](003-core-types.md). | +| `record` | `SetBrowserAndProfile` sets `Browser` and `Profile`; every record type's tags equal snake_case(field name); each type's `Category()` matches the table in [RFC-003](003-core-types.md). | | extractors (`browser/*`) | A sanitized fixture (SQLite, JSON, plist, LevelDB) in `testdata/`, captured into a `t.TempDir()` snapshot, parsed, and compared to a golden record set. No live browser. | | `snapshot` | `t.TempDir()`; capture with `-wal`/`-shm` sidecars, reopen, zip round-trip, Zip-Slip rejection; a vanished file reads back as `fs.ErrNotExist` and a failed copy as its error while the rest of the capture completes; `Close` removes a temporary snapshot directory — also after an error — and leaves an opened one in place. | | `export` | Records in → golden `csv` / `json` / `cookie-editor` out; deterministic order; byte-identical to v1.1.0's encoder on the same records, HTML escaping included. | @@ -31,7 +31,7 @@ These guard the contract; a failure means something a user can see has changed. Export and extractor tests compare against checked-in golden outputs. Deterministic ordering is what makes goldens stable — without it, goldens would flap. Setting `HBD_UPDATE_GOLDEN=1` regenerates them on intentional changes. Goldens double as documentation of the exact output shape, useful for the README and for talks. -Each golden lives beside the package whose output it pins: the export goldens in `export`, `keys.json` in `masterkey`, and the `extract`, `archive`, and `restore` goldens — all of which run the pipeline — in `app`; the flag-surface and `list` goldens stay in `cmd/hack-browser-data`. Shared fixture builders are in `internal/browser/browsertest`, the comparison helpers in `internal/golden`. A golden holds what no other golden already implies: the Cookie-Editor golden holds only `cookie.json`, because every other category is asserted to match the json output byte for byte, and `restore` is asserted to match the extract output except for its `browser` stamp. +Each golden lives beside the package whose output it pins: the export goldens in `export`, `keys.json` in `masterkey`, and the `extract`, `archive`, and `restore` goldens — all of which run the pipeline — in `app`; the flag-surface and `list` goldens stay in `cmd/hack-browser-data`. Shared fixture builders are in `internal/browser/browsertest`, the comparison helpers in `internal/golden`. A golden holds what no other golden already implies: the Cookie-Editor golden holds only `cookie.json`, because every other category is asserted to match the json output byte for byte, and `restore` is asserted to match the extract output except for its `browser` value. ## Regression tests for the known bugs @@ -66,7 +66,7 @@ Each bug designed out by this rewrite gets a test that would have caught it, so ## Table and payload consistency -- Every key in the Chromium override table resolves through `browser.Lookup` to a Chromium `Def`. +- Every key in the Chromium override table resolves through `browser.Lookup` to a Chromium `Browser`. - Every Windows row of the table with `ABE` other than `ABENone` has a row in the payload's `com_iid.c` with the same executable and ABE kind; the test parses the C table, which may list browsers the Go table does not, such as Avast. It lives inside `browser` and reads the whole table, since `Supported()` lists only the running OS's rows. (The Go-side `winutil.Table` join, and the `TestWinUtilTableCoversABEBrowsers` that guarded it, disappear into `Platform`.) ## Import direction diff --git a/rfcs/016-chrome-abe-integration.md b/rfcs/016-chrome-abe-integration.md index 5130dd8..d9737b8 100644 --- a/rfcs/016-chrome-abe-integration.md +++ b/rfcs/016-chrome-abe-integration.md @@ -295,7 +295,7 @@ Three steps. 2. **Mine IIDs from TypeLib** — the interface IIDs live in the TypeLib resource of `\Application\\elevation_service.exe`. PowerShell + `ITypeLib.GetTypeInfo` enumerates them. Map `IElevator` → v1 IID, `IElevator2` → v2 IID (absent for older vendors). 3. **Determine vtable slot** — count `IElevator` methods in the TypeLib. Chrome-family has 3 methods (slot 5). Edge prepends 3 placeholders (slot 8). Avast extends the interface further (slot 13). -Edit `internal/abe/native/com_iid.c` (add the C-side entry: exe, kind, CLSID, IIDs) and `internal/browser/table.go` (on the browser's `Def` row, set the `Windows` platform's `Exe`, `ExeFallbacks`, and `ABE` to the matching `masterkey.ABEKind`), then `make payload-clean && make build-windows` and redeploy. `TestABERowsMatchPayloadTable` fails at `go test` time if a Go `ABE` row has no `com_iid.c` row with the same exe and kind. +Edit `internal/abe/native/com_iid.c` (add the C-side entry: exe, kind, CLSID, IIDs) and `internal/browser/table.go` (on the browser's row, set the `Windows` platform's `Exe`, `ExeFallbacks`, and `ABE` to the matching `masterkey.ABEKind`), then `make payload-clean && make build-windows` and redeploy. `TestABERowsMatchPayloadTable` fails at `go test` time if a Go `ABE` row has no `com_iid.c` row with the same exe and kind. ## 12. Known issues & future work