Files
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

144 lines
6.1 KiB
Go

package app
import (
"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/snapshot"
)
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 lookup(t *testing.T, name string) browser.Browser {
t.Helper()
namedBrowser, ok := browser.Lookup(name)
require.True(t, ok, name)
return namedBrowser
}
func TestPlanExtractions(t *testing.T) {
path := t.TempDir()
touch(t, path, "Local State")
touch(t, path, "Default", "Login Data")
touch(t, path, "Default", "Network", "Cookies")
touch(t, path, "Default", "History")
touch(t, path, "Profile 1", "History")
first := browser.Profile{Name: "Default", RelativePath: "Default"}
second := browser.Profile{Name: "Profile 1", RelativePath: "Profile 1"}
dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{first, second}}
categories := []category.Category{category.Password, category.Cookie, category.History, category.Download, category.CreditCard}
extractions, files, skipped := planExtractions(dir, categories)
file := func(relativePath string) snapshot.File {
return snapshot.File{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: relativePath}
}
extraction := func(profile browser.Profile, dataCategory category.Category) Extraction {
return Extraction{DirID: "chrome", Profile: profile, Category: dataCategory}
}
absent := func(profile browser.Profile, dataCategory category.Category) Result {
return Result{Extraction: extraction(profile, dataCategory), Outcome: OutcomeAbsent}
}
assert.Equal(t, []Extraction{
extraction(first, category.Password), extraction(first, category.Cookie),
extraction(first, category.History), extraction(first, category.Download),
extraction(second, category.History), extraction(second, category.Download),
}, extractions)
assert.Equal(t, []snapshot.File{
file("Default/Login Data"), file("Local State"), file("Default/Network/Cookies"), file("Default/History"),
file("Profile 1/History"),
}, files, "Local State and History are copied once, however many extractions read them")
assert.Equal(t, []Result{
absent(first, category.CreditCard),
// Local State alone does not make a profile's passwords present.
absent(second, category.Password),
absent(second, category.Cookie),
absent(second, category.CreditCard),
}, skipped)
}
func TestPlanExtractions_PicksTheFirstCandidateOnDisk(t *testing.T) {
path := t.TempDir()
touch(t, path, "Default", "Cookies")
dir := browser.UserDataDir{ID: "chrome", Browser: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", RelativePath: "Default"}}}
_, files, _ := planExtractions(dir, []category.Category{category.Cookie})
assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Cookies"}}, files)
touch(t, path, "Default", "Network", "Cookies")
_, files, _ = planExtractions(dir, []category.Category{category.Cookie})
assert.Equal(t, []snapshot.File{{UserDataDirID: "chrome", UserDataDirPath: path, RelativePath: "Default/Network/Cookies"}}, files,
"a leftover legacy Cookies never wins")
}
func TestPlanExtractions_FlatLayoutProfile(t *testing.T) {
path := t.TempDir()
touch(t, path, "History")
profile := browser.Profile{Name: "Opera Stable"}
dir := browser.UserDataDir{ID: "opera", Browser: lookup(t, "opera"), Path: path, Profiles: []browser.Profile{profile}}
extractions, files, _ := planExtractions(dir, []category.Category{category.History})
assert.Equal(t, []snapshot.File{{UserDataDirID: "opera", UserDataDirPath: path, RelativePath: "History"}}, files)
assert.Equal(t, []Extraction{{DirID: "opera", Profile: profile, Category: category.History}}, extractions)
}
// TestPlanExtractions_UnsupportedCategory covers Firefox's credit cards, which it keeps nowhere HBD reads.
func TestPlanExtractions_UnsupportedCategory(t *testing.T) {
profile := browser.Profile{Name: "a.default", RelativePath: "a.default"}
dir := browser.UserDataDir{ID: "firefox", Browser: lookup(t, "firefox"), Path: t.TempDir(), Profiles: []browser.Profile{profile}}
extractions, _, skipped := planExtractions(dir, []category.Category{category.CreditCard})
unsupported := Extraction{DirID: "firefox", Profile: profile, Category: category.CreditCard}
assert.Equal(t, []Result{{Extraction: unsupported, Outcome: OutcomeUnsupported}}, skipped)
assert.Empty(t, extractions)
}
// TestPlanExtractions_CategoryWithoutSourcesRuns covers Safari's passwords: read from the keychain, they are never absent.
func TestPlanExtractions_CategoryWithoutSourcesRuns(t *testing.T) {
profile := browser.Profile{Name: "default", RelativePath: "Safari"}
dir := browser.UserDataDir{ID: "safari", Browser: lookup(t, "safari"), Path: t.TempDir(), Profiles: []browser.Profile{profile}}
extractions, files, skipped := planExtractions(dir, []category.Category{category.Password})
assert.Equal(t, []Extraction{{DirID: "safari", Profile: profile, Category: category.Password}}, extractions)
assert.Empty(t, files)
assert.Empty(t, skipped)
}
// lock makes dir unsearchable until the test ends, so a Stat of anything under it fails with permission denied.
func lock(t *testing.T, dir string) {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("mode bits do not restrict Stat on Windows")
}
if os.Geteuid() == 0 {
t.Skip("root ignores mode bits")
}
require.NoError(t, os.Chmod(dir, 0))
t.Cleanup(func() { assert.NoError(t, os.Chmod(dir, 0o700)) })
}
func TestPlanExtractions_UnreadableFileIsAnError(t *testing.T) {
dir := chromeDir(t, "Default")
lock(t, filepath.Join(dir.Path, "Default"))
extractions, files, skipped := planExtractions(dir, []category.Category{category.History})
require.Len(t, skipped, 1)
assert.Equal(t, OutcomeError, skipped[0].Outcome)
require.ErrorIs(t, skipped[0].Err, fs.ErrPermission)
assert.Empty(t, extractions)
assert.Empty(t, files)
}