diff --git a/CLAUDE.md b/CLAUDE.md index 09907d9..bd98b94 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,7 +59,7 @@ make payload-clean # rm internal/abe/payload/*.bin - **C payload**: all sources in `internal/abe/native/` are first-party (no vendored C); `rfcs/003-secrets.md` says why. - **Error handling**: `fmt.Errorf("context: %w", err)` for wrapping, never `_ =` to ignore errors - **Logging**: `log.Debugf` for record-level diagnostics, `log.Infof` for user-facing progress/status, `log.Warnf` for unexpected conditions. Extract methods should return errors, not log them. -- **Naming**: follow Go conventions and the naming rules in `rfcs/001-architecture.md`; spell names out (`extractors`, `snapshotDir`, `profile`), leaving only `i`/`j`, `err`, `ctx`, `ok`, `t`/`tb`, `id`, `iv`, `db`, `fd`, `n`, and one-letter receivers short (`varnamelen` enforces it) +- **Naming**: follow Go conventions and the naming rules in `rfcs/001-architecture.md`; spell names out (`extractors`, `relativePath`, `profile`), leaving only `i`/`j`, `err`, `ctx`, `ok`, `t`/`tb`, `id`, `iv`, `db`, `fd`, `n`, and one-letter receivers short (`varnamelen` enforces it) - **Comments**: none by default; when one is needed, one line of at most 120 characters that says why, never what the code does (up to 3 lines only when the reason cannot fit); a comment on a declaration starts with its name (`// AssertJSONFallback checks …`) - **Tests**: `internal/browser/browsertest` builds real fixture files (SQLite, JSON, LevelDB, plist) into a `t.TempDir()` — never a live browser, never a database mock; goldens live in each package's `testdata/` and `HBD_UPDATE_GOLDEN=1 go test ./...` regenerates them - **Architecture**: see `rfcs/README.md` — eight short RFCs on the decisions behind the design; an RFC changes only when a decision does, never for a refactor diff --git a/cmd/hack-browser-data/archive.go b/cmd/hack-browser-data/archive.go index 3313640..59d3fb7 100644 --- a/cmd/hack-browser-data/archive.go +++ b/cmd/hack-browser-data/archive.go @@ -24,7 +24,7 @@ func newArchiveCommand() *cobra.Command { return err } discovery := app.Discover(options.Target) - if foundNothing(command.ErrOrStderr(), discovery, "no browsers found") { + if warnIfNothingFound(command.ErrOrStderr(), discovery, "no browsers found") { return nil } fileCount, err := app.Archive(command.Context(), discovery, options.Categories, outputPath) diff --git a/cmd/hack-browser-data/dump.go b/cmd/hack-browser-data/dump.go index d39f4a9..8f35943 100644 --- a/cmd/hack-browser-data/dump.go +++ b/cmd/hack-browser-data/dump.go @@ -46,7 +46,7 @@ func runDump(ctx context.Context, stderr io.Writer, flags app.DumpFlags, keychai return err } discovery := app.Discover(options.Target) - if foundNothing(stderr, discovery, "no browsers found") { + if warnIfNothingFound(stderr, discovery, "no browsers found") { return nil } summary, err := app.Execute(ctx, discovery, options.Categories, options.Output, options.Keychain) diff --git a/cmd/hack-browser-data/main.go b/cmd/hack-browser-data/main.go index b7303f4..777f49e 100644 --- a/cmd/hack-browser-data/main.go +++ b/cmd/hack-browser-data/main.go @@ -80,8 +80,8 @@ func report(writer io.Writer, summary app.Summary) { } } -// foundNothing reports discovery's failures, the likely reason it found no browser data, then says so. -func foundNothing(stderr io.Writer, discovery app.Discovery, message string) bool { +// warnIfNothingFound reports discovery's failures, the likely reason it found no browser data, then says so. +func warnIfNothingFound(stderr io.Writer, discovery app.Discovery, message string) bool { if len(discovery.Dirs) > 0 { return false } @@ -93,7 +93,7 @@ func foundNothing(stderr io.Writer, discovery app.Discovery, message string) boo } // announceExport lists the files a run wrote, even when it stopped early, so the user finds what it left. -func announceExport(stderr io.Writer, exported export.Output) { +func announceExport(stderr io.Writer, exported export.Listing) { if len(exported.Files) == 0 { return } diff --git a/cmd/hack-browser-data/restore.go b/cmd/hack-browser-data/restore.go index 5a1bdf3..264cb85 100644 --- a/cmd/hack-browser-data/restore.go +++ b/cmd/hack-browser-data/restore.go @@ -47,17 +47,17 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e if err != nil { return err } - data, err := openRestoreData(flags.DataDir, flags.DataZip) + root, err := openRestoreData(flags.DataDir, flags.DataZip) if err != nil { return err } - defer closeRestoreData(data) + defer closeRestoreData(root) - discovery, keys, err := app.DiscoverRestore(data.Path(), keyFile, options.Target.BrowserName) + discovery, keys, err := app.DiscoverRestore(root.Path(), keyFile, options.Target.BrowserName) if err != nil { return err } - if foundNothing(stderr, discovery, "no browsers to restore from the supplied keys and data") { + if warnIfNothingFound(stderr, discovery, "no browsers to restore from the supplied keys and data") { return nil } summary, err := app.ExecuteWithKeys(ctx, discovery, options.Categories, options.Output, keys) @@ -68,19 +68,19 @@ func runRestore(ctx context.Context, stderr io.Writer, flags app.RestoreFlags) e return err } -func openRestoreData(dataDir, dataZip string) (*snapshot.Dir, error) { +func openRestoreData(dataDir, dataZip string) (*snapshot.Root, error) { if dataDir != "" { return snapshot.Open(dataDir), nil } - snapshots, err := snapshot.Unzip(dataZip) + root, err := snapshot.Unzip(dataZip) if err != nil { return nil, fmt.Errorf("extract %s: %w", dataZip, err) } - return snapshots, nil + return root, nil } -func closeRestoreData(snapshots *snapshot.Dir) { - if err := snapshots.Close(); err != nil { +func closeRestoreData(root *snapshot.Root) { + if err := root.Close(); err != nil { log.Warnf("restore: %v", err) } } diff --git a/internal/app/archive.go b/internal/app/archive.go index fe9ae86..2272bfc 100644 --- a/internal/app/archive.go +++ b/internal/app/archive.go @@ -45,19 +45,19 @@ func Archive(ctx context.Context, discovery Discovery, categories []category.Cat } files := archiveFiles(dirs, categories) - snapshots, err := snapshot.Temp() + root, err := snapshot.Temp() if err != nil { return 0, err } - defer closeSnapshot(snapshots) - if err := snapshots.Capture(ctx, files); err != nil { + defer closeRoot(root) + if err := root.Capture(ctx, files); err != nil { return 0, err } - fileCount := countCaptured(snapshots, files) + fileCount := countCaptured(root, files) if fileCount == 0 { return 0, errors.New("no decryption-relevant files found to archive") } - if err := snapshots.Zip(archivePath); err != nil { + if err := root.Zip(archivePath); err != nil { return 0, fmt.Errorf("write archive %s: %w", archivePath, err) } return fileCount, nil @@ -81,10 +81,10 @@ func archiveFiles(dirs []browser.UserDataDir, categories []category.Category) [] } // countCaptured counts the files that reached the snapshot, reporting each one whose copy failed. -func countCaptured(snapshots *snapshot.Dir, files []snapshot.File) int { +func countCaptured(root *snapshot.Root, files []snapshot.File) int { fileCount := 0 for _, file := range files { - if _, err := snapshots.Snapshot(file.UserDataDirID).Path(file.RelativePath); err != nil { + if _, err := root.Snapshot(file.UserDataDirID).Path(file.RelativePath); err != nil { log.Warnf("archive: acquire %s/%s: %v", file.UserDataDirID, file.RelativePath, err) continue } diff --git a/internal/app/dumpkeys.go b/internal/app/dumpkeys.go index 2b6e420..d5d7763 100644 --- a/internal/app/dumpkeys.go +++ b/internal/app/dumpkeys.go @@ -65,7 +65,7 @@ func dumpKeysWith(ctx context.Context, discovery Discovery, keys dirKeysFunc) (m if dir.Browser.Base != browser.Chromium { continue } - set, err := retrieveKeys(ctx, dir, keys) + set, err := retrieveDirKeys(ctx, dir, keys) if ctxErr := ctx.Err(); ctxErr != nil { return masterkey.KeyFile{}, fmt.Errorf("run stopped: %w", ctxErr) } @@ -94,22 +94,22 @@ func dumpKeysWith(ctx context.Context, discovery Discovery, keys dirKeysFunc) (m return keyFile, nil } -func retrieveKeys(ctx context.Context, dir browser.UserDataDir, keys dirKeysFunc) (masterkey.Set, error) { - snapshots, err := snapshot.Temp() +func retrieveDirKeys(ctx context.Context, dir browser.UserDataDir, keys dirKeysFunc) (masterkey.Set, error) { + root, err := snapshot.Temp() if err != nil { return nil, err } - defer closeSnapshot(snapshots) + defer closeRoot(root) var files []snapshot.File for _, source := range chromium.KeySources() { if file, ok, err := firstOnDisk(dir, browser.Profile{}, source); err == nil && ok { files = append(files, file) } } - if err := snapshots.Capture(ctx, files); err != nil { + if err := root.Capture(ctx, files); err != nil { return nil, err } - return keys(ctx, dir, snapshots.Snapshot(string(dir.ID))) + return keys(ctx, dir, root.Snapshot(string(dir.ID))) } func profileNames(dir browser.UserDataDir) []string { diff --git a/internal/app/execute.go b/internal/app/execute.go index cf81e57..bf5c3b1 100644 --- a/internal/app/execute.go +++ b/internal/app/execute.go @@ -40,7 +40,7 @@ func execute( } summary, err := runner{writer: writer, extractors: extractors, retrieveKeys: keys, logProgress: true}.run(ctx, discovery, categories) closeErr := writer.Close() - summary.Exported = writer.Output() + summary.Exported = writer.Listing() return summary, errors.Join(err, closeErr) } @@ -82,20 +82,20 @@ func (r runner) runDir(ctx context.Context, dir browser.UserDataDir, categories log.Infof("Extracting %s...", dir.Browser.DisplayName) } - snapshots, err := snapshot.Temp() + root, err := snapshot.Temp() if err != nil { summary.Results = append(summary.Results, failAll(plan.extractions, err)...) return summary, nil } - defer closeSnapshot(snapshots) - if err := snapshots.Capture(ctx, plan.files); err != nil { + defer closeRoot(root) + if err := root.Capture(ctx, plan.files); err != nil { if ctx.Err() != nil { return summary, err } summary.Results = append(summary.Results, failAll(plan.extractions, err)...) return summary, nil } - dirSnapshot := snapshots.Snapshot(string(dir.ID)) + dirSnapshot := root.Snapshot(string(dir.ID)) keys := &dirKeys{dir: dir, dirSnapshot: dirSnapshot} if dir.Browser.Base == browser.Chromium { @@ -139,8 +139,8 @@ func failAll(extractions []plannedExtraction, err error) []Result { return results } -func closeSnapshot(snapshots *snapshot.Dir) { - if err := snapshots.Close(); err != nil { +func closeRoot(root *snapshot.Root) { + if err := root.Close(); err != nil { log.Warnf("%v", err) } } diff --git a/internal/app/restore_golden_test.go b/internal/app/restore_golden_test.go index d8ef18c..4f11daa 100644 --- a/internal/app/restore_golden_test.go +++ b/internal/app/restore_golden_test.go @@ -85,7 +85,7 @@ func chromiumKeyFile(t *testing.T) string { profiles = append(profiles, fixtureProfile.Dir) } keyFile := masterkey.KeyFile{ - // A literal rather than KeyFileVersion: keys files written by today's dumpkeys must keep restoring. + // A literal rather than the version constant: keys files written by today's dumpkeys must keep restoring. Version: "2", CreatedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), Host: masterkey.Host{OS: "windows", Arch: "amd64"}, diff --git a/internal/app/result.go b/internal/app/result.go index 8c015cf..fd17823 100644 --- a/internal/app/result.go +++ b/internal/app/result.go @@ -60,5 +60,5 @@ type DirFailure struct { type Summary struct { Results []Result DirFailures []DirFailure - Exported export.Output // the files Execute wrote; empty when nothing was exported + Exported export.Listing // the files Execute wrote; empty when nothing was exported } diff --git a/internal/browser/chromium/chromium.go b/internal/browser/chromium/chromium.go index e16c2f4..d5c9ff5 100644 --- a/internal/browser/chromium/chromium.go +++ b/internal/browser/chromium/chromium.go @@ -94,7 +94,7 @@ func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { var profiles []browser.Profile for _, entry := range entries { - if entry.IsDir() && !isSkippedDir(entry.Name()) && isProfileDir(filepath.Join(dir.Path, entry.Name())) { + if entry.IsDir() && !isSkippedProfileDir(entry.Name()) && isProfileDir(filepath.Join(dir.Path, entry.Name())) { profiles = append(profiles, browser.Profile{Name: entry.Name(), RelativePath: entry.Name()}) } } @@ -110,23 +110,23 @@ func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { // Copied or restored trees may lack the marker, which no category reads, so a subdir with profile files is one too. for _, entry := range entries { - if entry.IsDir() && !isSkippedDir(entry.Name()) && hasAnyFile(filepath.Join(dir.Path, entry.Name()), profileFiles) { + if entry.IsDir() && !isSkippedProfileDir(entry.Name()) && hasAnyFile(filepath.Join(dir.Path, entry.Name()), profileFiles) { profiles = append(profiles, browser.Profile{Name: entry.Name(), RelativePath: entry.Name()}) } } return profiles, nil } -func isProfileDir(dir string) bool { +func isProfileDir(path string) bool { for _, name := range profileMarkers { - if _, err := os.Stat(filepath.Join(dir, name)); err == nil { + if _, err := os.Stat(filepath.Join(path, name)); err == nil { return true } } return false } -func isSkippedDir(name string) bool { +func isSkippedProfileDir(name string) bool { switch name { case "System Profile", "Guest Profile", "Snapshot": return true @@ -146,9 +146,9 @@ func profileFilePaths(dir browser.UserDataDir) []string { return paths } -func hasAnyFile(dir string, paths []string) bool { - for _, relativePath := range paths { - if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(relativePath))); err == nil { +func hasAnyFile(path string, relativePaths []string) bool { + for _, relativePath := range relativePaths { + if _, err := os.Stat(filepath.Join(path, filepath.FromSlash(relativePath))); err == nil { return true } } diff --git a/internal/browser/chromium/override.go b/internal/browser/chromium/override.go index aeddcfa..164b737 100644 --- a/internal/browser/chromium/override.go +++ b/internal/browser/chromium/override.go @@ -7,13 +7,13 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/category" ) -// kindChromium is the keys.json kind of every Chromium browser no override covers. -const kindChromium = "chromium" +// 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 - kind string + vaultKind string extractors browser.Extractors } @@ -21,7 +21,7 @@ type override struct { var overrides = []override{ { browserNames: []string{"yandex"}, - kind: "chromium-yandex", + vaultKind: "chromium-yandex", extractors: browser.Extractors{ category.Password: newDecryptingExtractor(extractYandexPasswords, yaPassmanData), category.CreditCard: newDecryptingExtractor(extractYandexCreditCards, yaCreditCards), @@ -29,7 +29,7 @@ var overrides = []override{ }, { browserNames: []string{"opera", "opera-gx", "vought"}, - kind: "chromium-opera", + vaultKind: "chromium-opera", extractors: browser.Extractors{ category.Extension: newPlainExtractor(extractOperaExtensions, securePreferences), }, @@ -50,18 +50,18 @@ func overrideFor(browserName string) (override, bool) { // 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.kind + return fork.vaultKind } - return kindChromium + return vaultKindChromium } // BrowserNameForKind names the browser whose extractors read a vault of kind; a plain Chromium vault keeps its own. func BrowserNameForKind(kind, name string) (string, error) { - if kind == kindChromium { + if kind == vaultKindChromium { return name, nil } for _, fork := range overrides { - if fork.kind == kind { + if fork.vaultKind == kind { return fork.browserNames[0], nil } } diff --git a/internal/browser/chromium/override_test.go b/internal/browser/chromium/override_test.go index b7ad1c6..6fb7242 100644 --- a/internal/browser/chromium/override_test.go +++ b/internal/browser/chromium/override_test.go @@ -25,11 +25,11 @@ func TestOverrides_NameChromiumBrowsers(t *testing.T) { // TestOverrides_KindsAndNamesAreUnique keeps BrowserNameForKind and overrideFor from depending on table order. func TestOverrides_KindsAndNamesAreUnique(t *testing.T) { - kinds := map[string]bool{kindChromium: true} + kinds := map[string]bool{vaultKindChromium: true} names := map[string]bool{} for _, fork := range overrides { - assert.Falsef(t, kinds[fork.kind], "kind %q is used twice", fork.kind) - kinds[fork.kind] = true + 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 @@ -42,7 +42,7 @@ 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.kind, kind, "override %q", name) + require.Equalf(t, fork.vaultKind, kind, "override %q", name) forkBrowserName, err := BrowserNameForKind(kind, "unknown") require.NoError(t, err) restored, ok := overrideFor(forkBrowserName) @@ -50,8 +50,8 @@ func TestVaultKind_RoundTripsEveryFork(t *testing.T) { assert.Equalf(t, categoriesOf(fork.extractors), categoriesOf(restored.extractors), "kind %s of %q", kind, name) } } - assert.Equal(t, kindChromium, VaultKind(browser.Browser{Name: "chrome"})) - plainBrowserName, err := BrowserNameForKind(kindChromium, "unknown") + assert.Equal(t, vaultKindChromium, VaultKind(browser.Browser{Name: "chrome"})) + plainBrowserName, err := BrowserNameForKind(vaultKindChromium, "unknown") require.NoError(t, err) assert.Equal(t, "unknown", plainBrowserName) _, err = BrowserNameForKind("bogus", "unknown") diff --git a/internal/browser/extractor_test.go b/internal/browser/extractor_test.go index a7f42dc..5ea5dc4 100644 --- a/internal/browser/extractor_test.go +++ b/internal/browser/extractor_test.go @@ -57,15 +57,15 @@ func TestProfileSnapshotPath_FailedCopyIsReported(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(from, "Default", "Network", "Cookies"), 0o700)) writeSnapshotFile(t, from, "Default/Cookies") - snapshotDir, err := snapshot.Temp() + root, err := snapshot.Temp() require.NoError(t, err) - defer func() { require.NoError(t, snapshotDir.Close()) }() - require.NoError(t, snapshotDir.Capture(context.Background(), []snapshot.File{ + defer func() { require.NoError(t, root.Close()) }() + require.NoError(t, root.Capture(context.Background(), []snapshot.File{ {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Network/Cookies"}, {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Cookies"}, })) - profileSnapshot := NewProfileSnapshot(snapshotDir.Snapshot("chrome"), Profile{Name: "Default", RelativePath: "Default"}, nil) + profileSnapshot := NewProfileSnapshot(root.Snapshot("chrome"), Profile{Name: "Default", RelativePath: "Default"}, nil) _, err = profileSnapshot.Path(Source{Path: "Network/Cookies", Fallbacks: []string{"Cookies"}}) require.Error(t, err) assert.NotErrorIs(t, err, fs.ErrNotExist) diff --git a/internal/browser/firefox/firefox.go b/internal/browser/firefox/firefox.go index 6827a10..c0621fa 100644 --- a/internal/browser/firefox/firefox.go +++ b/internal/browser/firefox/firefox.go @@ -93,14 +93,14 @@ func discoverProfiles(dir browser.UserDataDir) ([]browser.Profile, error) { return profiles, nil } -func hasDataFile(dir string) bool { +func hasDataFile(path string) bool { for _, extractor := range defaultExtractors { for _, source := range extractor.Sources { if source.Optional { continue } for _, relativePath := range source.Paths() { - if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(relativePath))); err == nil { + if _, err := os.Stat(filepath.Join(path, filepath.FromSlash(relativePath))); err == nil { return true } } diff --git a/internal/browser/safari/profiles.go b/internal/browser/safari/profiles.go index c9c90b0..b226f4a 100644 --- a/internal/browser/safari/profiles.go +++ b/internal/browser/safari/profiles.go @@ -39,21 +39,21 @@ func namedProfiles(library string) []browser.Profile { // readNamedProfilesFromDB reads a copy, never Safari's live file; (nil, err) means unreadable, and any slice is final. func readNamedProfilesFromDB(library string) ([]browser.Profile, error) { - snapshotDir, err := snapshot.Temp() + root, err := snapshot.Temp() if err != nil { return nil, err } defer func() { - if err := snapshotDir.Close(); err != nil { + if err := root.Close(); err != nil { log.Warnf("%v", err) } }() - if err := snapshotDir.Capture(context.Background(), []snapshot.File{{ + if err := root.Capture(context.Background(), []snapshot.File{{ UserDataDirID: discoveryUserDataDirID, UserDataDirPath: library, RelativePath: tabsDatabasePath, }}); err != nil { return nil, fmt.Errorf("copy SafariTabs.db: %w", err) } - path, err := snapshotDir.Snapshot(discoveryUserDataDirID).Path(tabsDatabasePath) + path, err := root.Snapshot(discoveryUserDataDirID).Path(tabsDatabasePath) if err != nil { return nil, fmt.Errorf("copy SafariTabs.db: %w", err) } @@ -109,7 +109,7 @@ func readNamedProfilesFromDir(library string) []browser.Profile { return out } -// newNamedProfile sets Dir to the profile's own History.db directory, so its UUID travels with it to Extractors. +// newNamedProfile sets RelativePath to the profile's own History.db directory, so its UUID travels with it to Extractors. func newNamedProfile(upperUUID, title string) browser.Profile { return browser.Profile{Name: resolveProfileName(title, upperUUID), RelativePath: namedProfilesDir + "/" + upperUUID} } diff --git a/internal/crypto/asn1pbe.go b/internal/crypto/asn1pbe.go index a0bd923..85b586e 100644 --- a/internal/crypto/asn1pbe.go +++ b/internal/crypto/asn1pbe.go @@ -48,12 +48,12 @@ type privateKeyPBE struct { func (pbe privateKeyPBE) Decrypt(globalSalt []byte) ([]byte, error) { key, iv := pbe.deriveKeyAndIV(globalSalt) - return DES3Decrypt(key, iv, pbe.Encrypted) + return des3Decrypt(key, iv, pbe.Encrypted) } func (pbe privateKeyPBE) Encrypt(globalSalt, plaintext []byte) ([]byte, error) { key, iv := pbe.deriveKeyAndIV(globalSalt) - return DES3Encrypt(key, iv, plaintext) + return des3Encrypt(key, iv, plaintext) } // deriveKeyAndIV follows https://searchfox.org/mozilla-central/source/security/nss/lib/softoken/lowpbe.c @@ -145,7 +145,7 @@ func (pbe credentialPBE) Decrypt(masterKey []byte) ([]byte, error) { if len(key) < des3KeySize { return nil, errShortKey } - return DES3Decrypt(key[:des3KeySize], iv, pbe.Encrypted) + return des3Decrypt(key[:des3KeySize], iv, pbe.Encrypted) case aes.BlockSize: // 16: AES-256-CBC (Firefox 144+) return AESCBCDecrypt(key, iv, pbe.Encrypted) default: @@ -160,7 +160,7 @@ func (pbe credentialPBE) Encrypt(masterKey, plaintext []byte) ([]byte, error) { if len(key) < des3KeySize { return nil, errShortKey } - return DES3Encrypt(key[:des3KeySize], iv, plaintext) + return des3Encrypt(key[:des3KeySize], iv, plaintext) case aes.BlockSize: return AESCBCEncrypt(key, iv, plaintext) default: diff --git a/internal/crypto/crypto.go b/internal/crypto/crypto.go index d240be1..e008315 100644 --- a/internal/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -23,7 +23,7 @@ func AESCBCDecrypt(key, iv, ciphertext []byte) ([]byte, error) { return cbcDecrypt(block, iv, ciphertext) } -func DES3Encrypt(key, iv, plaintext []byte) ([]byte, error) { +func des3Encrypt(key, iv, plaintext []byte) ([]byte, error) { block, err := des.NewTripleDESCipher(key) if err != nil { return nil, err @@ -31,7 +31,7 @@ func DES3Encrypt(key, iv, plaintext []byte) ([]byte, error) { return cbcEncrypt(block, iv, plaintext) } -func DES3Decrypt(key, iv, ciphertext []byte) ([]byte, error) { +func des3Decrypt(key, iv, ciphertext []byte) ([]byte, error) { block, err := des.NewTripleDESCipher(key) if err != nil { return nil, err diff --git a/internal/crypto/crypto_test.go b/internal/crypto/crypto_test.go index dbc8e16..e8ff50d 100644 --- a/internal/crypto/crypto_test.go +++ b/internal/crypto/crypto_test.go @@ -45,7 +45,7 @@ func TestAESCBCDecrypt(t *testing.T) { } func TestDES3Encrypt(t *testing.T) { - encrypted, err := DES3Encrypt(des3Key, des3IV, plainText) + encrypted, err := des3Encrypt(des3Key, des3IV, plainText) require.NoError(t, err) assert.NotEmpty(t, encrypted) assert.Equal(t, des3Ciphertext, fmt.Sprintf("%x", encrypted)) @@ -53,7 +53,7 @@ func TestDES3Encrypt(t *testing.T) { func TestDES3Decrypt(t *testing.T) { ciphertext, _ := hex.DecodeString(des3Ciphertext) - decrypted, err := DES3Decrypt(des3Key, des3IV, ciphertext) + decrypted, err := des3Decrypt(des3Key, des3IV, ciphertext) require.NoError(t, err) assert.NotEmpty(t, decrypted) assert.Equal(t, plainText, decrypted) diff --git a/internal/export/writer.go b/internal/export/writer.go index 36aa34c..ed75ecd 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -14,16 +14,16 @@ import ( ) type Writer struct { - dir string - format Format - zip bool - files map[category.Category]*categoryFile - failed bool - out Output + dir string + format Format + zip bool + files map[category.Category]*categoryFile + failed bool + listing Listing } -// Output is what a clean Close left in the output dir: each category file in category order, and the zip with --zip. -type Output struct { +// Listing is what a clean Close left in the output dir: each category file in category order, and the zip with --zip. +type Listing struct { Dir string Files []File ZipName string @@ -82,7 +82,7 @@ func (w *Writer) write(dataCategory category.Category, records []record.Record) return nil } -// Close completes the files even after a failed Write, so they keep what was written; only a clean run fills Output. +// Close completes the files even after a failed Write, so they keep what was written; only a clean run fills Listing. func (w *Writer) Close() error { var ( errs []error @@ -106,15 +106,15 @@ func (w *Writer) Close() error { } return nil } - w.out = Output{Dir: w.dir, Files: files} + w.listing = Listing{Dir: w.dir, Files: files} if w.zip { return w.writeZip() } return nil } -func (w *Writer) Output() Output { - return w.out +func (w *Writer) Listing() Listing { + return w.listing } // writeZip removes the loose files only after the zip is in place, so a failure leaves every one of them where it was. @@ -133,7 +133,7 @@ func (w *Writer) writeZip() error { return fmt.Errorf("zip: remove %s: %w", name, err) } } - w.out.ZipName = zipName + w.listing.ZipName = zipName return nil } diff --git a/internal/export/writer_test.go b/internal/export/writer_test.go index 9502883..eec9620 100644 --- a/internal/export/writer_test.go +++ b/internal/export/writer_test.go @@ -115,7 +115,7 @@ func TestClose_AfterFailedWriteKeepsEarlierFiles(t *testing.T) { var cookies []record.Cookie readJSON(t, filepath.Join(dir, "cookie.json"), &cookies) assert.Empty(t, cookies) - assert.Zero(t, writer.Output(), "a failed run lists nothing") + assert.Zero(t, writer.Listing(), "a failed run lists nothing") } func TestClose_OutputListsTheFilesInCategoryOrder(t *testing.T) { @@ -128,7 +128,7 @@ func TestClose_OutputListsTheFilesInCategoryOrder(t *testing.T) { })) require.NoError(t, writer.Close()) - assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.json", Count: 2}, {Name: "history.json", Count: 1}}}, writer.Output()) + assert.Equal(t, Listing{Dir: dir, Files: []File{{Name: "password.json", Count: 2}, {Name: "history.json", Count: 1}}}, writer.Listing()) } // TestClose_ZipLeavesOtherFilesAlone packs only this run's files; the rest of the directory is not the writer's. @@ -158,7 +158,7 @@ func TestClose_ZipOutputNamesTheArchive(t *testing.T) { require.NoError(t, writer.Write(category.Password, []record.Record{&record.Login{URL: "https://a.example"}})) require.NoError(t, writer.Close()) - assert.Equal(t, Output{Dir: dir, Files: []File{{Name: "password.csv", Count: 1}}, ZipName: "results.zip"}, writer.Output()) + assert.Equal(t, Listing{Dir: dir, Files: []File{{Name: "password.csv", Count: 1}}, ZipName: "results.zip"}, writer.Listing()) } // TestClose_ZipIsOwnerOnly gives the zip the category files' owner-only mode, since it holds the same records. diff --git a/internal/log/logger.go b/internal/log/logger.go index afcd500..8decf93 100644 --- a/internal/log/logger.go +++ b/internal/log/logger.go @@ -65,15 +65,3 @@ func (l *logger) write(level logLevel, message string) { _, _ = io.WriteString(l.out, line) l.mutex.Unlock() } - -func (l *logger) Debugf(format string, args ...any) { - l.write(debugLevel, fmt.Sprintf(format, args...)) -} - -func (l *logger) Infof(format string, args ...any) { - l.write(infoLevel, fmt.Sprintf(format, args...)) -} - -func (l *logger) Warnf(format string, args ...any) { - l.write(warnLevel, fmt.Sprintf(format, args...)) -} diff --git a/internal/log/logger_test.go b/internal/log/logger_test.go index a322269..613bdca 100644 --- a/internal/log/logger_test.go +++ b/internal/log/logger_test.go @@ -9,6 +9,15 @@ import ( "github.com/stretchr/testify/assert" ) +func captureLog(t *testing.T) *bytes.Buffer { + t.Helper() + var buffer bytes.Buffer + saved := defaultLogger + defaultLogger = newLogger(&buffer) + t.Cleanup(func() { defaultLogger = saved }) + return &buffer +} + type baseTestCase struct { description string message string @@ -35,12 +44,10 @@ func TestLoggerDebugf(t *testing.T) { message := testCase.message + testCase.suffix testCase.wantedPattern = fmt.Sprintf(`^\[DBG\] \w+\.go:\d+: %s\n$`, testCase.message) t.Run(testCase.description, func(t *testing.T) { - var buffer bytes.Buffer - testLogger := newLogger(&buffer) - testLogger.setLevel(debugLevel) - testLogger.Debugf("%s", message) - got := buffer.String() - assert.Regexp(t, testCase.wantedPattern, got) + buffer := captureLog(t) + defaultLogger.setLevel(debugLevel) + Debugf("%s", message) + assert.Regexp(t, testCase.wantedPattern, buffer.String()) }) } } @@ -51,11 +58,9 @@ func TestLoggerInfof(t *testing.T) { message := testCase.message + testCase.suffix testCase.wantedPattern = fmt.Sprintf(`^\[INF\] %s\n$`, testCase.message) t.Run(testCase.description, func(t *testing.T) { - var buffer bytes.Buffer - testLogger := newLogger(&buffer) - testLogger.Infof("%s", message) - got := buffer.String() - assert.Regexp(t, testCase.wantedPattern, got) + buffer := captureLog(t) + Infof("%s", message) + assert.Regexp(t, testCase.wantedPattern, buffer.String()) }) } } @@ -66,11 +71,9 @@ func TestLoggerWarnf(t *testing.T) { message := testCase.message + testCase.suffix testCase.wantedPattern = fmt.Sprintf(`^\[WRN\] %s\n$`, testCase.message) t.Run(testCase.description, func(t *testing.T) { - var buffer bytes.Buffer - testLogger := newLogger(&buffer) - testLogger.Warnf("%s", message) - got := buffer.String() - assert.Regexp(t, testCase.wantedPattern, got) + buffer := captureLog(t) + Warnf("%s", message) + assert.Regexp(t, testCase.wantedPattern, buffer.String()) }) } } @@ -80,21 +83,20 @@ func TestLoggerWithLowerLevels(t *testing.T) { ops := []struct { name string level logLevel - logFunc func(*logger) + logFunc func() }{ - {"Debugf", debugLevel, func(testLogger *logger) { testLogger.Debugf("hello") }}, - {"Infof", infoLevel, func(testLogger *logger) { testLogger.Infof("hello") }}, - {"Warnf", warnLevel, func(testLogger *logger) { testLogger.Warnf("hello") }}, + {"Debugf", debugLevel, func() { Debugf("hello") }}, + {"Infof", infoLevel, func() { Infof("hello") }}, + {"Warnf", warnLevel, func() { Warnf("hello") }}, } for _, setLevel := range levels { for _, operation := range ops { - var buffer bytes.Buffer - testLogger := newLogger(&buffer) - testLogger.setLevel(setLevel) + buffer := captureLog(t) + defaultLogger.setLevel(setLevel) expectedOutput := operation.level >= setLevel - operation.logFunc(testLogger) + operation.logFunc() output := buffer.String() if expectedOutput { @@ -107,31 +109,26 @@ func TestLoggerWithLowerLevels(t *testing.T) { } func TestDefaultLevelIsInfo(t *testing.T) { - var buffer bytes.Buffer - testLogger := newLogger(&buffer) + buffer := captureLog(t) - testLogger.Debugf("debug msg") + Debugf("debug msg") assert.Empty(t, buffer.String(), "Debug should be suppressed at default infoLevel") - testLogger.Infof("info msg") + Infof("info msg") assert.Contains(t, buffer.String(), "info msg") } func TestDebugIncludesFileLine(t *testing.T) { - var buffer bytes.Buffer - testLogger := newLogger(&buffer) - testLogger.setLevel(debugLevel) - testLogger.Debugf("test location") - got := buffer.String() - assert.Regexp(t, `^\[DBG\] logger_test\.go:\d+: test location\n$`, got) + buffer := captureLog(t) + defaultLogger.setLevel(debugLevel) + Debugf("test location") + assert.Regexp(t, `^\[DBG\] logger_test\.go:\d+: test location\n$`, buffer.String()) } func TestMultilineMessageIndented(t *testing.T) { - var buffer bytes.Buffer - testLogger := newLogger(&buffer) - testLogger.Warnf("line1\nline2\nline3") - got := buffer.String() - assert.Equal(t, "[WRN] line1\n line2\n line3\n", got) + buffer := captureLog(t) + Warnf("line1\nline2\nline3") + assert.Equal(t, "[WRN] line1\n line2\n line3\n", buffer.String()) } func TestSetLevelInvalidPanics(t *testing.T) { diff --git a/internal/masterkey/abe_windows.go b/internal/masterkey/abe_windows.go index 4de3c16..7012440 100644 --- a/internal/masterkey/abe_windows.go +++ b/internal/masterkey/abe_windows.go @@ -30,12 +30,12 @@ func (abeRetriever) Version() Version { return V20 } func (abeRetriever) Retrieve(_ context.Context, loc Locator) ([]byte, error) { // Non-ABE forks (Opera/Vivaldi/Yandex) have no ABE kind; pre-v20 Chrome takes the errNoABEKey path below. if loc.ABE == ABENone { - return nil, ErrNotApplicable + return nil, errNotApplicable } encKey, err := loadEncryptedKey(loc.LocalState) if errors.Is(err, errNoABEKey) { - return nil, ErrNotApplicable + return nil, errNotApplicable } if err != nil { return nil, err diff --git a/internal/masterkey/dpapi_other.go b/internal/masterkey/dpapi_other.go index ea5a101..4cacb7a 100644 --- a/internal/masterkey/dpapi_other.go +++ b/internal/masterkey/dpapi_other.go @@ -8,5 +8,5 @@ import ( ) func DecryptDPAPI(_ []byte) ([]byte, error) { - return nil, fmt.Errorf("DPAPI on %s: %w", runtime.GOOS, ErrNotApplicable) + return nil, fmt.Errorf("DPAPI on %s: %w", runtime.GOOS, errNotApplicable) } diff --git a/internal/masterkey/gcoredump_darwin.go b/internal/masterkey/gcoredump_darwin.go index 34b86d3..47f00fa 100644 --- a/internal/masterkey/gcoredump_darwin.go +++ b/internal/masterkey/gcoredump_darwin.go @@ -58,8 +58,8 @@ type addressRange struct { end uint64 } -// DecryptKeychainRecords requires root. -func DecryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { +// decryptKeychainRecords requires root. +func decryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { if os.Geteuid() != 0 { return nil, errors.New("requires root privileges") } diff --git a/internal/masterkey/gcoredump_stub_darwin.go b/internal/masterkey/gcoredump_stub_darwin.go index 83b420d..a764922 100644 --- a/internal/masterkey/gcoredump_stub_darwin.go +++ b/internal/masterkey/gcoredump_stub_darwin.go @@ -8,7 +8,7 @@ import ( "github.com/moond4rk/keychainbreaker" ) -// DecryptKeychainRecords steps aside in default builds, which leave out the securityd dump (-tags keychain_gcore). -func DecryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { +// decryptKeychainRecords steps aside in default builds, which leave out the securityd dump (-tags keychain_gcore). +func decryptKeychainRecords() ([]keychainbreaker.GenericPassword, error) { return nil, errors.New("keychain gcore dump not built in (rebuild with -tags keychain_gcore)") } diff --git a/internal/masterkey/keyfile.go b/internal/masterkey/keyfile.go index 90c8b25..81af12c 100644 --- a/internal/masterkey/keyfile.go +++ b/internal/masterkey/keyfile.go @@ -10,7 +10,7 @@ import ( "time" ) -const KeyFileVersion = "2" +const keyFileVersion = "2" // KeyFile is keys.json: produced on one host, it decrypts copied profile data on another. type KeyFile struct { @@ -41,7 +41,7 @@ type Vault struct { func NewKeyFile() KeyFile { return KeyFile{ - Version: KeyFileVersion, + Version: keyFileVersion, CreatedAt: time.Now().UTC(), Host: currentHost(), Vaults: []Vault{}, @@ -75,8 +75,8 @@ func ReadKeyFile(reader io.Reader) (KeyFile, error) { if err := decoder.Decode(&dump); err != nil { return KeyFile{}, fmt.Errorf("decode key file: %w", err) } - if dump.Version != KeyFileVersion { - return KeyFile{}, fmt.Errorf("unsupported key file version %q (this build expects %q)", dump.Version, KeyFileVersion) + if dump.Version != keyFileVersion { + return KeyFile{}, fmt.Errorf("unsupported key file version %q (this build expects %q)", dump.Version, keyFileVersion) } return dump, nil } diff --git a/internal/masterkey/keys_golden_test.go b/internal/masterkey/keys_golden_test.go index bd72192..3abc697 100644 --- a/internal/masterkey/keys_golden_test.go +++ b/internal/masterkey/keys_golden_test.go @@ -42,7 +42,7 @@ func keysFreeze(t *testing.T, keyFile masterkey.KeyFile, host masterkey.Host) ma func keysVaultsFile(t *testing.T) masterkey.KeyFile { t.Helper() return masterkey.KeyFile{ - Version: masterkey.KeyFileVersion, + Version: "2", CreatedAt: keysGoldenCreatedAt, Host: masterkey.Host{OS: "windows", Arch: "amd64", Hostname: "GOLDEN-PC", User: `GOLDEN-PC\Jürgen`}, Vaults: []masterkey.Vault{ diff --git a/internal/masterkey/masterkey.go b/internal/masterkey/masterkey.go index 3e25a51..af3b295 100644 --- a/internal/masterkey/masterkey.go +++ b/internal/masterkey/masterkey.go @@ -21,14 +21,14 @@ const ( // Set holds one user data dir's key per version; encoding/json writes it as keys.json's "keys" object. type Set map[Version][]byte -// Retriever obtains one version's key from one OS secret store. -type Retriever interface { +// keyRetriever obtains one version's key from one OS secret store. +type keyRetriever interface { Version() Version Retrieve(ctx context.Context, loc Locator) ([]byte, error) } -// ErrNotApplicable is a retriever's way of stepping aside; it never counts as a failure. -var ErrNotApplicable = errors.New("retriever not applicable") +// errNotApplicable is a retriever's way of stepping aside; it never counts as a failure. +var errNotApplicable = errors.New("retriever not applicable") var errStorageNotFound = errors.New("not found in credential store") //nolint:unused // only used on darwin and linux @@ -62,7 +62,7 @@ func RetrieveAll(ctx context.Context, locator Locator) (Set, error) { return retrieveAll(ctx, locator, platformRetrievers) } -func retrieveAll(ctx context.Context, locator Locator, retrievers []Retriever) (Set, error) { +func retrieveAll(ctx context.Context, locator Locator, retrievers []keyRetriever) (Set, error) { keys := make(Set) var versions []Version failures := make(map[Version][]error) @@ -77,7 +77,7 @@ func retrieveAll(ctx context.Context, locator Locator, retrievers []Retriever) ( } key, err := retriever.Retrieve(ctx, locator) switch { - case errors.Is(err, ErrNotApplicable): + case errors.Is(err, errNotApplicable): case err != nil: log.Debugf("%s retriever %T failed: %v", version, retriever, err) failures[version] = append(failures[version], err) diff --git a/internal/masterkey/masterkey_test.go b/internal/masterkey/masterkey_test.go index a6bf935..07a6d41 100644 --- a/internal/masterkey/masterkey_test.go +++ b/internal/masterkey/masterkey_test.go @@ -75,7 +75,7 @@ func TestRetrieveAll_FirstKeyWinsAndStopsTheVersion(t *testing.T) { winner := &fakeRetriever{version: V10, key: v10Key} later := &fakeRetriever{version: V10, key: bytes.Repeat([]byte{0xFF}, 16)} - got, err := retrieveAll(context.Background(), Locator{}, []Retriever{failing, winner, later}) + got, err := retrieveAll(context.Background(), Locator{}, []keyRetriever{failing, winner, later}) require.NoError(t, err, "a strategy that failed before a later one succeeded is not an error") assert.Equal(t, Set{V10: v10Key}, got) assert.Equal(t, []int{1, 1, 0}, []int{failing.calls, winner.calls, later.calls}) @@ -83,7 +83,7 @@ func TestRetrieveAll_FirstKeyWinsAndStopsTheVersion(t *testing.T) { func TestRetrieveAll_VersionsAreIndependent(t *testing.T) { v20Retriever := &fakeRetriever{version: V20, err: errors.New("abe: inject failed")} - got, err := retrieveAll(context.Background(), Locator{}, []Retriever{ + got, err := retrieveAll(context.Background(), Locator{}, []keyRetriever{ &fakeRetriever{version: V10, key: v10Key}, v20Retriever, }) @@ -95,7 +95,7 @@ func TestRetrieveAll_VersionsAreIndependent(t *testing.T) { func TestRetrieveAll_ErrorOnlyWhenEveryRetrieverFails(t *testing.T) { first := errors.New("keychain: not found") second := errors.New("security command: denied") - _, err := retrieveAll(context.Background(), Locator{}, []Retriever{ + _, err := retrieveAll(context.Background(), Locator{}, []keyRetriever{ &fakeRetriever{version: V10, err: first}, &fakeRetriever{version: V10, err: second}, }) @@ -105,9 +105,9 @@ func TestRetrieveAll_ErrorOnlyWhenEveryRetrieverFails(t *testing.T) { } func TestRetrieveAll_NotApplicableIsSilent(t *testing.T) { - got, err := retrieveAll(context.Background(), Locator{}, []Retriever{ - &fakeRetriever{version: V10, err: ErrNotApplicable}, - &fakeRetriever{version: V20, err: ErrNotApplicable}, + got, err := retrieveAll(context.Background(), Locator{}, []keyRetriever{ + &fakeRetriever{version: V10, err: errNotApplicable}, + &fakeRetriever{version: V20, err: errNotApplicable}, &fakeRetriever{version: V11}, }) require.NoError(t, err) @@ -117,13 +117,13 @@ func TestRetrieveAll_NotApplicableIsSilent(t *testing.T) { func TestRetrieveAll_PassesTheLocator(t *testing.T) { retriever := &fakeRetriever{version: V10, key: v10Key} locator := Locator{LocalState: "/tmp/Local State", SecretLabel: "Chrome", Executable: "chrome.exe", ABE: ABEChromeBase} - _, err := retrieveAll(context.Background(), locator, []Retriever{retriever}) + _, err := retrieveAll(context.Background(), locator, []keyRetriever{retriever}) require.NoError(t, err) assert.Equal(t, locator, retriever.gotLoc) } -func asRetrievers(fakes []*fakeRetriever) []Retriever { - retrievers := make([]Retriever, 0, len(fakes)) +func asRetrievers(fakes []*fakeRetriever) []keyRetriever { + retrievers := make([]keyRetriever, 0, len(fakes)) for _, fake := range fakes { retrievers = append(retrievers, fake) } diff --git a/internal/masterkey/retriever_darwin.go b/internal/masterkey/retriever_darwin.go index dd14947..4f68455 100644 --- a/internal/masterkey/retriever_darwin.go +++ b/internal/masterkey/retriever_darwin.go @@ -31,7 +31,7 @@ var darwinParams = pbkdf2Params{ const securityCmdTimeout = 30 * time.Second // platformRetrievers stop at the first success; the security CLI goes last because it may prompt. -var platformRetrievers = []Retriever{ +var platformRetrievers = []keyRetriever{ &gcoredumpRetriever{}, keychainRetriever{}, &securityRetriever{cache: make(map[string]securityResult)}, @@ -49,17 +49,17 @@ func (*gcoredumpRetriever) Version() Version { return V10 } // Retrieve steps aside on failure: the common "needs root" case isn't warning-worthy and would drown real warnings. func (r *gcoredumpRetriever) Retrieve(_ context.Context, locator Locator) ([]byte, error) { r.once.Do(func() { - r.records, r.err = DecryptKeychainRecords() + r.records, r.err = decryptKeychainRecords() }) if r.err != nil { log.Debugf("gcoredump: %v", r.err) - return nil, ErrNotApplicable + return nil, errNotApplicable } key, err := findStorageKey(r.records, locator.SecretLabel) if err != nil { log.Debugf("gcoredump: %v", err) - return nil, ErrNotApplicable + return nil, errNotApplicable } return key, nil } @@ -80,11 +80,11 @@ func (keychainRetriever) Version() Version { return V10 } func (keychainRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, error) { if locator.Keychain == nil { - return nil, ErrNotApplicable + return nil, errNotApplicable } secret, err := locator.Keychain.GenericPassword(ctx, locator.SecretLabel) if errors.Is(err, keychain.ErrLocked) { - return nil, ErrNotApplicable + return nil, errNotApplicable } if err != nil { return nil, err diff --git a/internal/masterkey/retriever_darwin_test.go b/internal/masterkey/retriever_darwin_test.go index a3389a2..5f223e3 100644 --- a/internal/masterkey/retriever_darwin_test.go +++ b/internal/masterkey/retriever_darwin_test.go @@ -62,13 +62,13 @@ func TestKeychainRetriever(t *testing.T) { t.Run("no keychain steps aside", func(t *testing.T) { _, err := keychainRetriever{}.Retrieve(ctx, Locator{SecretLabel: "Chrome"}) - require.ErrorIs(t, err, ErrNotApplicable) + require.ErrorIs(t, err, errNotApplicable) }) t.Run("locked keychain steps aside", func(t *testing.T) { loginKeychain := &fakeKeychain{err: fmt.Errorf("%w: wrong password", keychain.ErrLocked)} _, err := keychainRetriever{}.Retrieve(ctx, locatorFor(loginKeychain)) - require.ErrorIs(t, err, ErrNotApplicable) + require.ErrorIs(t, err, errNotApplicable) }) t.Run("secret derives the v10 key", func(t *testing.T) { @@ -82,7 +82,7 @@ func TestKeychainRetriever(t *testing.T) { t.Run("missing label is an error", func(t *testing.T) { _, err := keychainRetriever{}.Retrieve(ctx, locatorFor(&fakeKeychain{secrets: map[string][]byte{}})) require.Error(t, err) - assert.NotErrorIs(t, err, ErrNotApplicable) + assert.NotErrorIs(t, err, errNotApplicable) }) } diff --git a/internal/masterkey/retriever_linux.go b/internal/masterkey/retriever_linux.go index 85f9e71..08a771e 100644 --- a/internal/masterkey/retriever_linux.go +++ b/internal/masterkey/retriever_linux.go @@ -20,7 +20,7 @@ var linuxParams = pbkdf2Params{ } // platformRetrievers run both: a profile holds v10 and v11 values once its host moved between headless and keyring. -var platformRetrievers = []Retriever{posixRetriever{}, dbusRetriever{}} +var platformRetrievers = []keyRetriever{posixRetriever{}, dbusRetriever{}} type dbusRetriever struct{} diff --git a/internal/masterkey/retriever_windows.go b/internal/masterkey/retriever_windows.go index 136710f..0fed5c3 100644 --- a/internal/masterkey/retriever_windows.go +++ b/internal/masterkey/retriever_windows.go @@ -14,7 +14,7 @@ import ( ) // platformRetrievers run both: a profile upgraded past Chrome 127 holds v10 and v20 values side by side. -var platformRetrievers = []Retriever{dpapiRetriever{}, abeRetriever{}} +var platformRetrievers = []keyRetriever{dpapiRetriever{}, abeRetriever{}} type dpapiRetriever struct{} diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 4b261ad..e17dbbe 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -19,46 +19,46 @@ type File struct { IsDir bool } -// Dir is a snapshot directory, laid out as //: one Snapshot per user data dir. -type Dir struct { +// Root is the snapshot directory, laid out as //: one Snapshot per user data dir. +type Root struct { path string temp bool failed map[string]error // keyed by the cleaned /, so any spelling of a file finds its failure } // Temp creates a private temporary snapshot directory, which Close removes. -func Temp() (*Dir, error) { +func Temp() (*Root, error) { path, err := os.MkdirTemp("", "hbd-snapshot-*") if err != nil { return nil, fmt.Errorf("create snapshot dir: %w", err) } - return &Dir{path: path, temp: true, failed: make(map[string]error)}, nil + return &Root{path: path, temp: true, failed: make(map[string]error)}, nil } // Open uses an existing snapshot directory in place; Close leaves it there. -func Open(path string) *Dir { - return &Dir{path: path, failed: make(map[string]error)} +func Open(path string) *Root { + return &Root{path: path, failed: make(map[string]error)} } // Unzip extracts an archive into a temporary snapshot directory, rejecting entries that would land outside it. -func Unzip(archivePath string) (*Dir, error) { - snapshotDir, err := Temp() +func Unzip(archivePath string) (*Root, error) { + root, err := Temp() if err != nil { return nil, err } - if err := zipfile.Extract(archivePath, snapshotDir.path); err != nil { - return nil, errors.Join(err, snapshotDir.Close()) + if err := zipfile.Extract(archivePath, root.path); err != nil { + return nil, errors.Join(err, root.Close()) } - return snapshotDir, nil + return root, nil } -func (d *Dir) Path() string { - return d.path +func (r *Root) Path() string { + return r.path } // Capture keeps a file's own failure for Snapshot.Path instead of stopping the rest of the capture. -func (d *Dir) Capture(ctx context.Context, files []File) error { - if err := os.MkdirAll(d.path, 0o700); err != nil { +func (r *Root) Capture(ctx context.Context, files []File) error { + if err := os.MkdirAll(r.path, 0o700); err != nil { return fmt.Errorf("snapshot dir: %w", err) } for _, file := range files { @@ -69,40 +69,40 @@ func (d *Dir) Capture(ctx context.Context, files []File) error { if err != nil { continue // Snapshot.Path reports the same error for this file } - if err := d.capture(local, file); err != nil { - d.failed[local] = err + if err := r.capture(local, file); err != nil { + r.failed[local] = err } else { - delete(d.failed, local) + delete(r.failed, local) } } return nil } -func (d *Dir) capture(local string, file File) error { - target := filepath.Join(d.path, local) +func (r *Root) capture(local string, file File) error { + target := filepath.Join(r.path, local) if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { return fmt.Errorf("create %s: %w", filepath.Dir(target), err) } return copyPath(filepath.Join(file.UserDataDirPath, filepath.FromSlash(file.RelativePath)), target, file.IsDir) } -func (d *Dir) Snapshot(userDataDirID string) Snapshot { - return Snapshot{userDataDirID: userDataDirID, root: d.path, failed: d.failed} +func (r *Root) Snapshot(userDataDirID string) Snapshot { + return Snapshot{userDataDirID: userDataDirID, rootPath: r.path, failed: r.failed} } -func (d *Dir) Close() error { - if !d.temp { +func (r *Root) Close() error { + if !r.temp { return nil } - if err := os.RemoveAll(d.path); err != nil { - return fmt.Errorf("remove snapshot dir %s: %w", d.path, err) + if err := os.RemoveAll(r.path); err != nil { + return fmt.Errorf("remove snapshot dir %s: %w", r.path, err) } return nil } type Snapshot struct { userDataDirID string - root string + rootPath string failed map[string]error } @@ -115,7 +115,7 @@ func (s Snapshot) Path(relativePath string) (string, error) { if err, ok := s.failed[local]; ok { return "", err } - fullPath := filepath.Join(s.root, local) + fullPath := filepath.Join(s.rootPath, local) if _, err := os.Lstat(fullPath); err != nil { return "", err } diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index c40c4d1..308a272 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -32,47 +32,47 @@ func userDataDir(t *testing.T) string { } func TestTemp_IsPrivateAndCloseRemovesIt(t *testing.T) { - snapshotDir, err := Temp() + root, err := Temp() require.NoError(t, err) - info, err := os.Stat(snapshotDir.Path()) + info, err := os.Stat(root.Path()) require.NoError(t, err) if runtime.GOOS != "windows" { assert.Equal(t, fs.FileMode(0o700), info.Mode().Perm()) } - require.NoError(t, snapshotDir.Close()) - assert.NoDirExists(t, snapshotDir.Path()) + require.NoError(t, root.Close()) + assert.NoDirExists(t, root.Path()) } func TestOpen_ReadsInPlaceAndCloseLeavesIt(t *testing.T) { dir := t.TempDir() writeFile(t, filepath.Join(dir, "chrome", "Local State"), []byte("{}")) - snapshotDir := Open(dir) - capturedPath, err := snapshotDir.Snapshot("chrome").Path("Local State") + root := Open(dir) + capturedPath, err := root.Snapshot("chrome").Path("Local State") require.NoError(t, err) assert.Equal(t, filepath.Join(dir, "chrome", "Local State"), capturedPath) - require.NoError(t, snapshotDir.Close()) + require.NoError(t, root.Close()) assert.FileExists(t, capturedPath) } func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) { from := userDataDir(t) - snapshotDir, err := Temp() + root, err := Temp() require.NoError(t, err) - defer snapshotDir.Close() + defer root.Close() - require.NoError(t, snapshotDir.Capture(context.Background(), []File{ + require.NoError(t, root.Capture(context.Background(), []File{ {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Local State"}, {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Network/Cookies"}, {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Local Storage/leveldb", IsDir: true}, })) - dirSnapshot := snapshotDir.Snapshot("chrome") + dirSnapshot := root.Snapshot("chrome") cookies, err := dirSnapshot.Path("Default/Network/Cookies") require.NoError(t, err) - assert.Equal(t, filepath.Join(snapshotDir.Path(), "chrome", "Default", "Network", "Cookies"), cookies) + assert.Equal(t, filepath.Join(root.Path(), "chrome", "Default", "Network", "Cookies"), cookies) for suffix, want := range map[string]string{"-wal": "wal", "-shm": "shm"} { got, err := os.ReadFile(cookies + suffix) require.NoError(t, err) @@ -88,17 +88,17 @@ func TestCapture_FilesWithSidecarsAndDirsWithoutLocks(t *testing.T) { func TestCapture_KeepsGoingPastFailedFiles(t *testing.T) { from := userDataDir(t) - snapshotDir, err := Temp() + root, err := Temp() require.NoError(t, err) - defer snapshotDir.Close() + defer root.Close() - require.NoError(t, snapshotDir.Capture(context.Background(), []File{ + require.NoError(t, root.Capture(context.Background(), []File{ {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/History"}, // vanished before Capture reached it {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/Network"}, // a directory read as a file, so the copy fails {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Local State"}, })) - dirSnapshot := snapshotDir.Snapshot("chrome") + dirSnapshot := root.Snapshot("chrome") _, err = dirSnapshot.Path("Default/History") require.ErrorIs(t, err, fs.ErrNotExist) @@ -112,26 +112,26 @@ func TestCapture_KeepsGoingPastFailedFiles(t *testing.T) { func TestCapture_StopsWhenCancelled(t *testing.T) { from := userDataDir(t) - snapshotDir, err := Temp() + root, err := Temp() require.NoError(t, err) - defer snapshotDir.Close() + defer root.Close() ctx, cancel := context.WithCancel(context.Background()) cancel() - err = snapshotDir.Capture(ctx, []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Local State"}}) + err = root.Capture(ctx, []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Local State"}}) require.ErrorIs(t, err, context.Canceled) - _, err = snapshotDir.Snapshot("chrome").Path("Local State") + _, err = root.Snapshot("chrome").Path("Local State") require.ErrorIs(t, err, fs.ErrNotExist) } func TestCapture_StaysInsideItsOwnSnapshot(t *testing.T) { from := userDataDir(t) - snapshotDir, err := Temp() + root, err := Temp() require.NoError(t, err) - defer snapshotDir.Close() + defer root.Close() - require.NoError(t, snapshotDir.Capture(context.Background(), []File{ + require.NoError(t, root.Capture(context.Background(), []File{ {UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "../edge/Local State"}, {UserDataDirID: "../chrome", UserDataDirPath: from, RelativePath: "Local State"}, {UserDataDirID: "chrome/sub", UserDataDirPath: from, RelativePath: "Local State"}, @@ -139,39 +139,39 @@ func TestCapture_StaysInsideItsOwnSnapshot(t *testing.T) { {UserDataDirID: "", UserDataDirPath: from, RelativePath: "Local State"}, })) - _, err = snapshotDir.Snapshot("chrome").Path("../edge/Local State") + _, err = root.Snapshot("chrome").Path("../edge/Local State") require.Error(t, err) - entries, err := os.ReadDir(snapshotDir.Path()) + entries, err := os.ReadDir(root.Path()) require.NoError(t, err) assert.Empty(t, entries, "nothing may be written outside a file's own snapshot") } func TestSnapshot_UncapturedFileIsNotExist(t *testing.T) { - snapshotDir, err := Temp() + root, err := Temp() require.NoError(t, err) - defer snapshotDir.Close() + defer root.Close() - _, err = snapshotDir.Snapshot("chrome").Path("Default/Login Data") + _, err = root.Snapshot("chrome").Path("Default/Login Data") require.ErrorIs(t, err, fs.ErrNotExist) } func TestCapture_ALaterCaptureReplacesAnEarlierFailure(t *testing.T) { from := t.TempDir() - snapshotDir, err := Temp() + root, err := Temp() require.NoError(t, err) - defer snapshotDir.Close() + defer root.Close() history := filepath.Join(from, "Default", "History") require.NoError(t, os.MkdirAll(history, 0o700)) // a directory read as a file, so the copy fails - require.NoError(t, snapshotDir.Capture(context.Background(), []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/History"}})) - _, err = snapshotDir.Snapshot("chrome").Path("Default/./History") + require.NoError(t, root.Capture(context.Background(), []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/History"}})) + _, err = root.Snapshot("chrome").Path("Default/./History") require.Error(t, err) require.NotErrorIs(t, err, fs.ErrNotExist, "a failure is found under any spelling of the path") require.NoError(t, os.Remove(history)) writeFile(t, history, []byte("history")) - require.NoError(t, snapshotDir.Capture(context.Background(), []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/./History"}})) - _, err = snapshotDir.Snapshot("chrome").Path("Default/History") + require.NoError(t, root.Capture(context.Background(), []File{{UserDataDirID: "chrome", UserDataDirPath: from, RelativePath: "Default/./History"}})) + _, err = root.Snapshot("chrome").Path("Default/History") require.NoError(t, err) } diff --git a/internal/snapshot/zip.go b/internal/snapshot/zip.go index 932903a..2bfd725 100644 --- a/internal/snapshot/zip.go +++ b/internal/snapshot/zip.go @@ -8,16 +8,16 @@ import ( "github.com/moond4rk/hackbrowserdata/internal/zipfile" ) -func (d *Dir) Zip(archivePath string) error { +func (r *Root) Zip(archivePath string) error { var names []string - walkErr := filepath.WalkDir(d.path, func(walkedPath string, entry fs.DirEntry, err error) error { + walkErr := filepath.WalkDir(r.path, func(walkedPath string, entry fs.DirEntry, err error) error { if err != nil { return err } if entry.IsDir() { return nil } - relativePath, err := filepath.Rel(d.path, walkedPath) + relativePath, err := filepath.Rel(r.path, walkedPath) if err != nil { return err } @@ -25,7 +25,7 @@ func (d *Dir) Zip(archivePath string) error { return nil }) if walkErr != nil { - return fmt.Errorf("zip %s: %w", d.path, walkErr) + return fmt.Errorf("zip %s: %w", r.path, walkErr) } - return zipfile.Write(archivePath, d.path, names) + return zipfile.Write(archivePath, r.path, names) } diff --git a/internal/snapshot/zip_test.go b/internal/snapshot/zip_test.go index 3e40c0b..24fc5dc 100644 --- a/internal/snapshot/zip_test.go +++ b/internal/snapshot/zip_test.go @@ -31,15 +31,15 @@ func TestZipUnzip_RoundTrip(t *testing.T) { } require.NoError(t, zipReader.Close()) - snapshotDir, err := Unzip(archive) + root, err := Unzip(archive) require.NoError(t, err) for relativePath, want := range files { - got, err := os.ReadFile(filepath.Join(snapshotDir.Path(), filepath.FromSlash(relativePath))) + got, err := os.ReadFile(filepath.Join(root.Path(), filepath.FromSlash(relativePath))) require.NoError(t, err, relativePath) assert.True(t, bytes.Equal(want, got), "%s: got %d bytes, want %d", relativePath, len(got), len(want)) } - require.NoError(t, snapshotDir.Close()) - assert.NoDirExists(t, snapshotDir.Path()) + require.NoError(t, root.Close()) + assert.NoDirExists(t, root.Path()) } func TestZip_MissingSnapshotDirFails(t *testing.T) { diff --git a/rfcs/001-architecture.md b/rfcs/001-architecture.md index 4a96f92..bbd5a1d 100644 --- a/rfcs/001-architecture.md +++ b/rfcs/001-architecture.md @@ -32,9 +32,10 @@ Dependencies point down only. Interfaces live with their consumer, nothing regis ## Naming -- A name is judged at its call site, qualified by its package, and never repeats the package's name. +- A name is judged at its call site, qualified by its package, and never repeats the package's name, unless it names the one type the package exists for. - A name says what a thing is, not its role or its shape, and one concept has one word. - Names are spelled out; only Go's universal idioms stay short, and lint enforces it. - The domain's words: a **browser** is a row of the browser table; its **base** is what it is built on (Chromium, Firefox, or Safari); a **user data dir** is a browser's data directory, where an installation would be the program; and a **profile**, an **extraction**, a **snapshot**, a **record**, and a **category** mean what they say. +- Unqualified, "dir" means a user data dir; any other directory is named for what it holds. **Rejected:** "engine" for the base, which means the renderer; "origin" or "owner" for where a record came from, which are web and access-control terms; and "job" for an extraction, which suggests a worker pool that does not exist.