Files
HackBrowserData/internal/browser/firefox/firefox_test.go
T
Roger c823d83e57 refactor(browser): give each base Sources and Extract (#714)
* refactor(browser): give each base Sources and Extract

browser.Input carried every base's secret, so no base said what it needs.
Each base now takes its own secret as a typed parameter, and app holds the
one switch that knows all three. Safari's files no longer need ../ paths.

* refactor(app): make execute the runner's export method

* docs: add a package map to CONTRIBUTING.md

* refactor(app): keep each base's secret on the runner

The bases interface had one real implementation and existed for the test
fake, so it held two of a run's three secrets. The runner holds them all,
and the run tests use real fixtures.

* refactor(chromium): pass data where a function was passed

DiscoverAt took a UserDataDir field by field, the Opera extension list was
a second function for one JSON key, and NeedsMasterKeys repeated by hand
which extractors decrypt.

* refactor(app): set both passwords after the flags are valid

The keychain password went in as a ValidateDump argument and the Firefox
one was assigned afterwards; cmd now sets both the same way.

* refactor: rename dumpKeysWith and CandidatePaths

buildKeyFile says what it returns, and DirRelativePaths says what its paths
are relative to. A failed browser's dir ID no longer comes from a cast.

* refactor(app): plan extractions without a plan struct

dirPlan and plannedExtraction existed to carry a profile and three lists.
An Extraction now holds its Profile, and planExtractions returns the lists.

* refactor(browser): rename profileAt and downloadsOf

profileAt returned a user data dir in two shapes, and downloadsOf returned
a function. Both bases now have dirFromProfilePath with one shape, and
Safari has newDownloadExtractor beside its other constructors.

* refactor: use one short name for a user data dir in app

Fields said UserDataDirID beside Dirs and DirFailure, and runDir did not
say what it runs. They are DirID and runExtractions; the type keeps its
full name.

* refactor(app): rename withData to dropEmptyProfiles

With reads as adding something, and the function removes profiles. hasData
loses a parameter that always held sourcesFor's result.

* refactor: rename five functions that misstate what they do

untilDone had no verb, canCreateIn asked a yes/no question but returned an
error, failAll only built results, sortKeyOf was the last xxxOf, and
checkProfilePath returned a value where its siblings return only an error.

* refactor: name forks as forks and drop the For lookups

The fork table was typed override while every variable said fork, and six
lookups were named for a preposition, not for what they return. The other
renames make one name mean one thing: extractors, dataSources, extractFile.

* refactor(browser): drop parameters Sources and Extract ignore

No interface makes the three bases share a signature, so the blank
parameters only hid that Chromium's sources vary by dir, Safari's by
profile, and that only Safari's extraction can be cancelled.

* refactor(browser): ask a base for one category's sources

Sources returned every category's files, so its name had no object and
each base carried a loop projecting its table. Keyed by category it is
the same lookup as Extract and NeedsMasterKeys.

* refactor: report a locked keychain as data, not a log line

Dump and DumpKeys return results for cmd to print, yet warned about the
keychain themselves, with the sentence passed in as an argument. Now cmd
says every sentence; warnIfLocked and printNothingFound take no message.

* refactor(cmd): rename printExported to printExportedFiles

Exported is an adjective; the function lists the files a run wrote.
2026-11-22 23:52:12 +08:00

175 lines
7.2 KiB
Go

package firefox
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/record"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
func testBrowser(userDataDirs ...string) browser.Browser {
platform := browser.Platform{UserDataDirPaths: userDataDirs}
return browser.Browser{Name: "firefox", DisplayName: "Firefox", Base: browser.Firefox, Darwin: platform, Linux: platform, Windows: platform}
}
func touch(t *testing.T, parts ...string) {
t.Helper()
path := filepath.Join(parts...)
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
require.NoError(t, os.WriteFile(path, []byte("{}"), 0o600))
}
func snapshotOf(t *testing.T, files map[string]string) snapshot.Snapshot {
t.Helper()
root := t.TempDir()
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, fixturePath, filepath.Base(relativePath))
}
return snapshot.Open(root).Snapshot("firefox")
}
func TestDiscover_ProfilesAreDirsWithDataFiles(t *testing.T) {
home := t.TempDir()
touch(t, home, "Profiles", "abcd1234.default-release", "places.sqlite")
touch(t, home, "Profiles", "wxyz5678.work", "logins.json")
touch(t, home, "Profiles", "k3y0nly0.default", "key4.db")
touch(t, home, "Profiles", "Crash Reports", "InstallTime20240101000000")
touch(t, home, "Profiles", "profiles.ini")
dirs, err := Discover(testBrowser("Profiles"), browser.DiscoverOptions{HomeDir: home})
require.NoError(t, err)
require.Len(t, dirs, 1)
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", RelativePath: "abcd1234.default-release"},
{Name: "wxyz5678.work", RelativePath: "wxyz5678.work"},
}, dirs[0].Profiles)
}
func TestDiscover_MissingUserDataDirYieldsNothing(t *testing.T) {
dirs, err := Discover(testBrowser("Profiles"), browser.DiscoverOptions{HomeDir: t.TempDir()})
require.NoError(t, err)
assert.Empty(t, dirs)
}
// 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, "Profiles", "abcd1234.default-release", "places.sqlite")
profiles := filepath.Join(home, "Profiles")
require.NoError(t, os.Chmod(profiles, 0o000))
defer func() { require.NoError(t, os.Chmod(profiles, 0o700)) }()
dirs, err := Discover(testBrowser("Profiles"), browser.DiscoverOptions{HomeDir: home})
require.Error(t, err)
assert.Empty(t, dirs)
}
// 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")
options := browser.DiscoverOptions{HomeDir: 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)
assert.Equal(t, []browser.Profile{{Name: "abcd1234.default-release", RelativePath: "abcd1234.default-release"}}, dirs[0].Profiles)
}
func TestDiscover_ProfilePathWithoutDataFindsNothing(t *testing.T) {
custom := t.TempDir()
touch(t, custom, "abcd1234.default-release", "key4.db")
options := browser.DiscoverOptions{HomeDir: 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) {
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", dataCategory) {
assert.NotNil(t, extractor.extract, dataCategory)
assert.NotEmpty(t, extractor.sources, dataCategory)
}
}
}
// TestPasswordExtractor_WithoutKeyStore exports empty secrets without key4.db; a legacy-cipher login once panicked.
func TestDecryptingExtractor_WithoutKeyStore(t *testing.T) {
encodedLogin := loginPBEBase64(t)
logins := createTestJSON(t, "logins.json", fmt.Sprintf(`{"logins": [{"hostname": "https://a.test",
"encryptedUsername": %q, "encryptedPassword": %q, "timeCreated": 1700000000000}]}`, encodedLogin, encodedLogin))
captured := profileP(snapshotOf(t, map[string]string{"p/logins.json": logins}))
var out testCollector
require.NoError(t, extractors[category.Password].extract(captured, "", &out))
got := collected[record.Login](t, &out)
require.Len(t, got, 1)
assert.Equal(t, "https://a.test", got[0].URL)
assert.Empty(t, got[0].Username)
assert.Empty(t, got[0].Password)
require.Len(t, out.fails, 3)
assert.ErrorIs(t, out.fails[0], fs.ErrNotExist)
}
// TestPasswordExtractor_NoLoginsNeverReadsTheKey leaves key4.db unread without logins, so an unreadable one is harmless.
func TestDecryptingExtractor_NoLoginsNeverReadsTheKey(t *testing.T) {
captured := profileP(snapshotOf(t, map[string]string{
"p/logins.json": createTestJSON(t, "logins.json", `{"logins": []}`),
"p/key4.db": createTestJSON(t, "key4.db", "not a database"),
}))
var out testCollector
require.NoError(t, extractors[category.Password].extract(captured, "", &out))
assert.Empty(t, out.records)
assert.Empty(t, out.fails)
}
// TestExtractors_EachProfileReadsItsOwnFiles reads one snapshot shared by every profile; each must get its own files.
func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) {
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{Browser: testBrowser()}
want := map[string]string{"a.default": "Home", "b.work": "Work"}
for _, profile := range []browser.Profile{{Name: "a.default", RelativePath: "a.default"}, {Name: "b.work", RelativePath: "b.work"}} {
var out testCollector
require.NoError(t, Extract(browser.NewProfileSnapshot(dir, profile, dirSnapshot), "", category.History, &out))
got := collected[record.History](t, &out)
require.Len(t, got, 1, profile.Name)
assert.Equal(t, want[profile.Name], got[0].Title, profile.Name)
}
}
func profileP(dirSnapshot snapshot.Snapshot) browser.ProfileSnapshot {
return browser.NewProfileSnapshot(browser.UserDataDir{Browser: testBrowser()}, browser.Profile{Name: "p", RelativePath: "p"}, dirSnapshot)
}