mirror of
https://github.com/moonD4rk/HackBrowserData.git
synced 2026-12-04 05:43:27 +01:00
refactor: run Chromium through the internal/app pipeline (#656)
Validate, Discover, NewPlan, Execute, and Report run beside today's path: one snapshot per user data dir, each dir's keys retrieved once on first use, every record stamped by the collector. On the Chromium fixtures it writes the extract goldens byte for byte; the CLI switches over later.
This commit is contained in:
1 parent
322c41d187
commit
2b70e4ad65
15 files changed
+1122
-1
No files matched your search
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/app"
|
||||
ibrowser "github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
)
|
||||
|
||||
// Until the switch-over the pipeline runs beside today's extract path: on the same fixtures it must write the same
|
||||
// goldens byte for byte.
|
||||
func TestPipelineGolden(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
keys := make(map[ibrowser.DirID]masterkey.Set)
|
||||
for _, inst := range chromiumFixtureInstalls {
|
||||
def, ok := ibrowser.Lookup(inst.key)
|
||||
require.True(t, ok, inst.key)
|
||||
require.Equal(t, inst.name, def.Name, "records are stamped with the table's display name")
|
||||
chromiumFixtureUserData(t, filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0])), inst.key)
|
||||
keys[ibrowser.DirID(inst.key)] = chromiumFixtureKeys
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
format string
|
||||
golden string
|
||||
jsonFallback bool
|
||||
}{
|
||||
{format: "csv", golden: "extract-csv.golden"},
|
||||
{format: "json", golden: "extract-json.golden"},
|
||||
{format: "cookie-editor", golden: "extract-cookie-editor.golden", jsonFallback: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.format, func(t *testing.T) {
|
||||
out := pipelineGoldenRun(t, home, keys, tt.format)
|
||||
got := bundleDir(t, out)
|
||||
if tt.jsonFallback {
|
||||
assertJSONFallback(t, out, pipelineGoldenRun(t, home, keys, "json"))
|
||||
got = bundleFiles(t, out, "cookie.json")
|
||||
}
|
||||
assertGolden(t, tt.golden, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func pipelineGoldenRun(t *testing.T, home string, keys map[ibrowser.DirID]masterkey.Set, format string) string {
|
||||
t.Helper()
|
||||
out := t.TempDir()
|
||||
req, err := app.Validate(app.Flags{Browser: "all", Categories: "all", Format: format, Dir: out})
|
||||
require.NoError(t, err)
|
||||
req.Home, req.Keys = home, keys
|
||||
|
||||
plan := app.NewPlan(app.Discover(req), req)
|
||||
_, err = app.Execute(context.Background(), plan, req)
|
||||
require.NoError(t, err)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// Package app runs the pipeline: Validate turns flags into a Request, Discover finds the user data dirs, NewPlan crosses
|
||||
// them with the requested categories, Execute captures, extracts, and exports one user data dir at a time, and Report
|
||||
// prints what every extraction got.
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/export"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
)
|
||||
|
||||
// Flags are a run's command-line values as cobra parsed them.
|
||||
type Flags struct {
|
||||
Browser string
|
||||
Categories string
|
||||
Format string
|
||||
Dir string
|
||||
ProfilePath string
|
||||
KeychainPassword string
|
||||
}
|
||||
|
||||
// Request is a validated run.
|
||||
type Request struct {
|
||||
Browser string // "all" or one Def.ID
|
||||
Categories []category.Category
|
||||
Format export.Format
|
||||
Dir string
|
||||
ProfilePath string
|
||||
Home string
|
||||
|
||||
// KeychainPassword yields the macOS login password when the login keychain is first opened; "" leaves it locked.
|
||||
KeychainPassword func(ctx context.Context) (string, error)
|
||||
// Keys are a dump's keys by user data dir; nil retrieves every dir's keys from this machine.
|
||||
Keys map[browser.DirID]masterkey.Set
|
||||
}
|
||||
|
||||
// Validate checks the flags and resolves the home directory, so nothing later reads the environment.
|
||||
func Validate(f Flags) (Request, error) {
|
||||
categories, err := parseCategories(f.Categories)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
format, err := export.ParseFormat(f.Format)
|
||||
if err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return Request{}, fmt.Errorf("home directory: %w", err)
|
||||
}
|
||||
name := strings.ToLower(strings.TrimSpace(f.Browser))
|
||||
if name == "" {
|
||||
name = "all"
|
||||
}
|
||||
password := f.KeychainPassword
|
||||
return Request{
|
||||
Browser: name,
|
||||
Categories: categories,
|
||||
Format: format,
|
||||
Dir: f.Dir,
|
||||
ProfilePath: f.ProfilePath,
|
||||
Home: home,
|
||||
KeychainPassword: func(context.Context) (string, error) { return password, nil },
|
||||
}, nil
|
||||
}
|
||||
|
||||
// parseCategories reads a comma-separated -c value; a repeated category is kept once, or its records would be
|
||||
// exported twice.
|
||||
func parseCategories(s string) ([]category.Category, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if strings.EqualFold(s, "all") {
|
||||
return category.All(), nil
|
||||
}
|
||||
var categories []category.Category
|
||||
seen := make(map[category.Category]bool)
|
||||
for _, name := range strings.Split(s, ",") {
|
||||
name = strings.TrimSpace(strings.ToLower(name))
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
c, err := category.Parse(name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w, available: all|%s", err, categoryNames())
|
||||
}
|
||||
if !seen[c] {
|
||||
seen[c] = true
|
||||
categories = append(categories, c)
|
||||
}
|
||||
}
|
||||
if len(categories) == 0 {
|
||||
return nil, fmt.Errorf("no categories specified")
|
||||
}
|
||||
return categories, nil
|
||||
}
|
||||
|
||||
func categoryNames() string {
|
||||
all := category.All()
|
||||
names := make([]string, len(all))
|
||||
for i, c := range all {
|
||||
names[i] = c.String()
|
||||
}
|
||||
return strings.Join(names, ",")
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/export"
|
||||
)
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
req, err := Validate(Flags{Browser: " Chrome ", Categories: "cookie, password,cookie", Format: "csv", Dir: "out", KeychainPassword: "pw"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "chrome", req.Browser)
|
||||
assert.Equal(t, []category.Category{category.Cookie, category.Password}, req.Categories, "a repeated category runs once")
|
||||
assert.Equal(t, export.CSV, req.Format)
|
||||
assert.Equal(t, "out", req.Dir)
|
||||
assert.NotEmpty(t, req.Home)
|
||||
password, err := req.KeychainPassword(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "pw", password)
|
||||
|
||||
req, err = Validate(Flags{Categories: "all", Format: "json"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "all", req.Browser)
|
||||
assert.Equal(t, category.All(), req.Categories)
|
||||
}
|
||||
|
||||
func TestValidate_RejectsBadInput(t *testing.T) {
|
||||
for name, f := range map[string]Flags{
|
||||
"unknown category": {Categories: "cookie,bogus", Format: "json"},
|
||||
"no category": {Categories: " , ", Format: "json"},
|
||||
"unknown format": {Categories: "all", Format: "xml"},
|
||||
} {
|
||||
_, err := Validate(f)
|
||||
assert.Error(t, err, name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/chromium"
|
||||
)
|
||||
|
||||
// Discovery is what Discover found: the user data dirs, and an error result for each browser whose data could not be
|
||||
// read, which is reported rather than mistaken for absence.
|
||||
type Discovery struct {
|
||||
Dirs []browser.UserDataDir
|
||||
Failed []Result
|
||||
}
|
||||
|
||||
// Discover looks for the requested browsers on this machine. -p applies only when one browser is named.
|
||||
func Discover(req Request) Discovery {
|
||||
var d Discovery
|
||||
for _, def := range browser.Supported() {
|
||||
if req.Browser != "all" && def.ID != req.Browser {
|
||||
continue
|
||||
}
|
||||
opts := browser.DiscoverOptions{Home: req.Home}
|
||||
if req.Browser != "all" {
|
||||
opts.ProfilePath = req.ProfilePath
|
||||
}
|
||||
dirs, err := discover(def, opts)
|
||||
d.Dirs = append(d.Dirs, dirs...)
|
||||
if err != nil {
|
||||
d.Failed = append(d.Failed, dirFailure(browser.DirID(def.ID), err))
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// discover and extractorsOf dispatch on the base here, because the base packages import browser and so browser cannot
|
||||
// call them.
|
||||
func discover(def browser.Def, opts browser.DiscoverOptions) ([]browser.UserDataDir, error) {
|
||||
switch def.Base {
|
||||
case browser.Chromium:
|
||||
return chromium.Discover(def, opts)
|
||||
default:
|
||||
return nil, nil // Firefox and Safari are not on the pipeline yet
|
||||
}
|
||||
}
|
||||
|
||||
func extractorsOf(dir browser.UserDataDir, p browser.Profile) browser.Extractors {
|
||||
switch dir.Def.Base {
|
||||
case browser.Chromium:
|
||||
return chromium.Extractors(dir, p)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
)
|
||||
|
||||
// installAt creates a profile where this OS's table expects the browser's user data dir under home.
|
||||
func installAt(t *testing.T, home, id string) string {
|
||||
t.Helper()
|
||||
def := lookup(t, id)
|
||||
require.NotEmpty(t, def.Platform().UserDataDirs, id)
|
||||
path := filepath.Join(home, filepath.FromSlash(def.Platform().UserDataDirs[0]))
|
||||
touch(t, path, "Default", "Preferences")
|
||||
return path
|
||||
}
|
||||
|
||||
func dirIDs(d Discovery) []browser.DirID {
|
||||
var ids []browser.DirID
|
||||
for _, dir := range d.Dirs {
|
||||
ids = append(ids, dir.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func TestDiscover(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
installAt(t, home, "edge")
|
||||
installAt(t, home, "chrome")
|
||||
|
||||
d := Discover(Request{Browser: "all", Home: home})
|
||||
assert.Equal(t, []browser.DirID{"chrome", "edge"}, dirIDs(d), "table order, which is output order")
|
||||
assert.Empty(t, d.Failed)
|
||||
|
||||
d = Discover(Request{Browser: "edge", Home: home})
|
||||
assert.Equal(t, []browser.DirID{"edge"}, dirIDs(d))
|
||||
}
|
||||
|
||||
func TestDiscover_ProfilePathNeedsOneBrowser(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
installAt(t, home, "chrome")
|
||||
custom := t.TempDir()
|
||||
touch(t, custom, "Default", "Preferences")
|
||||
|
||||
d := Discover(Request{Browser: "chrome", Home: home, ProfilePath: custom})
|
||||
require.Len(t, d.Dirs, 1)
|
||||
assert.Equal(t, custom, d.Dirs[0].Path)
|
||||
|
||||
d = Discover(Request{Browser: "all", Home: home, ProfilePath: custom})
|
||||
require.Len(t, d.Dirs, 1)
|
||||
assert.NotEqual(t, custom, d.Dirs[0].Path, "-p is ignored without a specific browser")
|
||||
}
|
||||
|
||||
func TestDiscover_UnreadableDirIsReported(t *testing.T) {
|
||||
if runtime.GOOS == "windows" || os.Geteuid() == 0 {
|
||||
t.Skip("directory permissions do not deny reads here")
|
||||
}
|
||||
home := t.TempDir()
|
||||
path := installAt(t, home, "chrome")
|
||||
require.NoError(t, os.Chmod(path, 0o000))
|
||||
defer func() { require.NoError(t, os.Chmod(path, 0o700)) }()
|
||||
|
||||
d := Discover(Request{Browser: "all", Home: home})
|
||||
assert.Empty(t, d.Dirs)
|
||||
require.Len(t, d.Failed, 1)
|
||||
assert.Equal(t, Extraction{DirID: "chrome"}, d.Failed[0].Extraction)
|
||||
assert.Equal(t, OutcomeError, d.Failed[0].Outcome)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sync"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser/chromium"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/export"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/log"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
// keySource retrieves one user data dir's Chromium keys, reading what it needs from the dir's snapshot.
|
||||
type keySource func(ctx context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error)
|
||||
|
||||
// Execute runs Capture, Extract, and Export one user data dir at a time, so at most one dir's copies are on disk. Its
|
||||
// error means the run could not finish, such as a failed output write; every other failure is a Result.
|
||||
func Execute(ctx context.Context, p Plan, req Request) (Summary, error) {
|
||||
keys := dumpKeys(req.Keys)
|
||||
if req.Keys == nil {
|
||||
keys = machineKeys(loginKeychain(req))
|
||||
}
|
||||
return execute(ctx, p, req, extractorsOf, keys)
|
||||
}
|
||||
|
||||
func execute(ctx context.Context, p Plan, req Request, extractors extractorsFunc, keys keySource) (Summary, error) {
|
||||
w, err := export.NewWriter(req.Dir, req.Format)
|
||||
if err != nil {
|
||||
return Summary{}, err
|
||||
}
|
||||
results := append([]Result(nil), p.Skipped...)
|
||||
for _, dir := range p.Dirs {
|
||||
dirResults, err := executeDir(ctx, dir, p, w, extractors, keys)
|
||||
results = append(results, dirResults...)
|
||||
if err != nil {
|
||||
return Summary{Results: results}, errors.Join(err, w.Close())
|
||||
}
|
||||
}
|
||||
return Summary{Results: results}, w.Close()
|
||||
}
|
||||
|
||||
func executeDir(ctx context.Context, dir browser.UserDataDir, p Plan, w *export.Writer, extractors extractorsFunc,
|
||||
keys keySource,
|
||||
) ([]Result, error) {
|
||||
extractions := extractionsOf(p, dir.ID)
|
||||
if len(extractions) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
log.Infof("Extracting %s...", dir.Def.Name)
|
||||
|
||||
d, err := snapshot.Temp()
|
||||
if err != nil {
|
||||
return failAll(extractions, err), nil
|
||||
}
|
||||
defer closeSnapshot(d)
|
||||
if err := d.Capture(ctx, filesOf(p, dir.ID)); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, err
|
||||
}
|
||||
return failAll(extractions, err), nil
|
||||
}
|
||||
snap := d.Snapshot(string(dir.ID))
|
||||
|
||||
var (
|
||||
dk *dirKeys
|
||||
masterKeys func(context.Context) masterkey.Set
|
||||
)
|
||||
if dir.Def.Base == browser.Chromium {
|
||||
dk = &dirKeys{retrieve: func(ctx context.Context) (masterkey.Set, error) { return keys(ctx, dir, snap) }}
|
||||
masterKeys = dk.get
|
||||
}
|
||||
|
||||
profiles := make(map[string]browser.Profile, len(dir.Profiles))
|
||||
byProfile := make(map[string]browser.Extractors, len(dir.Profiles))
|
||||
for _, prof := range dir.Profiles {
|
||||
profiles[prof.Name] = prof
|
||||
byProfile[prof.Name] = extractors(dir, prof)
|
||||
}
|
||||
|
||||
results := make([]Result, 0, len(extractions)+1)
|
||||
for _, e := range extractions {
|
||||
x, ok := byProfile[e.Profile][e.Category]
|
||||
if !ok || x.Extract == nil {
|
||||
results = append(results, Result{Extraction: e, Outcome: OutcomeUnsupported})
|
||||
continue
|
||||
}
|
||||
prof := profiles[e.Profile]
|
||||
c := &collector{browser: dir.Def.Name, profile: prof.Name}
|
||||
err := x.Extract(ctx, browser.NewProfileSnapshot(snap, prof, masterKeys), c)
|
||||
// Records emitted before an extraction failed are kept, as they always were.
|
||||
if writeErr := w.Write(e.Category, c.records); writeErr != nil {
|
||||
return results, writeErr
|
||||
}
|
||||
results = append(results, c.result(e, err))
|
||||
}
|
||||
if dk != nil && dk.err != nil {
|
||||
results = append(results, dirFailure(dir.ID, fmt.Errorf("master key retrieval: %w", dk.err)))
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func extractionsOf(p Plan, id browser.DirID) []Extraction {
|
||||
var out []Extraction
|
||||
for _, e := range p.Extractions {
|
||||
if e.DirID == id {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func filesOf(p Plan, id browser.DirID) []snapshot.File {
|
||||
var out []snapshot.File
|
||||
for _, f := range p.Files {
|
||||
if f.DirID == string(id) {
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func failAll(extractions []Extraction, err error) []Result {
|
||||
results := make([]Result, len(extractions))
|
||||
for i, e := range extractions {
|
||||
results[i] = Result{Extraction: e, Outcome: OutcomeError, Err: err}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
func closeSnapshot(d *snapshot.Dir) {
|
||||
if err := d.Close(); err != nil {
|
||||
log.Warnf("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// collector stamps every record with its browser and profile, and keeps one extraction's output for the writer.
|
||||
type collector struct {
|
||||
browser, profile string
|
||||
records []record.Record
|
||||
failed int
|
||||
firstFail error
|
||||
}
|
||||
|
||||
func (c *collector) Add(r record.Record) {
|
||||
record.Stamp(r, c.browser, c.profile)
|
||||
c.records = append(c.records, r)
|
||||
}
|
||||
|
||||
func (c *collector) Fail(err error) {
|
||||
c.failed++
|
||||
if c.firstFail == nil {
|
||||
c.firstFail = err
|
||||
}
|
||||
log.Debugf("%s/%s: %v", c.browser, c.profile, err)
|
||||
}
|
||||
|
||||
// result applies the outcome rules: a source that vanished after planning is absent, and problems with no record to
|
||||
// show for them are an error, while problems beside records are partial.
|
||||
func (c *collector) result(e Extraction, err error) Result {
|
||||
r := Result{Extraction: e, Count: len(c.records), Failed: c.failed}
|
||||
switch {
|
||||
case err != nil && errors.Is(err, fs.ErrNotExist) && r.Count == 0:
|
||||
r.Outcome = OutcomeAbsent
|
||||
case err != nil:
|
||||
r.Outcome, r.Err = OutcomeError, err
|
||||
case r.Failed > 0 && r.Count == 0:
|
||||
r.Outcome, r.Err = OutcomeError, c.firstFail
|
||||
case r.Failed > 0:
|
||||
r.Outcome = OutcomePartial
|
||||
default:
|
||||
r.Outcome = OutcomeOK
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// dirKeys retrieves a user data dir's keys on first use and keeps them, and the error, for the dir's other profiles.
|
||||
// Go 1.20 has no sync.OnceValues.
|
||||
type dirKeys struct {
|
||||
once sync.Once
|
||||
retrieve func(context.Context) (masterkey.Set, error)
|
||||
keys masterkey.Set
|
||||
err error
|
||||
}
|
||||
|
||||
func (k *dirKeys) get(ctx context.Context) masterkey.Set {
|
||||
k.once.Do(func() { k.keys, k.err = k.retrieve(ctx) })
|
||||
return k.keys
|
||||
}
|
||||
|
||||
// machineKeys asks this machine's secret stores; on macOS that includes the run's login keychain.
|
||||
func machineKeys(kc masterkey.LoginKeychain) keySource {
|
||||
return func(ctx context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error) {
|
||||
loc, err := chromium.KeyLocator(dir, snap)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
loc.Keychain = kc
|
||||
return masterkey.RetrieveAll(ctx, loc)
|
||||
}
|
||||
}
|
||||
|
||||
func dumpKeys(keys map[browser.DirID]masterkey.Set) keySource {
|
||||
return func(_ context.Context, dir browser.UserDataDir, _ snapshot.Snapshot) (masterkey.Set, error) {
|
||||
return keys[dir.ID], nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"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/masterkey"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/record"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
var history = browser.Source{Paths: []string{"History"}}
|
||||
|
||||
type extractFunc func(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error
|
||||
|
||||
// fakeBase reads History for every category, so a test needs one fixture file per profile.
|
||||
func fakeBase(fns map[category.Category]extractFunc) extractorsFunc {
|
||||
return func(browser.UserDataDir, browser.Profile) browser.Extractors {
|
||||
ex := make(browser.Extractors, len(fns))
|
||||
for c, fn := range fns {
|
||||
ex[c] = browser.Extractor{Sources: []browser.Source{history}, Extract: fn}
|
||||
}
|
||||
return ex
|
||||
}
|
||||
}
|
||||
|
||||
func noKeys(t *testing.T) keySource {
|
||||
return func(context.Context, browser.UserDataDir, snapshot.Snapshot) (masterkey.Set, error) {
|
||||
t.Error("keys were retrieved")
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
func chromeDir(t *testing.T, id browser.DirID, profiles ...string) browser.UserDataDir {
|
||||
t.Helper()
|
||||
dir := browser.UserDataDir{ID: id, Def: lookup(t, "chrome"), Path: t.TempDir()}
|
||||
for _, name := range profiles {
|
||||
touch(t, dir.Path, name, "History")
|
||||
dir.Profiles = append(dir.Profiles, browser.Profile{Name: name, Dir: name})
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func run(t *testing.T, base extractorsFunc, keys keySource, categories []category.Category, dirs ...browser.UserDataDir) (Summary, string) {
|
||||
t.Helper()
|
||||
req := Request{Categories: categories, Dir: t.TempDir()}
|
||||
summary, err := execute(context.Background(), newPlan(Discovery{Dirs: dirs}, req, base), req, base, keys)
|
||||
require.NoError(t, err)
|
||||
return summary, req.Dir
|
||||
}
|
||||
|
||||
func outcomes(s Summary) map[category.Category]Result {
|
||||
out := make(map[category.Category]Result)
|
||||
for _, r := range s.Results {
|
||||
out[r.Category] = r
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestExecute_Outcomes(t *testing.T) {
|
||||
cookie := func(name string) *record.Cookie { return &record.Cookie{Name: name} }
|
||||
base := fakeBase(map[category.Category]extractFunc{
|
||||
category.Cookie: func(_ context.Context, _ browser.ProfileSnapshot, out browser.Collector) error {
|
||||
out.Add(cookie("a"))
|
||||
out.Add(cookie("b"))
|
||||
out.Fail(errors.New("value not decrypted"))
|
||||
return nil
|
||||
},
|
||||
category.Password: func(_ context.Context, _ browser.ProfileSnapshot, out browser.Collector) error {
|
||||
out.Fail(errors.New("password not decrypted"))
|
||||
return nil
|
||||
},
|
||||
category.History: func(context.Context, browser.ProfileSnapshot, browser.Collector) error { return nil },
|
||||
category.Bookmark: func(context.Context, browser.ProfileSnapshot, browser.Collector) error {
|
||||
return errors.New("corrupt")
|
||||
},
|
||||
category.Download: func(context.Context, browser.ProfileSnapshot, browser.Collector) error {
|
||||
return fmt.Errorf("History: %w", fs.ErrNotExist)
|
||||
},
|
||||
category.Extension: func(_ context.Context, _ browser.ProfileSnapshot, out browser.Collector) error {
|
||||
out.Add(&record.Extension{Name: "kept"})
|
||||
return errors.New("truncated")
|
||||
},
|
||||
})
|
||||
categories := []category.Category{
|
||||
category.Cookie, category.Password, category.History, category.Bookmark, category.Download, category.Extension,
|
||||
}
|
||||
summary, out := run(t, base, noKeys(t), categories, chromeDir(t, "chrome", "Default"))
|
||||
|
||||
got := outcomes(summary)
|
||||
assert.Equal(t, OutcomePartial, got[category.Cookie].Outcome)
|
||||
assert.Equal(t, 2, got[category.Cookie].Count)
|
||||
assert.Equal(t, 1, got[category.Cookie].Failed)
|
||||
assert.Equal(t, OutcomeError, got[category.Password].Outcome, "problems and no record")
|
||||
require.EqualError(t, got[category.Password].Err, "password not decrypted")
|
||||
assert.Equal(t, OutcomeOK, got[category.History].Outcome, "an empty source is ok, not absent")
|
||||
assert.Equal(t, OutcomeError, got[category.Bookmark].Outcome)
|
||||
assert.Equal(t, OutcomeAbsent, got[category.Download].Outcome, "a source that vanished after planning")
|
||||
assert.Equal(t, OutcomeError, got[category.Extension].Outcome)
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(out, "extension.json"))
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(data), `"kept"`, "records emitted before the error are exported")
|
||||
data, err = os.ReadFile(filepath.Join(out, "cookie.json"))
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(data), `"browser": "Chrome"`, "the collector stamps the browser's display name")
|
||||
assert.Contains(t, string(data), `"profile": "Default"`)
|
||||
}
|
||||
|
||||
func TestExecute_KeysAreRetrievedOncePerUserDataDir(t *testing.T) {
|
||||
cookie := func(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error {
|
||||
out.Add(&record.Cookie{Value: string(ps.MasterKeys(ctx)[masterkey.V10])})
|
||||
return nil
|
||||
}
|
||||
login := func(ctx context.Context, ps browser.ProfileSnapshot, out browser.Collector) error {
|
||||
out.Add(&record.Login{Password: string(ps.MasterKeys(ctx)[masterkey.V10])})
|
||||
return nil
|
||||
}
|
||||
calls := 0
|
||||
keys := func(_ context.Context, dir browser.UserDataDir, snap snapshot.Snapshot) (masterkey.Set, error) {
|
||||
calls++
|
||||
_, err := snap.Path("Default/History")
|
||||
require.NoError(t, err, "keys are read from the dir's own snapshot")
|
||||
return masterkey.Set{masterkey.V10: []byte(dir.ID)}, errors.New("v20: no ABE")
|
||||
}
|
||||
base := fakeBase(map[category.Category]extractFunc{category.Cookie: cookie, category.Password: login})
|
||||
categories := []category.Category{category.Cookie, category.Password}
|
||||
|
||||
summary, _ := run(t, base, keys, categories, chromeDir(t, "chrome", "Default", "Profile 1"))
|
||||
|
||||
assert.Equal(t, 1, calls)
|
||||
last := summary.Results[len(summary.Results)-1]
|
||||
assert.Equal(t, Extraction{DirID: "chrome"}, last.Extraction, "a retrieval error is reported once, for the dir")
|
||||
assert.Equal(t, OutcomeError, last.Outcome)
|
||||
require.ErrorContains(t, last.Err, "v20: no ABE")
|
||||
assert.Len(t, summary.Results, 5)
|
||||
}
|
||||
|
||||
// A run that only asks for data without secrets never retrieves a key, so it never prompts on macOS.
|
||||
func TestExecute_HistoryNeverRetrievesKeys(t *testing.T) {
|
||||
path := t.TempDir()
|
||||
touch(t, path, "Local State")
|
||||
touch(t, path, "Default", "History")
|
||||
touch(t, path, "Default", "Network", "Cookies")
|
||||
dir := browser.UserDataDir{ID: "chrome", Def: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}}
|
||||
|
||||
run(t, extractorsOf, noKeys(t), []category.Category{category.History, category.Download}, dir)
|
||||
|
||||
calls := 0
|
||||
counting := func(context.Context, browser.UserDataDir, snapshot.Snapshot) (masterkey.Set, error) {
|
||||
calls++
|
||||
return nil, nil
|
||||
}
|
||||
run(t, extractorsOf, counting, []category.Category{category.Cookie, category.History}, dir)
|
||||
assert.Equal(t, 1, calls)
|
||||
}
|
||||
|
||||
// At most one user data dir's copies are on disk: a dir's snapshot is removed before the next dir is captured.
|
||||
func TestExecute_RemovesEachSnapshotBeforeTheNextDir(t *testing.T) {
|
||||
var captured []string
|
||||
base := fakeBase(map[category.Category]extractFunc{
|
||||
category.History: func(_ context.Context, ps browser.ProfileSnapshot, _ browser.Collector) error {
|
||||
for _, earlier := range captured {
|
||||
_, err := os.Stat(earlier)
|
||||
require.ErrorIs(t, err, fs.ErrNotExist, "an earlier dir's copy is still on disk")
|
||||
}
|
||||
path, err := ps.Path(history)
|
||||
require.NoError(t, err)
|
||||
captured = append(captured, path)
|
||||
return nil
|
||||
},
|
||||
})
|
||||
run(t, base, noKeys(t), []category.Category{category.History}, chromeDir(t, "chrome", "Default"), chromeDir(t, "chrome-2", "Default"))
|
||||
|
||||
require.Len(t, captured, 2)
|
||||
for _, path := range captured {
|
||||
_, err := os.Stat(path)
|
||||
assert.ErrorIs(t, err, fs.ErrNotExist)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecute_OutputFailureStopsTheRunAndLeavesNoCopies(t *testing.T) {
|
||||
if runtime.GOOS == "windows" || os.Geteuid() == 0 {
|
||||
t.Skip("directory permissions do not deny writes here")
|
||||
}
|
||||
var copied string
|
||||
base := fakeBase(map[category.Category]extractFunc{
|
||||
category.History: func(_ context.Context, ps browser.ProfileSnapshot, out browser.Collector) error {
|
||||
copied, _ = ps.Path(history)
|
||||
out.Add(&record.History{URL: "https://example.com"})
|
||||
return nil
|
||||
},
|
||||
})
|
||||
req := Request{Categories: []category.Category{category.History}, Dir: t.TempDir()}
|
||||
require.NoError(t, os.Chmod(req.Dir, 0o500))
|
||||
defer func() { require.NoError(t, os.Chmod(req.Dir, 0o700)) }()
|
||||
|
||||
plan := newPlan(Discovery{Dirs: []browser.UserDataDir{chromeDir(t, "chrome", "Default")}}, req, base)
|
||||
_, err := execute(context.Background(), plan, req, base, noKeys(t))
|
||||
require.Error(t, err)
|
||||
require.NotEmpty(t, copied)
|
||||
_, statErr := os.Stat(copied)
|
||||
assert.ErrorIs(t, statErr, fs.ErrNotExist)
|
||||
}
|
||||
|
||||
func TestExecute_DumpKeys(t *testing.T) {
|
||||
want := masterkey.Set{masterkey.V10: []byte("dumped")}
|
||||
keys := dumpKeys(map[browser.DirID]masterkey.Set{"chrome": want})
|
||||
got, err := keys(context.Background(), browser.UserDataDir{ID: "chrome"}, snapshot.Snapshot{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, got)
|
||||
|
||||
got, err = keys(context.Background(), browser.UserDataDir{ID: "edge"}, snapshot.Snapshot{})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, got, "a dump without the dir's keys decrypts nothing")
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//go:build darwin
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/keychain"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
)
|
||||
|
||||
// loginKeychain builds the run's one login keychain without opening it, so a run that never decrypts never prompts.
|
||||
func loginKeychain(req Request) masterkey.LoginKeychain {
|
||||
password := keychain.PasswordFunc(req.KeychainPassword)
|
||||
if password == nil {
|
||||
password = func(context.Context) (string, error) { return "", nil }
|
||||
}
|
||||
return keychain.New(filepath.Join(req.Home, "Library", "Keychains", "login.keychain-db"), password)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !darwin
|
||||
|
||||
package app
|
||||
|
||||
import "github.com/moond4rk/hackbrowserdata/internal/masterkey"
|
||||
|
||||
func loginKeychain(Request) masterkey.LoginKeychain { return nil }
|
||||
@@ -0,0 +1,97 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
"github.com/moond4rk/hackbrowserdata/internal/snapshot"
|
||||
)
|
||||
|
||||
// Extraction is one category of data from one profile of one user data dir. It is plain data, looked up again when it
|
||||
// runs, so a Plan prints as it is and compares with reflect.DeepEqual.
|
||||
type Extraction struct {
|
||||
DirID browser.DirID
|
||||
Profile string // Profile.Name; "" in a result about a whole user data dir
|
||||
Category category.Category // zero in a result about a whole user data dir
|
||||
}
|
||||
|
||||
// Plan is what a run will do: the extractions in output order, the files they need captured once each, and the
|
||||
// requested extractions that cannot run.
|
||||
type Plan struct {
|
||||
Dirs []browser.UserDataDir
|
||||
Files []snapshot.File
|
||||
Extractions []Extraction
|
||||
Skipped []Result
|
||||
}
|
||||
|
||||
type extractorsFunc func(browser.UserDataDir, browser.Profile) browser.Extractors
|
||||
|
||||
// NewPlan crosses every discovered profile with the requested categories. It only stats files; it opens nothing.
|
||||
func NewPlan(d Discovery, req Request) Plan {
|
||||
return newPlan(d, req, extractorsOf)
|
||||
}
|
||||
|
||||
func newPlan(d Discovery, req Request, extractors extractorsFunc) Plan {
|
||||
p := Plan{Dirs: d.Dirs, Skipped: append([]Result(nil), d.Failed...)}
|
||||
captured := make(map[snapshot.File]bool)
|
||||
for _, dir := range d.Dirs {
|
||||
for _, prof := range dir.Profiles {
|
||||
ex := extractors(dir, prof)
|
||||
for _, c := range req.Categories {
|
||||
e := Extraction{DirID: dir.ID, Profile: prof.Name, Category: c}
|
||||
x, ok := ex[c]
|
||||
if !ok {
|
||||
p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeUnsupported})
|
||||
continue
|
||||
}
|
||||
files, ok := locate(dir, prof, x.Sources)
|
||||
if !ok {
|
||||
p.Skipped = append(p.Skipped, Result{Extraction: e, Outcome: OutcomeAbsent})
|
||||
continue
|
||||
}
|
||||
p.Extractions = append(p.Extractions, e)
|
||||
for _, f := range files {
|
||||
if !captured[f] {
|
||||
captured[f] = true
|
||||
p.Files = append(p.Files, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// locate finds each source's first candidate on disk. An extraction needs every required source and at least one of
|
||||
// the profile's own; a shared one such as Local State never makes it present by itself.
|
||||
func locate(dir browser.UserDataDir, p browser.Profile, sources []browser.Source) ([]snapshot.File, bool) {
|
||||
var files []snapshot.File
|
||||
present := false
|
||||
for _, src := range sources {
|
||||
f, ok := firstOnDisk(dir, p, src)
|
||||
switch {
|
||||
case ok:
|
||||
files = append(files, f)
|
||||
present = present || !src.Shared
|
||||
case !src.Optional:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return files, present
|
||||
}
|
||||
|
||||
func firstOnDisk(dir browser.UserDataDir, p browser.Profile, src browser.Source) (snapshot.File, bool) {
|
||||
for _, rel := range src.Paths {
|
||||
if !src.Shared {
|
||||
rel = path.Join(p.Dir, rel)
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(dir.Path, filepath.FromSlash(rel)))
|
||||
if err == nil && info.IsDir() == src.IsDir {
|
||||
return snapshot.File{DirID: string(dir.ID), From: dir.Path, Rel: rel, IsDir: src.IsDir}, true
|
||||
}
|
||||
}
|
||||
return snapshot.File{}, false
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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, id string) browser.Def {
|
||||
t.Helper()
|
||||
def, ok := browser.Lookup(id)
|
||||
require.True(t, ok, id)
|
||||
return def
|
||||
}
|
||||
|
||||
func TestNewPlan(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")
|
||||
dir := browser.UserDataDir{
|
||||
ID: "chrome", Def: lookup(t, "chrome"), Path: path,
|
||||
Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}, {Name: "Profile 1", Dir: "Profile 1"}},
|
||||
}
|
||||
failed := dirFailure("edge", errors.New("permission denied"))
|
||||
req := Request{Categories: []category.Category{category.Password, category.Cookie, category.History, category.Download, category.CreditCard}}
|
||||
|
||||
got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}, Failed: []Result{failed}}, req)
|
||||
|
||||
file := func(rel string) snapshot.File { return snapshot.File{DirID: "chrome", From: path, Rel: rel} }
|
||||
extraction := func(profile string, c category.Category) Extraction {
|
||||
return Extraction{DirID: "chrome", Profile: profile, Category: c}
|
||||
}
|
||||
skipped := func(profile string, c category.Category, o Outcome) Result {
|
||||
return Result{Extraction: extraction(profile, c), Outcome: o}
|
||||
}
|
||||
assert.Equal(t, Plan{
|
||||
Dirs: []browser.UserDataDir{dir},
|
||||
// Local State and History are captured once, however many extractions read them.
|
||||
Files: []snapshot.File{
|
||||
file("Default/Login Data"), file("Local State"), file("Default/Network/Cookies"), file("Default/History"),
|
||||
file("Profile 1/History"),
|
||||
},
|
||||
Extractions: []Extraction{
|
||||
extraction("Default", category.Password), extraction("Default", category.Cookie),
|
||||
extraction("Default", category.History), extraction("Default", category.Download),
|
||||
extraction("Profile 1", category.History), extraction("Profile 1", category.Download),
|
||||
},
|
||||
Skipped: []Result{
|
||||
failed,
|
||||
skipped("Default", category.CreditCard, OutcomeAbsent),
|
||||
// Local State alone does not make a profile's passwords present.
|
||||
skipped("Profile 1", category.Password, OutcomeAbsent),
|
||||
skipped("Profile 1", category.Cookie, OutcomeAbsent),
|
||||
skipped("Profile 1", category.CreditCard, OutcomeAbsent),
|
||||
},
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestNewPlan_PicksTheFirstCandidateOnDisk(t *testing.T) {
|
||||
path := t.TempDir()
|
||||
touch(t, path, "Default", "Cookies")
|
||||
dir := browser.UserDataDir{ID: "chrome", Def: lookup(t, "chrome"), Path: path, Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}}
|
||||
|
||||
got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.Cookie}})
|
||||
assert.Equal(t, []snapshot.File{{DirID: "chrome", From: path, Rel: "Default/Cookies"}}, got.Files)
|
||||
}
|
||||
|
||||
func TestNewPlan_FlatLayoutProfile(t *testing.T) {
|
||||
path := t.TempDir()
|
||||
touch(t, path, "History")
|
||||
dir := browser.UserDataDir{ID: "opera", Def: lookup(t, "opera"), Path: path, Profiles: []browser.Profile{{Name: "Opera Stable"}}}
|
||||
|
||||
got := NewPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.History}})
|
||||
assert.Equal(t, []snapshot.File{{DirID: "opera", From: path, Rel: "History"}}, got.Files)
|
||||
assert.Equal(t, []Extraction{{DirID: "opera", Profile: "Opera Stable", Category: category.History}}, got.Extractions)
|
||||
}
|
||||
|
||||
func TestNewPlan_UnsupportedCategory(t *testing.T) {
|
||||
dir := browser.UserDataDir{ID: "x", Path: t.TempDir(), Profiles: []browser.Profile{{Name: "Default", Dir: "Default"}}}
|
||||
none := func(browser.UserDataDir, browser.Profile) browser.Extractors { return browser.Extractors{} }
|
||||
|
||||
got := newPlan(Discovery{Dirs: []browser.UserDataDir{dir}}, Request{Categories: []category.Category{category.CreditCard}}, none)
|
||||
assert.Equal(t, []Result{{Extraction: Extraction{DirID: "x", Profile: "Default", Category: category.CreditCard}, Outcome: OutcomeUnsupported}},
|
||||
got.Skipped)
|
||||
assert.Empty(t, got.Extractions)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"text/tabwriter"
|
||||
)
|
||||
|
||||
// Report writes every result as one line, in output order. The summary is additive: it is not part of the output
|
||||
// contract, and it never changes the exit status.
|
||||
func Report(w io.Writer, s Summary) error {
|
||||
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, "Browser\tProfile\tCategory\tResult\tRecords\tDetail")
|
||||
for _, r := range s.Results {
|
||||
profile, cat := "-", "-"
|
||||
if r.Profile != "" {
|
||||
profile = r.Profile
|
||||
}
|
||||
if r.Category != 0 {
|
||||
cat = r.Category.String()
|
||||
}
|
||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%d\t%s\n", r.DirID, profile, cat, r.Outcome, r.Count, detail(r))
|
||||
}
|
||||
return tw.Flush()
|
||||
}
|
||||
|
||||
func detail(r Result) string {
|
||||
switch {
|
||||
case r.Err != nil:
|
||||
return r.Err.Error()
|
||||
case r.Failed > 0:
|
||||
return fmt.Sprintf("%d not recovered", r.Failed)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/moond4rk/hackbrowserdata/internal/category"
|
||||
)
|
||||
|
||||
func TestReport(t *testing.T) {
|
||||
cookie := Extraction{DirID: "chrome", Profile: "Default", Category: category.Cookie}
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, Report(&buf, Summary{Results: []Result{
|
||||
{Extraction: cookie, Outcome: OutcomePartial, Count: 224, Failed: 4},
|
||||
dirFailure("arc-2", errors.New("permission denied")),
|
||||
{Extraction: Extraction{DirID: "edge", Profile: "Default", Category: category.Password}},
|
||||
}}))
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
|
||||
require.Len(t, lines, 4)
|
||||
assert.Equal(t, []string{"chrome", "Default", "cookie", "partial", "224", "4", "not", "recovered"}, strings.Fields(lines[1]))
|
||||
assert.Equal(t, []string{"arc-2", "-", "-", "error", "0", "permission", "denied"}, strings.Fields(lines[2]))
|
||||
assert.Equal(t, "unset", strings.Fields(lines[3])[3], "a result whose outcome was never set must not read as ok")
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package app
|
||||
|
||||
import "github.com/moond4rk/hackbrowserdata/internal/browser"
|
||||
|
||||
// Outcome is how one extraction ended. It starts at 1, so a result whose outcome was never set does not read as ok.
|
||||
type Outcome int
|
||||
|
||||
const (
|
||||
OutcomeOK Outcome = iota + 1
|
||||
OutcomePartial
|
||||
OutcomeAbsent
|
||||
OutcomeUnsupported
|
||||
OutcomeError
|
||||
)
|
||||
|
||||
func (o Outcome) String() string {
|
||||
switch o {
|
||||
case OutcomeOK:
|
||||
return "ok"
|
||||
case OutcomePartial:
|
||||
return "partial"
|
||||
case OutcomeAbsent:
|
||||
return "absent"
|
||||
case OutcomeUnsupported:
|
||||
return "unsupported"
|
||||
case OutcomeError:
|
||||
return "error"
|
||||
default:
|
||||
return "unset"
|
||||
}
|
||||
}
|
||||
|
||||
// Result is one extraction's outcome, or a failure of a whole user data dir when Profile and Category are empty.
|
||||
type Result struct {
|
||||
Extraction
|
||||
Outcome Outcome
|
||||
Count int // records emitted
|
||||
Failed int // record-level problems reported
|
||||
Err error // set when Outcome is OutcomeError
|
||||
}
|
||||
|
||||
// Summary is every result of a run, in output order: what never ran first, then each user data dir's extractions.
|
||||
type Summary struct {
|
||||
Results []Result
|
||||
}
|
||||
|
||||
func dirFailure(id browser.DirID, err error) Result {
|
||||
return Result{Extraction: Extraction{DirID: id}, Outcome: OutcomeError, Err: err}
|
||||
}
|
||||
@@ -67,7 +67,7 @@ type Extractors map[category.Category]Extractor
|
||||
|
||||
Sources are static data: a base package declares them once per category and never rewrites them per profile. Plan joins a profile-scoped path with the profile's `Dir`, leaves a `Shared` one as it is, and captures the union once per user data dir — so `Local State`, or the Chromium `History` file that feeds both history and downloads, is copied once however many extractions need it.
|
||||
|
||||
An extraction is `absent` when a required source has no candidate on disk, or when all its sources are optional and none is there. Chromium passwords are two optional sources — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces today's output, including a profile that only ever synced passwords, without a special case.
|
||||
An extraction is `absent` when a required source has no candidate on disk, or when all its sources are optional and none of the profile's own is there: a shared source such as `Local State` never makes an extraction present by itself. Chromium passwords are two optional sources — `Login Data` (store `local`) and `Login Data For Account` (store `account`) — which reproduces today's output, including a profile that only ever synced passwords, without a special case.
|
||||
|
||||
`Extractor` / `Extractors` are **DECIDED**.
|
||||
|
||||
|
||||
Reference in new issue
Block a user