mirror of
https://github.com/moonD4rk/HackBrowserData.git
synced 2026-12-04 05:43:27 +01:00
fix: validate first and make -p select what it names (#664)
The pipeline's Validate rejects bad -b/-c/-f/-d/-p before discovery (an unknown -b now exits 1). -p at a Chromium profile dir uses its parent, so Local State is found; Firefox -p selects only that profile; the keychain password comes from a flag, stdin, a terminal prompt, or nowhere.
This commit is contained in:
1 parent
8c9c9901a1
commit
1636091b3f
14 files changed
+367
-39
No files matched your search
+96
-16
@@ -5,25 +5,30 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/export"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
)
|
||||
|
||||
// Flags are a run's command-line values as cobra parsed them.
|
||||
type Flags struct {
|
||||
Browser string
|
||||
Categories string
|
||||
Format string
|
||||
Dir string
|
||||
Zip bool
|
||||
ProfilePath string
|
||||
KeychainPassword string
|
||||
Browser string
|
||||
Categories string
|
||||
Format string
|
||||
Dir string
|
||||
Zip bool
|
||||
ProfilePath string
|
||||
KeychainPassword string
|
||||
KeychainPasswordStdin bool
|
||||
}
|
||||
|
||||
// Request is a validated run.
|
||||
@@ -42,8 +47,17 @@ type Request struct {
|
||||
Keys map[browser.DirID]masterkey.Set
|
||||
}
|
||||
|
||||
// Validate checks the flags and resolves the home directory, so nothing later reads the environment.
|
||||
// Validate checks every flag before any browser is touched or any secret is read, and resolves the home directory, so
|
||||
// nothing later reads the environment.
|
||||
func Validate(f Flags) (Request, error) {
|
||||
return validate(f, os.Stdin)
|
||||
}
|
||||
|
||||
func validate(f Flags, stdin *os.File) (Request, error) {
|
||||
id, err := parseBrowser(f.Browser)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
categories, err := parseCategories(f.Categories)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
@@ -52,27 +66,93 @@ func Validate(f Flags) (Request, error) {
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
if err := checkOutputDir(f.Dir); err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
profilePath, err := checkProfilePath(id, f.ProfilePath)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
password, err := keychainPassword(f, stdin)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return Request{}, fmt.Errorf("home directory: %w", err)
|
||||
}
|
||||
name := strings.ToLower(strings.TrimSpace(f.Browser))
|
||||
if name == "" {
|
||||
name = "all"
|
||||
}
|
||||
password := f.KeychainPassword
|
||||
return Request{
|
||||
Browser: name,
|
||||
Browser: id,
|
||||
Categories: categories,
|
||||
Format: format,
|
||||
Dir: f.Dir,
|
||||
Zip: f.Zip,
|
||||
ProfilePath: f.ProfilePath,
|
||||
ProfilePath: profilePath,
|
||||
Home: home,
|
||||
KeychainPassword: func(context.Context) (string, error) { return password, nil },
|
||||
KeychainPassword: password,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 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 == "all" {
|
||||
return "all", nil
|
||||
}
|
||||
ids := []string{"all"}
|
||||
for _, def := range browser.Supported() {
|
||||
if def.ID == id {
|
||||
return id, nil
|
||||
}
|
||||
ids = append(ids, def.ID)
|
||||
}
|
||||
return "", fmt.Errorf("unknown browser %q, available: %s", s, strings.Join(ids, "|"))
|
||||
}
|
||||
|
||||
// checkOutputDir creates nothing: -d must already be a directory, or its nearest existing ancestor must be one that a
|
||||
// directory can be created in.
|
||||
func checkOutputDir(dir string) error {
|
||||
path := filepath.Clean(dir)
|
||||
for {
|
||||
info, err := os.Stat(path)
|
||||
switch {
|
||||
case err == nil && info.IsDir():
|
||||
if err := canCreateIn(path); err != nil {
|
||||
return fmt.Errorf("output dir %s: %w", dir, err)
|
||||
}
|
||||
return nil
|
||||
case err == nil:
|
||||
return fmt.Errorf("output dir %s: %s is not a directory", dir, path)
|
||||
case !errors.Is(err, fs.ErrNotExist):
|
||||
return fmt.Errorf("output dir %s: %w", dir, err)
|
||||
}
|
||||
parent := filepath.Dir(path)
|
||||
if parent == path {
|
||||
return fmt.Errorf("output dir %s: no existing parent directory", dir)
|
||||
}
|
||||
path = parent
|
||||
}
|
||||
}
|
||||
|
||||
// checkProfilePath keeps -p only when one browser is named; with -b all it is ignored, as it always was, but now said.
|
||||
func checkProfilePath(id, path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", nil
|
||||
}
|
||||
if id == "all" {
|
||||
log.Warnf("-p needs a specific -b; ignoring %s", path)
|
||||
return "", nil
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("profile path: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", fmt.Errorf("profile path %s: not a directory", path)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// parseCategories reads a comma-separated -c value; a repeated category is kept once, or its records would be
|
||||
// exported twice.
|
||||
func parseCategories(s string) ([]category.Category, error) {
|
||||
|
||||
@@ -2,11 +2,17 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/export"
|
||||
)
|
||||
@@ -30,12 +36,96 @@ func TestValidate(t *testing.T) {
|
||||
}
|
||||
|
||||
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{
|
||||
"unknown category": {Categories: "cookie,bogus", Format: "json"},
|
||||
"no category": {Categories: " , ", Format: "json"},
|
||||
"unknown format": {Categories: "all", Format: "xml"},
|
||||
"unknown category": {Categories: "cookie,bogus", Format: "json"},
|
||||
"no category": {Categories: " , ", Format: "json"},
|
||||
"unknown format": {Categories: "all", Format: "xml"},
|
||||
"unknown browser": {Browser: "bogus", Categories: "all", Format: "json"},
|
||||
"another OS's browser": {Browser: otherOSBrowser(t), Categories: "all", Format: "json"},
|
||||
"-d below a file": {Categories: "all", Format: "json", Dir: filepath.Join(file, "out")},
|
||||
"-d is a file": {Categories: "all", Format: "json", Dir: file},
|
||||
"missing -p": {Browser: "chrome", Categories: "all", Format: "json", ProfilePath: missing},
|
||||
"-p is a file": {Browser: "chrome", Categories: "all", Format: "json", ProfilePath: file},
|
||||
"two password inputs": {Categories: "all", Format: "json", KeychainPassword: "pw", KeychainPasswordStdin: true},
|
||||
} {
|
||||
_, err := Validate(f)
|
||||
assert.Error(t, err, name)
|
||||
}
|
||||
}
|
||||
|
||||
// otherOSBrowser is a browser in the table that the running OS does not have.
|
||||
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
|
||||
}
|
||||
}
|
||||
t.Fatal("every candidate is supported here")
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestValidate_CreatesNoOutputDir(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
req, 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)
|
||||
_, err = os.Stat(filepath.Join(root, "a"))
|
||||
assert.ErrorIs(t, err, fs.ErrNotExist)
|
||||
}
|
||||
|
||||
func TestValidate_RejectsAnOutputDirThatCannotBeCreated(t *testing.T) {
|
||||
if runtime.GOOS == "windows" || os.Geteuid() == 0 {
|
||||
t.Skip("directory permissions do not deny writes here")
|
||||
}
|
||||
root := t.TempDir()
|
||||
require.NoError(t, os.Chmod(root, 0o500))
|
||||
defer func() { require.NoError(t, os.Chmod(root, 0o700)) }()
|
||||
|
||||
_, err := Validate(Flags{Categories: "all", Format: "json", Dir: filepath.Join(root, "results")})
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
// -p without a named browser was always ignored; it is still not checked, only reported.
|
||||
func TestValidate_IgnoresProfilePathForAllBrowsers(t *testing.T) {
|
||||
req, err := Validate(Flags{Browser: "all", Categories: "all", Format: "json", ProfilePath: filepath.Join(t.TempDir(), "missing")})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, req.ProfilePath)
|
||||
}
|
||||
|
||||
func TestValidate_KeychainPasswordInputs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
flags Flags
|
||||
stdin string
|
||||
want string
|
||||
err error
|
||||
}{
|
||||
{name: "flag", flags: Flags{KeychainPassword: "from-flag"}, stdin: "from-stdin\n", want: "from-flag"},
|
||||
{name: "stdin", flags: Flags{KeychainPasswordStdin: true}, stdin: "from-stdin\r\nnext\n", want: "from-stdin"},
|
||||
{name: "stdin without newline", flags: Flags{KeychainPasswordStdin: true}, stdin: "from-stdin", want: "from-stdin"},
|
||||
{name: "none off a terminal", flags: Flags{}, stdin: "from-stdin\n", err: errNoPassword},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, w, err := os.Pipe()
|
||||
require.NoError(t, err)
|
||||
defer r.Close()
|
||||
_, err = w.WriteString(tt.stdin)
|
||||
require.NoError(t, errors.Join(err, w.Close()))
|
||||
|
||||
tt.flags.Categories, tt.flags.Format = "all", "json"
|
||||
req, err := validate(tt.flags, r)
|
||||
require.NoError(t, err)
|
||||
got, err := req.KeychainPassword(context.Background())
|
||||
require.ErrorIs(t, err, tt.err)
|
||||
assert.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !windows
|
||||
|
||||
package app
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
func canCreateIn(dir string) error {
|
||||
return unix.Access(dir, unix.W_OK|unix.X_OK)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build windows
|
||||
|
||||
package app
|
||||
|
||||
// canCreateIn accepts every directory: Windows grants writes through ACLs that only the write itself can check.
|
||||
func canCreateIn(string) error { return nil }
|
||||
@@ -0,0 +1,51 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
var errNoPassword = errors.New("macOS login password not given and stdin is not a terminal")
|
||||
|
||||
// keychainPassword picks the run's one source of the macOS login password, read when the keychain is first opened: a
|
||||
// flag, else a no-echo prompt on a terminal, else none, which leaves keychain-protected data as metadata only.
|
||||
func keychainPassword(f Flags, stdin *os.File) (func(context.Context) (string, error), error) {
|
||||
switch {
|
||||
case f.KeychainPassword != "" && f.KeychainPasswordStdin:
|
||||
return nil, errors.New("--keychain-pw and --keychain-pw-stdin cannot be used together")
|
||||
case f.KeychainPassword != "":
|
||||
password := f.KeychainPassword
|
||||
return func(context.Context) (string, error) { return password, nil }, nil
|
||||
case f.KeychainPasswordStdin:
|
||||
return func(context.Context) (string, error) { return firstLine(stdin) }, nil
|
||||
case term.IsTerminal(int(stdin.Fd())):
|
||||
return func(context.Context) (string, error) { return prompt(stdin) }, nil
|
||||
default:
|
||||
return func(context.Context) (string, error) { return "", errNoPassword }, nil
|
||||
}
|
||||
}
|
||||
|
||||
func firstLine(r io.Reader) (string, error) {
|
||||
line, err := bufio.NewReader(r).ReadString('\n')
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return "", fmt.Errorf("read the password from stdin: %w", err)
|
||||
}
|
||||
return strings.TrimRight(line, "\r\n"), nil
|
||||
}
|
||||
|
||||
func prompt(stdin *os.File) (string, error) {
|
||||
fmt.Fprint(os.Stderr, "Enter macOS login password: ")
|
||||
password, err := term.ReadPassword(int(stdin.Fd()))
|
||||
fmt.Fprintln(os.Stderr)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read the password: %w", err)
|
||||
}
|
||||
return string(password), nil
|
||||
}
|
||||
@@ -21,6 +21,9 @@ var profileMarkers = []string{"Preferences", "Preferences_02"}
|
||||
// Discover finds def's user data dirs and their profiles. A user data dir that does not exist yields nothing; any
|
||||
// other failure is returned, joined across dirs, beside whatever was found.
|
||||
func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) {
|
||||
if dir, ok := profileAt(def, opts.ProfilePath); ok {
|
||||
return []browser.UserDataDir{dir}, nil
|
||||
}
|
||||
paths, err := userDataDirPaths(def, opts)
|
||||
errs := []error{err}
|
||||
var dirs []browser.UserDataDir
|
||||
@@ -40,6 +43,22 @@ func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserData
|
||||
return dirs, errors.Join(errs...)
|
||||
}
|
||||
|
||||
// profileAt reads -p as the path chrome://version shows: a directory with a profile marker but no Local State is one
|
||||
// profile, so its parent is the user data dir that holds the keys, and only that profile is selected.
|
||||
func profileAt(def browser.Def, path string) (browser.UserDataDir, bool) {
|
||||
if path == "" || !isProfileDir(path) || hasAnySource(path, localState.Paths) {
|
||||
return browser.UserDataDir{}, false
|
||||
}
|
||||
clean := filepath.Clean(path)
|
||||
name := filepath.Base(clean)
|
||||
return browser.UserDataDir{
|
||||
ID: dirID(def, 0),
|
||||
Def: def,
|
||||
Path: filepath.Dir(clean),
|
||||
Profiles: []browser.Profile{{Name: name, Dir: name}},
|
||||
}, true
|
||||
}
|
||||
|
||||
// userDataDirPaths keeps every glob match, so both of a machine's Arc packages are found. Joining with "/" keeps the
|
||||
// path strings keys.json has always recorded; -p replaces the table's entries.
|
||||
func userDataDirPaths(def browser.Def, opts browser.DiscoverOptions) ([]string, error) {
|
||||
|
||||
@@ -135,6 +135,37 @@ func TestDiscover_ProfilePathReplacesTheTable(t *testing.T) {
|
||||
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.
|
||||
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)
|
||||
require.NoError(t, err)
|
||||
want := browser.UserDataDir{
|
||||
ID: "chrome", Def: testDef("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.
|
||||
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})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, dirs, 1)
|
||||
assert.Equal(t, flat, dirs[0].Path)
|
||||
assert.Equal(t, []browser.Profile{{Name: filepath.Base(flat)}}, dirs[0].Profiles)
|
||||
}
|
||||
|
||||
func TestExtractors_CoverEveryCategory(t *testing.T) {
|
||||
ex := Extractors(browser.UserDataDir{Def: testDef("chrome")}, browser.Profile{})
|
||||
for _, c := range category.All() {
|
||||
|
||||
@@ -32,9 +32,12 @@ var extractors = browser.Extractors{
|
||||
category.LocalStorage: plain(file("webappsstore.sqlite"), extractLocalStorage),
|
||||
}
|
||||
|
||||
// Discover finds def's Profiles directory and the profiles in it. -p names one profile, and its parent directory is
|
||||
// searched, as today.
|
||||
// Discover finds def's Profiles directory and the profiles in it. -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
|
||||
}
|
||||
var errs []error
|
||||
var dirs []browser.UserDataDir
|
||||
for i, path := range userDataDirPaths(def, opts) {
|
||||
@@ -53,10 +56,21 @@ func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserData
|
||||
return dirs, errors.Join(errs...)
|
||||
}
|
||||
|
||||
func userDataDirPaths(def browser.Def, opts browser.DiscoverOptions) []string {
|
||||
if opts.ProfilePath != "" {
|
||||
return []string{filepath.Dir(filepath.Clean(opts.ProfilePath))}
|
||||
func profileAt(def browser.Def, 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,
|
||||
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)))
|
||||
|
||||
@@ -83,8 +83,8 @@ func TestDiscover_UnreadableUserDataDirIsAnError(t *testing.T) {
|
||||
assert.Empty(t, dirs)
|
||||
}
|
||||
|
||||
// -p names one profile, yet every profile beside it is found too, as today; narrowing to it waits for the switch-over.
|
||||
func TestDiscover_ProfilePathSearchesItsParent(t *testing.T) {
|
||||
// Before, -p searched its parent and exported every profile beside the one it named.
|
||||
func TestDiscover_ProfilePathSelectsOnlyThatProfile(t *testing.T) {
|
||||
custom := t.TempDir()
|
||||
touch(t, custom, "abcd1234.default-release", "places.sqlite")
|
||||
touch(t, custom, "wxyz5678.work", "places.sqlite")
|
||||
@@ -94,7 +94,17 @@ func TestDiscover_ProfilePathSearchesItsParent(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Len(t, dirs, 1)
|
||||
assert.Equal(t, custom, dirs[0].Path)
|
||||
assert.Len(t, dirs[0].Profiles, 2)
|
||||
assert.Equal(t, []browser.Profile{{Name: "abcd1234.default-release", Dir: "abcd1234.default-release"}}, dirs[0].Profiles)
|
||||
}
|
||||
|
||||
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)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, dirs)
|
||||
}
|
||||
|
||||
func TestExtractors_CoverFirefoxCategories(t *testing.T) {
|
||||
|
||||
@@ -51,14 +51,22 @@ func TestDiscover_MissingSafariYieldsNothing(t *testing.T) {
|
||||
assert.Empty(t, dirs)
|
||||
}
|
||||
|
||||
// -p does not apply to Safari: the table's directory is used, and Validate rejects -p at the switch-over.
|
||||
func TestDiscover_IgnoresProfilePath(t *testing.T) {
|
||||
func TestDiscover_ProfilePathIsTheSafariDir(t *testing.T) {
|
||||
const uuid = "5604E6F5-02ED-4E40-8249-63DE7BC986C8"
|
||||
copied := t.TempDir()
|
||||
mkFile(t, copied, "Library", "SafariCopy", "History.db")
|
||||
container := filepath.Join(copied, "Library", "Containers", "com.apple.Safari", "Data", "Library")
|
||||
mkFile(t, container, "Safari", "Profiles", uuid, "History.db")
|
||||
writeSafariTabsDB(t, filepath.Join(container, "Safari", "SafariTabs.db"), []tabRow{{uuid: uuid, title: "work"}})
|
||||
|
||||
home := t.TempDir()
|
||||
libraryAt(t, home)
|
||||
dirs, err := Discover(testDef(), browser.DiscoverOptions{Home: home, ProfilePath: t.TempDir()})
|
||||
opts := browser.DiscoverOptions{Home: home, ProfilePath: filepath.Join(copied, "Library", "SafariCopy")}
|
||||
dirs, err := Discover(testDef(), opts)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, dirs, 1)
|
||||
assert.Equal(t, filepath.Join(home, "Library"), dirs[0].Path)
|
||||
assert.Equal(t, filepath.Join(copied, "Library"), dirs[0].Path)
|
||||
assert.Equal(t, []browser.Profile{{Name: "default", Dir: "SafariCopy"}, named("work", uuid)}, dirs[0].Profiles)
|
||||
}
|
||||
|
||||
func TestDiscover_WithNamedProfile(t *testing.T) {
|
||||
|
||||
@@ -36,12 +36,11 @@ type LoginKeychain interface {
|
||||
}
|
||||
|
||||
// Discover finds Safari's data under ~/Library: the default profile, whose Dir is the Safari directory, and the named
|
||||
// profiles SafariTabs.db lists. -p does not apply to Safari, and Validate rejects it at the switch-over.
|
||||
// profiles SafariTabs.db lists. -p names another Safari directory, whose parent stands in for ~/Library.
|
||||
func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) {
|
||||
var errs []error
|
||||
var dirs []browser.UserDataDir
|
||||
for i, rel := range def.Platform().UserDataDirs {
|
||||
safariPath := filepath.Join(opts.Home, filepath.FromSlash(rel))
|
||||
for i, safariPath := range safariPaths(def, opts) {
|
||||
if _, err := os.Stat(safariPath); err != nil {
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
errs = append(errs, fmt.Errorf("%s: %w", safariPath, err))
|
||||
@@ -56,6 +55,17 @@ func Discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserData
|
||||
return dirs, errors.Join(errs...)
|
||||
}
|
||||
|
||||
func safariPaths(def browser.Def, opts browser.DiscoverOptions) []string {
|
||||
if opts.ProfilePath != "" {
|
||||
return []string{filepath.Clean(opts.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)))
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
func dirID(def browser.Def, i int) browser.DirID {
|
||||
if i == 0 {
|
||||
return browser.DirID(def.ID)
|
||||
|
||||
@@ -40,7 +40,7 @@ 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` (today's status), **before** any browser is discovered and **before** any keychain prompt. Today `-c` and `-f` are checked only after discovery and the prompt; that ordering bug is designed out here.
|
||||
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` (today's status, except for an unknown browser ID, which found nothing and exited `0`; [RFC-009](009-cli-surface.md)), **before** any browser is discovered and **before** any keychain prompt. Today `-c` and `-f` are checked only after discovery and the prompt; that ordering bug is designed out here.
|
||||
|
||||
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` logs a warning and is ignored, as today, instead of being dropped silently.
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ The flag names stay, and the Go names follow them: `-c/--category` selects `cate
|
||||
|
||||
## Validation happens first — the ordering bug, designed out
|
||||
|
||||
Today `-c` and `-f` are checked only after discovery and after the keychain prompt (`cmd/hack-browser-data/dump.go`, `extract.go`), so a typo in a format wastes a prompt and a discovery pass. In the rewrite, **Validate is stage 1** ([RFC-001](001-architecture-and-pipeline.md)): an unknown format, category, or browser ID, a `-d` that cannot be created, `--data-dir` together with `--data-zip`, or an unreadable `--keys` all fail before any browser is touched and before any secret is read. The exit status stays today's `1`; only the timing changes. The rule: _nothing with a side effect runs until the request is valid._
|
||||
Today `-c` and `-f` are checked only after discovery and after the keychain prompt (`cmd/hack-browser-data/dump.go`, `extract.go`), so a typo in a format wastes a prompt and a discovery pass. In the rewrite, **Validate is stage 1** ([RFC-001](001-architecture-and-pipeline.md)): an unknown format, category, or browser ID, a `-d` that cannot be created, `--data-dir` together with `--data-zip`, or an unreadable `--keys` all fail before any browser is touched and before any secret is read. These exit `1`, as today; only the timing changes, and a typo in `-c` or `-f` now fails even where no browser is found, where today the run stops first at "no browsers found" with `0`. An unknown `-b`, including a browser only another OS has, is the same case: today it finds nothing and exits `0`; like a missing `-p`, it now exits `1`, because such a command line never did anything. The rule: _nothing with a side effect runs until the request is valid._
|
||||
|
||||
## `-p, --profile-path` — same meaning, the long-standing bugs fixed
|
||||
|
||||
@@ -41,9 +41,9 @@ The flag keeps its meaning and its name: a custom data location for one browser.
|
||||
|
||||
- **Validated first.** Today a non-existent `-p` is read as an empty directory, so the run just says "no browsers found" and exits `0`. Validate now checks that the path exists and is a directory, and exits `1` with a clear message if not ([RFC-001](001-architecture-and-pipeline.md)).
|
||||
- **With `-b all`.** Today `-p` is silently ignored when `-b` is `all` (`browser/browser.go`, `discoverFromConfigs`), because the override is guarded by `name != "all"`. Validate now logs a warning that `-p` needs a specific `-b`, then ignores it as before — the run itself is unchanged. Rejecting the combination would turn today's exit status `0` into `1`, which the contract rules out.
|
||||
- **Pointing at a Chromium profile directory.** The help text asks for the path `chrome://version` shows, which is a profile directory (`…/User Data/Default`). Today that directory becomes the whole user data dir, so the `Local State` one level up is never found and, on Windows, the DPAPI and ABE keys cannot be derived — `-p` effectively cannot decrypt anything there. The Chromium `Discover` now looks at what it was given: a directory holding `Preferences` is a profile, so its parent is the user data dir and only that profile is selected; a directory holding profile subdirectories is a user data dir, as before. Either way the keys resolve.
|
||||
- **Pointing at a Chromium profile directory.** The help text asks for the path `chrome://version` shows, which is a profile directory (`…/User Data/Default`). Today that directory becomes the whole user data dir, so the `Local State` one level up is never found and, on Windows, the DPAPI and ABE keys cannot be derived — `-p` effectively cannot decrypt anything there. The Chromium `Discover` now looks at what it was given: a directory holding `Preferences` but no `Local State` is a profile, so its parent is the user data dir and only that profile is selected; a directory holding profile subdirectories, or a flat layout with its own `Local State`, is a user data dir, as before. Either way the keys resolve.
|
||||
- **Firefox selects only the named profile.** Today the Firefox override takes the parent of the given directory as the Profiles root and then exports _every_ profile under it, not the one asked for. `Discover` now selects only the profile the path names. This narrows today's output for `-b firefox -p <profile>` and is called out as an expected diff in the parity suite ([RFC-011](011-testing-and-quality.md)).
|
||||
- **Safari says no.** `-b safari -p` is rejected in Validate with a one-line reason: Safari's data is spread across `~/Library` and a container, so a single profile directory cannot stand in for it. Today the flag is quietly accepted and has no effect.
|
||||
- **Safari keeps its meaning.** `-b safari -p` names a Safari directory to read instead of `~/Library/Safari`, as it always has: its parent stands in for `~/Library`, so the named profiles in the container beside it are found too, and passwords still come from the login keychain.
|
||||
|
||||
Selecting profiles by name across browsers is DEFERRED; if added, it gets its own flag rather than changing `-p`.
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ Each bug designed out by this rewrite gets a test that would have caught it, so
|
||||
- **`-p` with `-b all`**: a warning is logged and no user data dir is overridden.
|
||||
- **`-p` at a Chromium profile directory**: its parent becomes the user data dir, so `Local State` is captured and keys resolve.
|
||||
- **`-p` for Firefox**: only the named profile is exported, not every sibling under it.
|
||||
- **`-p` for Safari**: rejected in Validate with a reason.
|
||||
- **`-p` for Safari**: names the Safari directory, whose parent stands in for `~/Library`, as today.
|
||||
- **Keychain password precedence**: explicit flag > prompt > none.
|
||||
- **Temp snapshot cleanup**: a run that fails mid-way leaves no copied `Login Data` or `Cookies` behind.
|
||||
- **Discovery errors are not absence**: an unreadable user data dir (permission denied) is reported as an `error` result, distinct from one that simply isn't there (nothing). The home directory comes from `DiscoverOptions`, so a `t.TempDir()` stands in.
|
||||
|
||||
Reference in new issue
Block a user