From c7b262f9b7a1c274a3f259723b1cf2b8c9248c76 Mon Sep 17 00:00:00 2001 From: moonD4rk Date: Thu, 19 Nov 2026 18:55:13 +0800 Subject: [PATCH 1/2] feat(masterkey): decrypt Chromium v12 portal keys v12 derives its key with HKDF-SHA256 over the XDG desktop portal's per-app secret, read via the Secret Service; v10/v11 stay unchanged. Closes #580 --- internal/browser/browser.go | 1 + internal/browser/chromium/chromium.go | 32 ++++ internal/browser/chromium/chromium_test.go | 27 ++++ internal/browser/chromium/decrypt.go | 8 +- internal/browser/chromium/decrypt_test.go | 29 +++- internal/browser/table.go | 4 + internal/crypto/hkdf.go | 30 ++++ internal/crypto/hkdf_test.go | 63 ++++++++ internal/masterkey/masterkey.go | 6 +- internal/masterkey/retriever_linux.go | 175 +++++++++++++++++++-- internal/masterkey/retriever_linux_test.go | 114 +++++++++++++- 11 files changed, 460 insertions(+), 29 deletions(-) create mode 100644 internal/crypto/hkdf.go create mode 100644 internal/crypto/hkdf_test.go diff --git a/internal/browser/browser.go b/internal/browser/browser.go index a48735a..7e51eda 100644 --- a/internal/browser/browser.go +++ b/internal/browser/browser.go @@ -32,6 +32,7 @@ const ( type Platform struct { UserDataDirs []string // slash-separated, relative to the home directory; globs allowed SecretLabel string // macOS Keychain account / Linux Secret Service label; "" = none + PortalAppID string // Linux: the app id whose XDG portal secret decrypts v12 values; "" = none Executable string // Windows: the program the ABE payload is injected into ExecutableFallbacks []string // Windows: program paths tried when the registry has no App Paths entry ABE masterkey.ABEKind diff --git a/internal/browser/chromium/chromium.go b/internal/browser/chromium/chromium.go index 56237e9..08b0f69 100644 --- a/internal/browser/chromium/chromium.go +++ b/internal/browser/chromium/chromium.go @@ -7,6 +7,7 @@ import ( "io/fs" "os" "path/filepath" + "strings" "github.com/moond4rk/hackbrowserdata/internal/browser" "github.com/moond4rk/hackbrowserdata/internal/masterkey" @@ -164,6 +165,7 @@ func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterk platform := dir.Browser.Platform() locator := masterkey.Locator{ SecretLabel: platform.SecretLabel, Executable: platform.Executable, ExecutableFallbacks: platform.ExecutableFallbacks, ABE: platform.ABE, + PortalAppIDs: portalAppIDs(dir.Path, platform.PortalAppID), } path, err := dirSnapshot.Path(localState.Path) switch { @@ -175,6 +177,36 @@ func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterk return locator, nil } +// portalAppIDs lists the v12 app id candidates for a dir, most specific first: a Flatpak install's own id, taken +// from its .var/app// path, then the browser's registered id. Empty ids and duplicates are dropped. +func portalAppIDs(dirPath, registeredID string) []string { + var ids []string + add := func(id string) { + if id == "" { + return + } + for _, existing := range ids { + if existing == id { + return + } + } + ids = append(ids, id) + } + add(flatpakAppID(dirPath)) + add(registeredID) + return ids +} + +// flatpakAppID returns the Flatpak application id in a path like ".../.var/app//config/...", or "" if absent. +func flatpakAppID(dirPath string) string { + _, after, found := strings.Cut(filepath.ToSlash(dirPath), ".var/app/") + if !found { + return "" + } + id, _, _ := strings.Cut(after, "/") + return id +} + // KeySources are the files KeyLocator reads from a snapshot. func KeySources() []browser.Source { return []browser.Source{localState} diff --git a/internal/browser/chromium/chromium_test.go b/internal/browser/chromium/chromium_test.go index 155b9c6..2213767 100644 --- a/internal/browser/chromium/chromium_test.go +++ b/internal/browser/chromium/chromium_test.go @@ -166,3 +166,30 @@ func TestKeyLocator(t *testing.T) { require.NoError(t, err, "a user data dir without Local State still has keys on macOS and Linux") assert.Empty(t, locator.LocalState) } + +func TestPortalAppIDs(t *testing.T) { + tests := []struct { + name string + dirPath string + registeredID string + want []string + }{ + {name: "deb install uses the table id", dirPath: "/home/u/.config/google-chrome", registeredID: "com.google.Chrome", want: []string{"com.google.Chrome"}}, + { + name: "flatpak install is tried before the table id", registeredID: "org.chromium.Chromium", + dirPath: "/home/u/.var/app/io.github.ungoogled_software.ungoogled_chromium/config/chromium", + want: []string{"io.github.ungoogled_software.ungoogled_chromium", "org.chromium.Chromium"}, + }, + { + name: "matching flatpak and table id collapse to one", registeredID: "com.google.Chrome", + dirPath: "/home/u/.var/app/com.google.Chrome/config/google-chrome", want: []string{"com.google.Chrome"}, + }, + {name: "no table id leaves only the flatpak id", dirPath: "/home/u/.var/app/com.brave.Browser/config/BraveSoftware/Brave-Browser", want: []string{"com.brave.Browser"}}, + {name: "no candidates for a browser without a portal id", dirPath: "/home/u/.config/microsoft-edge", want: nil}, + } + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + assert.Equal(t, testCase.want, portalAppIDs(testCase.dirPath, testCase.registeredID)) + }) + } +} diff --git a/internal/browser/chromium/decrypt.go b/internal/browser/chromium/decrypt.go index b7b569d..c88d117 100644 --- a/internal/browser/chromium/decrypt.go +++ b/internal/browser/chromium/decrypt.go @@ -28,10 +28,10 @@ func decryptValue(masterKeys masterkey.Set, ciphertext []byte) ([]byte, error) { return decryptCBC(masterKeys[masterkey.V10], ciphertext) case masterkey.V11: return decryptCBC(masterKeys[masterkey.V11], ciphertext) + case masterkey.V12: + return decryptGCM(masterKeys[masterkey.V12], ciphertext) case masterkey.V20: return decryptGCM(masterKeys[masterkey.V20], ciphertext) - case versionV12: - return nil, fmt.Errorf("unsupported cipher version v12 (Chromium SecretPortal / Flatpak; not yet implemented)") case unversioned: return masterkey.DecryptDPAPI(ciphertext) default: @@ -40,8 +40,6 @@ func decryptValue(masterKeys masterkey.Set, ciphertext []byte) ([]byte, error) { } const ( - // versionV12 is recognized only to report a known gap: v12 is not implemented yet. - versionV12 masterkey.Version = "v12" // unversioned is a value without a version prefix, which Chromium on Windows sealed with DPAPI. unversioned masterkey.Version = "" @@ -53,7 +51,7 @@ func detectVersion(ciphertext []byte) masterkey.Version { return unversioned } switch version := masterkey.Version(ciphertext[:versionPrefixLength]); version { - case masterkey.V10, masterkey.V11, masterkey.V20, versionV12: + case masterkey.V10, masterkey.V11, masterkey.V12, masterkey.V20: return version default: return unversioned diff --git a/internal/browser/chromium/decrypt_test.go b/internal/browser/chromium/decrypt_test.go index bc8adb7..fae452f 100644 --- a/internal/browser/chromium/decrypt_test.go +++ b/internal/browser/chromium/decrypt_test.go @@ -68,6 +68,33 @@ func TestDecryptValue_V10_CrossHostGCM(t *testing.T) { assert.Equal(t, plaintext, got) } +// TestDecryptValue_V12 seals a value as Chromium's SecretPortalKeyProvider does and decrypts it via the V12 slot. +func TestDecryptValue_V12(t *testing.T) { + key := []byte("0123456789abcdef0123456789abcdef") // 32-byte HKDF-SHA256 output + plaintext := []byte("portal_cookie_value") + nonce := []byte("v12_nonce_12") + gcm, err := crypto.AESGCMEncrypt(key, nonce, plaintext) + require.NoError(t, err) + ciphertext := append([]byte("v12"), append(nonce, gcm...)...) + + t.Run("decrypts via the V12 slot", func(t *testing.T) { + got, err := decryptValue(masterkey.Set{masterkey.V12: key}, ciphertext) + require.NoError(t, err) + assert.Equal(t, plaintext, got) + }) + + t.Run("v12 routes to its own key, not V20", func(t *testing.T) { + wrong := bytes.Repeat([]byte{0x99}, 32) + _, err := decryptValue(masterkey.Set{masterkey.V12: wrong, masterkey.V20: key}, ciphertext) + require.Error(t, err, "the GCM tag must fail when the V12 slot holds the wrong key") + }) + + t.Run("missing V12 key errors", func(t *testing.T) { + _, err := decryptValue(masterkey.Set{masterkey.V10: key}, ciphertext) + require.Error(t, err) + }) +} + // TestDecryptValue_V10_V11_SlotSeparation is #578 on Linux: v10 and v11 values each route to their own key. func TestDecryptValue_V10_V11_SlotSeparation(t *testing.T) { v10Key := bytes.Repeat([]byte{0x10}, 16) // V10 slot key (peanuts-derived kV10Key) @@ -160,7 +187,7 @@ func TestDetectVersion(t *testing.T) { }{ {"v10 prefix", []byte("v10" + "encrypted_data"), masterkey.V10}, {"v11 prefix", []byte("v11" + "encrypted_data"), masterkey.V11}, - {"v12 prefix", []byte("v12" + "encrypted_data"), versionV12}, + {"v12 prefix", []byte("v12" + "encrypted_data"), masterkey.V12}, {"v20 prefix", []byte("v20" + "encrypted_data"), masterkey.V20}, {"no prefix (DPAPI)", []byte{0x01, 0x00, 0x00, 0x00}, unversioned}, {"short input", []byte{0x01, 0x02}, unversioned}, diff --git a/internal/browser/table.go b/internal/browser/table.go index 3e4eb61..dd4a1d4 100644 --- a/internal/browser/table.go +++ b/internal/browser/table.go @@ -15,6 +15,7 @@ var browsers = []Browser{ Linux: Platform{ UserDataDirs: []string{".config/google-chrome"}, SecretLabel: "Chrome Safe Storage", + PortalAppID: "com.google.Chrome", }, Windows: Platform{ UserDataDirs: []string{"AppData/Local/Google/Chrome/User Data"}, @@ -60,6 +61,7 @@ var browsers = []Browser{ Linux: Platform{ UserDataDirs: []string{".config/chromium"}, SecretLabel: "Chromium Safe Storage", + PortalAppID: "org.chromium.Chromium", }, Windows: Platform{ UserDataDirs: []string{"AppData/Local/Chromium/User Data"}, @@ -76,6 +78,7 @@ var browsers = []Browser{ Linux: Platform{ UserDataDirs: []string{".config/google-chrome-beta"}, SecretLabel: "Chrome Safe Storage", + PortalAppID: "com.google.Chrome.beta", }, Windows: Platform{ UserDataDirs: []string{"AppData/Local/Google/Chrome Beta/User Data"}, @@ -170,6 +173,7 @@ var browsers = []Browser{ Linux: Platform{ UserDataDirs: []string{".config/BraveSoftware/Brave-Browser"}, SecretLabel: "Brave Safe Storage", + PortalAppID: "com.brave.Browser", }, Windows: Platform{ UserDataDirs: []string{"AppData/Local/BraveSoftware/Brave-Browser/User Data"}, diff --git a/internal/crypto/hkdf.go b/internal/crypto/hkdf.go new file mode 100644 index 0000000..6a3a281 --- /dev/null +++ b/internal/crypto/hkdf.go @@ -0,0 +1,30 @@ +package crypto + +import ( + "crypto/hmac" + "hash" +) + +// HKDFKey is the extract-and-expand HKDF, written out because Go 1.20 has no crypto/hkdf and the project adds no +// x/crypto dependency; an empty salt means a block of newHash-sized zeros, as the construction specifies. +func HKDFKey(secret, salt, info []byte, keyLength int, newHash func() hash.Hash) []byte { + if len(salt) == 0 { + salt = make([]byte, newHash().Size()) + } + extractor := hmac.New(newHash, salt) + extractor.Write(secret) + pseudoRandomKey := extractor.Sum(nil) + + expander := hmac.New(newHash, pseudoRandomKey) + key := make([]byte, 0, keyLength) + var block []byte + for counter := byte(1); len(key) < keyLength; counter++ { + expander.Reset() + expander.Write(block) + expander.Write(info) + expander.Write([]byte{counter}) + block = expander.Sum(nil) + key = append(key, block...) + } + return key[:keyLength] +} diff --git a/internal/crypto/hkdf_test.go b/internal/crypto/hkdf_test.go new file mode 100644 index 0000000..95396bc --- /dev/null +++ b/internal/crypto/hkdf_test.go @@ -0,0 +1,63 @@ +package crypto + +import ( + "crypto/sha256" + "encoding/hex" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestHKDFKey_RFC5869 uses the SHA-256 test vectors from RFC 5869 appendix A.1-A.3. +func TestHKDFKey_RFC5869(t *testing.T) { + tests := []struct { + name string + ikm string + salt string + info string + length int + want string + }{ + { + name: "A.1 basic", + ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", + salt: "000102030405060708090a0b0c", + info: "f0f1f2f3f4f5f6f7f8f9", + length: 42, + want: "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865", + }, + { + name: "A.2 longer inputs", + ikm: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f", + salt: "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + info: "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", + length: 82, + want: "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87", + }, + { + name: "A.3 zero-length salt and info", + ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", + salt: "", + info: "", + length: 42, + want: "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8", + }, + } + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + ikm := decodeHex(t, testCase.ikm) + salt := decodeHex(t, testCase.salt) + info := decodeHex(t, testCase.info) + got := HKDFKey(ikm, salt, info, testCase.length, sha256.New) + assert.Equal(t, testCase.want, hex.EncodeToString(got)) + }) + } +} + +func decodeHex(t *testing.T, value string) []byte { + t.Helper() + decoded, err := hex.DecodeString(value) + require.NoError(t, err) + return decoded +} diff --git a/internal/masterkey/masterkey.go b/internal/masterkey/masterkey.go index af3b295..b378e56 100644 --- a/internal/masterkey/masterkey.go +++ b/internal/masterkey/masterkey.go @@ -15,6 +15,7 @@ type Version string const ( V10 Version = "v10" V11 Version = "v11" + V12 Version = "v12" V20 Version = "v20" ) @@ -34,8 +35,9 @@ var errStorageNotFound = errors.New("not found in credential store") //nolint:un // Locator is where one user data dir's keys are found; each retriever reads only the fields of its OS. type Locator struct { - LocalState string // the copied Local State; "" when the user data dir has none - SecretLabel string // macOS Keychain account / Linux D-Bus Secret Service label + LocalState string // the copied Local State; "" when the user data dir has none + SecretLabel string // macOS Keychain account / Linux D-Bus Secret Service label + PortalAppIDs []string // Linux: XDG portal app ids whose v12 secret decrypts this dir, most specific first Executable string ExecutableFallbacks []string ABE ABEKind diff --git a/internal/masterkey/retriever_linux.go b/internal/masterkey/retriever_linux.go index 09cc78d..f80f600 100644 --- a/internal/masterkey/retriever_linux.go +++ b/internal/masterkey/retriever_linux.go @@ -5,13 +5,16 @@ package masterkey import ( "context" "crypto/sha1" + "crypto/sha256" "errors" "fmt" + "hash" "strings" "time" "github.com/godbus/dbus/v5" + "github.com/moond4rk/hackbrowserdata/internal/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" ) @@ -23,8 +26,27 @@ var linuxParams = pbkdf2Params{ hashFunc: sha1.New, } -// platformRetrievers run both: a profile holds v10 and v11 values once its host moved between headless and keyring. -var platformRetrievers = []keyRetriever{posixRetriever{}, dbusRetriever{}} +// portalParams derive the v12 key from the XDG portal app secret, matching Chromium's SecretPortalKeyProvider. +var portalParams = hkdfParams{ + salt: []byte("fdo_portal_secret_salt"), + info: []byte("HKDF-SHA-256 AES-256-GCM"), + keySize: 32, + hashFunc: sha256.New, +} + +type hkdfParams struct { + salt []byte + info []byte + keySize int + hashFunc func() hash.Hash +} + +func (p hkdfParams) deriveKey(secret []byte) []byte { + return crypto.HKDFKey(secret, p.salt, p.info, p.keySize, p.hashFunc) +} + +// platformRetrievers run in order: v10 headless, v11 keyring, v12 XDG portal; a profile can hold values of each. +var platformRetrievers = []keyRetriever{posixRetriever{}, dbusRetriever{}, portalRetriever{}} type dbusRetriever struct{} @@ -59,12 +81,14 @@ func (dbusRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, err return linuxParams.deriveKey(secret), nil } -// secretStore is what findStorageSecret needs from the Secret Service, so tests can stand in for D-Bus. +// secretStore is what the lookups need from the Secret Service, so tests can stand in for D-Bus. secrets reads a +// batch in one call, the only way to read gnome-keyring's portal items, whose D-Bus objects it never exports. type secretStore interface { searchItems(ctx context.Context, attributes map[string]string) (unlocked, locked []dbus.ObjectPath, err error) unlock(ctx context.Context, items []dbus.ObjectPath) ([]dbus.ObjectPath, error) itemLabel(ctx context.Context, item dbus.ObjectPath) (string, error) itemSecret(ctx context.Context, item dbus.ObjectPath) ([]byte, error) + secrets(ctx context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) } // searchQueries find the storage item by libsecret's schema (GNOME), KWallet's schema, and KWallet's entry-name @@ -103,18 +127,10 @@ func findStorageSecret(ctx context.Context, store secretStore, storage string) ( // searchStorageSecret relies on SearchItems, which resolves only live items, and reads each match on its own, so a // stale path that fails is skipped (a whole-collection read aborts on it instead). func searchStorageSecret(ctx context.Context, store secretStore, attributes map[string]string, storage string) ([]byte, error) { - items, locked, err := store.searchItems(ctx, attributes) + items, allOpened, err := searchAndUnlock(ctx, store, attributes) if err != nil { return nil, err } - var opened []dbus.ObjectPath - if len(locked) > 0 { - opened, err = store.unlock(ctx, locked) - if err != nil { - log.Debugf("secret service: %v", err) - } - items = append(items, opened...) - } for _, item := range items { label, err := store.itemLabel(ctx, item) if err != nil { @@ -133,7 +149,93 @@ func searchStorageSecret(ctx context.Context, store secretStore, attributes map[ return secret, nil } } - if len(opened) < len(locked) { + if !allOpened { + return nil, errKeyringLocked + } + return nil, errStorageNotFound +} + +// searchAndUnlock resolves a query to live item paths, unlocking any that open without a prompt; allOpened is false +// when a locked item stayed locked, which the callers report as errKeyringLocked rather than as not found. +func searchAndUnlock(ctx context.Context, store secretStore, attributes map[string]string) (items []dbus.ObjectPath, allOpened bool, err error) { + unlocked, locked, err := store.searchItems(ctx, attributes) + if err != nil { + return nil, false, err + } + items = unlocked + allOpened = true + if len(locked) > 0 { + opened, err := store.unlock(ctx, locked) + if err != nil { + log.Debugf("secret service: %v", err) + } + items = append(items, opened...) + allOpened = len(opened) >= len(locked) + } + return items, allOpened, nil +} + +// findPortalSecret looks up the XDG portal app secret for each candidate app id; a secret behind a wallet that stays +// locked reads as locked, and no match at all steps aside so a profile without v12 gets no error row. +func findPortalSecret(ctx context.Context, store secretStore, appIDs []string) ([]byte, error) { + locked := false + for _, appID := range appIDs { + for _, attributes := range portalQueries(appID) { + secret, err := searchPortalSecret(ctx, store, attributes) + switch { + case err == nil: + return secret, nil + case errors.Is(err, errKeyringLocked): + locked = true + case !errors.Is(err, errStorageNotFound): + log.Debugf("portal secret %v: %v", attributes, err) + } + } + } + switch { + case ctx.Err() != nil: + return nil, fmt.Errorf("portal secret lookup: %w", ctx.Err()) + case locked: + return nil, errKeyringLocked + } + return nil, errStorageNotFound +} + +// portalQueries find the app secret by gnome-keyring's portal schema and app_id, then by ksecretd's synthesized +// folder and entry, which carry no schema. +func portalQueries(appID string) []map[string]string { + return []map[string]string{ + {"xdg:schema": "org.freedesktop.portal.Secret", "app_id": appID}, + {"server": "xdg-desktop-portal", "user": appID}, + } +} + +// searchPortalSecret reads matches with GetSecrets first, since gnome-keyring's portal items answer nothing else, +// and falls back to a per-item read for stores that leave GetSecrets empty. +func searchPortalSecret(ctx context.Context, store secretStore, attributes map[string]string) ([]byte, error) { + items, allOpened, err := searchAndUnlock(ctx, store, attributes) + if err != nil { + return nil, err + } + secrets, err := store.secrets(ctx, items) + if err != nil { + log.Debugf("portal secret batch: %v", err) + secrets = nil + } + for _, item := range items { + secret := secrets[item] + if len(secret) == 0 { + secret, err = store.itemSecret(ctx, item) + if err != nil { + log.Debugf("portal secret %s: %v", item, err) + continue + } + } + if len(secret) > 0 { + return secret, nil + } + } + if !allOpened { return nil, errKeyringLocked } return nil, errStorageNotFound @@ -223,6 +325,23 @@ func (s *secretService) itemSecret(ctx context.Context, item dbus.ObjectPath) ([ return reply.Value, nil } +// secrets reads several items in one call; gnome-keyring answers here for portal items it never exports as objects. +func (s *secretService) secrets(ctx context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) { + if len(items) == 0 { + return nil, nil + } + call := s.object.CallWithContext(ctx, secretServiceInterface+".GetSecrets", 0, items, s.session) + var replies map[dbus.ObjectPath]dbusSecret + if err := call.Store(&replies); err != nil { + return nil, fmt.Errorf("get secrets: %w", err) + } + values := make(map[dbus.ObjectPath][]byte, len(replies)) + for path, reply := range replies { + values[path] = reply.Value + } + return values, nil +} + // dbusSecret is the org.freedesktop.Secret.Item.GetSecret reply; a plain session leaves Value unencrypted. type dbusSecret struct { Session dbus.ObjectPath @@ -231,6 +350,36 @@ type dbusSecret struct { ContentType string } +// portalRetriever reads the XDG desktop portal app secret (Chromium's SecretPortalKeyProvider, the v12 scheme). It +// reads only a secret the portal already stored; it never calls RetrieveSecret, which would create one when missing. +type portalRetriever struct{} + +func (portalRetriever) Version() Version { return V12 } + +func (portalRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, error) { + if len(locator.PortalAppIDs) == 0 { + return nil, errNotApplicable + } + ctx, cancel := context.WithTimeout(ctx, secretCallTimeout) + defer cancel() + + service, err := newSecretService(ctx) + if err != nil { + log.Debugf("portal secret: %v", err) + return nil, errNotApplicable + } + defer service.Close() + + secret, err := findPortalSecret(ctx, service, locator.PortalAppIDs) + switch { + case errors.Is(err, errStorageNotFound): + return nil, errNotApplicable + case err != nil: + return nil, err + } + return portalParams.deriveKey(secret), nil +} + // posixRetriever covers hosts without a keyring (headless, Docker, CI), mirroring Chromium's PosixKeyProvider. type posixRetriever struct{} diff --git a/internal/masterkey/retriever_linux_test.go b/internal/masterkey/retriever_linux_test.go index 22ad457..f029d0a 100644 --- a/internal/masterkey/retriever_linux_test.go +++ b/internal/masterkey/retriever_linux_test.go @@ -4,6 +4,7 @@ package masterkey import ( "context" + "encoding/hex" "errors" "strconv" "testing" @@ -48,11 +49,13 @@ func TestPosixRetriever_MatchesChromiumKV10Key(t *testing.T) { } func TestPlatformRetrievers_Linux(t *testing.T) { - require.Len(t, platformRetrievers, 2) + require.Len(t, platformRetrievers, 3) assert.IsType(t, posixRetriever{}, platformRetrievers[0], "v10 is the peanuts kV10Key") assert.IsType(t, dbusRetriever{}, platformRetrievers[1], "v11 is the D-Bus keyring kV11Key") + assert.IsType(t, portalRetriever{}, platformRetrievers[2], "v12 is the XDG portal app key") assert.Equal(t, V10, platformRetrievers[0].Version()) assert.Equal(t, V11, platformRetrievers[1].Version()) + assert.Equal(t, V12, platformRetrievers[2].Version()) } func TestLabelMatches(t *testing.T) { @@ -139,6 +142,89 @@ func TestFindStorageSecret(t *testing.T) { } } +func TestFindPortalSecret(t *testing.T) { + gnome := func(appID string) map[string]string { + return map[string]string{"xdg:schema": "org.freedesktop.portal.Secret", "app_id": appID} + } + kde := func(appID string) map[string]string { + return map[string]string{"server": "xdg-desktop-portal", "user": appID} + } + tests := []struct { + name string + store fakeSecretStore + appIDs []string + want string + wantErr error + }{ + { + name: "gnome portal item read via GetSecrets", + store: fakeSecretStore{{attributes: gnome("com.google.Chrome"), secret: "gnome", stale: true, batchReadable: true}}, + appIDs: []string{"com.google.Chrome"}, + want: "gnome", + }, + { + name: "kde portal item falls back to a per-item read", + store: fakeSecretStore{{attributes: kde("com.google.Chrome"), label: "xdg-desktop-portal/com.google.Chrome", secret: "kde"}}, + appIDs: []string{"com.google.Chrome"}, + want: "kde", + }, + { + name: "flatpak id is tried before the table id", + store: fakeSecretStore{ + {attributes: gnome("com.google.Chrome"), secret: "deb", stale: true, batchReadable: true}, + {attributes: gnome("org.chromium.Chromium"), secret: "flatpak", stale: true, batchReadable: true}, + }, + appIDs: []string{"org.chromium.Chromium", "com.google.Chrome"}, + want: "flatpak", + }, + { + name: "empty app id is the final candidate", + store: fakeSecretStore{{attributes: gnome(""), secret: "shared", stale: true, batchReadable: true}}, + appIDs: []string{"com.brave.Browser", ""}, + want: "shared", + }, + { + name: "portal item that stays locked reads as locked", + store: fakeSecretStore{{attributes: gnome("com.google.Chrome"), secret: "hidden", stale: true, batchReadable: true, locked: true}}, + appIDs: []string{"com.google.Chrome"}, + wantErr: errKeyringLocked, + }, + { + name: "no matching app id is not found", + store: fakeSecretStore{{attributes: gnome("com.google.Chrome"), secret: "x", stale: true, batchReadable: true}}, + appIDs: []string{"org.chromium.Chromium"}, + wantErr: errStorageNotFound, + }, + } + for _, testCase := range tests { + t.Run(testCase.name, func(t *testing.T) { + secret, err := findPortalSecret(context.Background(), testCase.store, testCase.appIDs) + if testCase.wantErr != nil { + require.ErrorIs(t, err, testCase.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, testCase.want, string(secret)) + }) + } +} + +// TestPortalParams_Vector pins the v12 key derivation to an independently computed HKDF-SHA256 output. +func TestPortalParams_Vector(t *testing.T) { + secret := make([]byte, 64) + for i := range secret { + secret[i] = byte(i) + } + want := "39ba5df998f8f1c032fac27b67d7359f8feda53482637745b35e4778295d32e7" + assert.Equal(t, want, hex.EncodeToString(portalParams.deriveKey(secret))) + assert.Len(t, portalParams.deriveKey(secret), 32) +} + +func TestPortalRetriever_StepsAside(t *testing.T) { + _, err := portalRetriever{}.Retrieve(context.Background(), Locator{}) + require.ErrorIs(t, err, errNotApplicable, "no portal app id means no v12, so the retriever must step aside") +} + func TestFindStorageSecret_Timeout(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 0) defer cancel() @@ -149,14 +235,16 @@ func TestFindStorageSecret_Timeout(t *testing.T) { assert.NotErrorIs(t, err, errStorageNotFound, "a lookup that ran out of time must not read as not found") } -// fakeItem is one Secret Service item: a locked one reads only once unlocked, and a stale one never does. +// fakeItem is one Secret Service item: a locked one reads only once unlocked, and a stale one never does. A +// batchReadable item answers GetSecrets but not a per-item read, as gnome-keyring's unexported portal items do. type fakeItem struct { - attributes map[string]string - label string - secret string - locked bool - unlockable bool - stale bool + attributes map[string]string + label string + secret string + locked bool + unlockable bool + stale bool + batchReadable bool } type fakeSecretStore []fakeItem @@ -223,6 +311,16 @@ func (s fakeSecretStore) itemSecret(_ context.Context, path dbus.ObjectPath) ([] return []byte(item.secret), nil } +func (s fakeSecretStore) secrets(_ context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) { + values := make(map[dbus.ObjectPath][]byte) + for _, path := range items { + if item := s.item(path); item.batchReadable && !item.locked { + values[path] = []byte(item.secret) + } + } + return values, nil +} + func hasAttributes(attributes, query map[string]string) bool { for key, value := range query { if attributes[key] != value { From ec69af3685c1dbb0f47b09287eebf65bb4452476 Mon Sep 17 00:00:00 2001 From: moonD4rk Date: Thu, 19 Nov 2026 19:21:55 +0800 Subject: [PATCH 2/2] refactor(masterkey): simplify v12 portal lookup Address review: single PortalAppID (a Flatpak sandbox fixes the id, so it never falls back to the table id), GetSecrets-only (no unreachable per-item fallback), drop the hkdfParams wrapper, and use stillLocked instead of a shadowed named return (fixes a lll violation on Linux). --- internal/browser/chromium/chromium.go | 25 ++--- internal/browser/chromium/chromium_test.go | 21 ++-- internal/crypto/hkdf.go | 1 + internal/masterkey/masterkey.go | 6 +- internal/masterkey/retriever_linux.go | 109 ++++++++------------- internal/masterkey/retriever_linux_test.go | 62 +++++------- 6 files changed, 82 insertions(+), 142 deletions(-) diff --git a/internal/browser/chromium/chromium.go b/internal/browser/chromium/chromium.go index 08b0f69..977b927 100644 --- a/internal/browser/chromium/chromium.go +++ b/internal/browser/chromium/chromium.go @@ -165,7 +165,7 @@ func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterk platform := dir.Browser.Platform() locator := masterkey.Locator{ SecretLabel: platform.SecretLabel, Executable: platform.Executable, ExecutableFallbacks: platform.ExecutableFallbacks, ABE: platform.ABE, - PortalAppIDs: portalAppIDs(dir.Path, platform.PortalAppID), + PortalAppID: portalAppID(dir.Path, platform.PortalAppID), } path, err := dirSnapshot.Path(localState.Path) switch { @@ -177,24 +177,13 @@ func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterk return locator, nil } -// portalAppIDs lists the v12 app id candidates for a dir, most specific first: a Flatpak install's own id, taken -// from its .var/app// path, then the browser's registered id. Empty ids and duplicates are dropped. -func portalAppIDs(dirPath, registeredID string) []string { - var ids []string - add := func(id string) { - if id == "" { - return - } - for _, existing := range ids { - if existing == id { - return - } - } - ids = append(ids, id) +// portalAppID is the v12 app id for a dir: a Flatpak install's id is fixed by its sandbox, taken from the +// .var/app// path, so it wins outright; otherwise the browser's registered id applies. +func portalAppID(dirPath, registeredID string) string { + if flatpak := flatpakAppID(dirPath); flatpak != "" { + return flatpak } - add(flatpakAppID(dirPath)) - add(registeredID) - return ids + return registeredID } // flatpakAppID returns the Flatpak application id in a path like ".../.var/app//config/...", or "" if absent. diff --git a/internal/browser/chromium/chromium_test.go b/internal/browser/chromium/chromium_test.go index 2213767..8c6282d 100644 --- a/internal/browser/chromium/chromium_test.go +++ b/internal/browser/chromium/chromium_test.go @@ -167,29 +167,26 @@ func TestKeyLocator(t *testing.T) { assert.Empty(t, locator.LocalState) } -func TestPortalAppIDs(t *testing.T) { +func TestPortalAppID(t *testing.T) { tests := []struct { name string dirPath string registeredID string - want []string + want string }{ - {name: "deb install uses the table id", dirPath: "/home/u/.config/google-chrome", registeredID: "com.google.Chrome", want: []string{"com.google.Chrome"}}, + {name: "deb install uses the registered id", dirPath: "/home/u/.config/google-chrome", registeredID: "com.google.Chrome", want: "com.google.Chrome"}, { - name: "flatpak install is tried before the table id", registeredID: "org.chromium.Chromium", + // a Flatpak sandbox fixes the app id, so the path id wins over the table id and never falls back to it. + name: "flatpak id overrides the registered id", registeredID: "org.chromium.Chromium", dirPath: "/home/u/.var/app/io.github.ungoogled_software.ungoogled_chromium/config/chromium", - want: []string{"io.github.ungoogled_software.ungoogled_chromium", "org.chromium.Chromium"}, + want: "io.github.ungoogled_software.ungoogled_chromium", }, - { - name: "matching flatpak and table id collapse to one", registeredID: "com.google.Chrome", - dirPath: "/home/u/.var/app/com.google.Chrome/config/google-chrome", want: []string{"com.google.Chrome"}, - }, - {name: "no table id leaves only the flatpak id", dirPath: "/home/u/.var/app/com.brave.Browser/config/BraveSoftware/Brave-Browser", want: []string{"com.brave.Browser"}}, - {name: "no candidates for a browser without a portal id", dirPath: "/home/u/.config/microsoft-edge", want: nil}, + {name: "no registered id leaves only the flatpak id", dirPath: "/home/u/.var/app/com.brave.Browser/config/BraveSoftware/Brave-Browser", want: "com.brave.Browser"}, + {name: "no portal id for a browser without one", dirPath: "/home/u/.config/microsoft-edge", want: ""}, } for _, testCase := range tests { t.Run(testCase.name, func(t *testing.T) { - assert.Equal(t, testCase.want, portalAppIDs(testCase.dirPath, testCase.registeredID)) + assert.Equal(t, testCase.want, portalAppID(testCase.dirPath, testCase.registeredID)) }) } } diff --git a/internal/crypto/hkdf.go b/internal/crypto/hkdf.go index 6a3a281..02f1fc3 100644 --- a/internal/crypto/hkdf.go +++ b/internal/crypto/hkdf.go @@ -7,6 +7,7 @@ import ( // HKDFKey is the extract-and-expand HKDF, written out because Go 1.20 has no crypto/hkdf and the project adds no // x/crypto dependency; an empty salt means a block of newHash-sized zeros, as the construction specifies. +// keyLength must be at most 255*HashLen (the single-block AES-256 key here is well within it). func HKDFKey(secret, salt, info []byte, keyLength int, newHash func() hash.Hash) []byte { if len(salt) == 0 { salt = make([]byte, newHash().Size()) diff --git a/internal/masterkey/masterkey.go b/internal/masterkey/masterkey.go index b378e56..f65b146 100644 --- a/internal/masterkey/masterkey.go +++ b/internal/masterkey/masterkey.go @@ -35,9 +35,9 @@ var errStorageNotFound = errors.New("not found in credential store") //nolint:un // Locator is where one user data dir's keys are found; each retriever reads only the fields of its OS. type Locator struct { - LocalState string // the copied Local State; "" when the user data dir has none - SecretLabel string // macOS Keychain account / Linux D-Bus Secret Service label - PortalAppIDs []string // Linux: XDG portal app ids whose v12 secret decrypts this dir, most specific first + LocalState string // the copied Local State; "" when the user data dir has none + SecretLabel string // macOS Keychain account / Linux D-Bus Secret Service label + PortalAppID string // Linux: the XDG portal app id whose v12 secret decrypts this dir; "" = no v12 Executable string ExecutableFallbacks []string ABE ABEKind diff --git a/internal/masterkey/retriever_linux.go b/internal/masterkey/retriever_linux.go index f80f600..a8f8d73 100644 --- a/internal/masterkey/retriever_linux.go +++ b/internal/masterkey/retriever_linux.go @@ -8,7 +8,6 @@ import ( "crypto/sha256" "errors" "fmt" - "hash" "strings" "time" @@ -26,23 +25,9 @@ var linuxParams = pbkdf2Params{ hashFunc: sha1.New, } -// portalParams derive the v12 key from the XDG portal app secret, matching Chromium's SecretPortalKeyProvider. -var portalParams = hkdfParams{ - salt: []byte("fdo_portal_secret_salt"), - info: []byte("HKDF-SHA-256 AES-256-GCM"), - keySize: 32, - hashFunc: sha256.New, -} - -type hkdfParams struct { - salt []byte - info []byte - keySize int - hashFunc func() hash.Hash -} - -func (p hkdfParams) deriveKey(secret []byte) []byte { - return crypto.HKDFKey(secret, p.salt, p.info, p.keySize, p.hashFunc) +// portalKey derives the v12 key from the XDG portal app secret, matching Chromium's SecretPortalKeyProvider. +func portalKey(secret []byte) []byte { + return crypto.HKDFKey(secret, []byte("fdo_portal_secret_salt"), []byte("HKDF-SHA-256 AES-256-GCM"), 32, sha256.New) } // platformRetrievers run in order: v10 headless, v11 keyring, v12 XDG portal; a profile can hold values of each. @@ -81,14 +66,14 @@ func (dbusRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, err return linuxParams.deriveKey(secret), nil } -// secretStore is what the lookups need from the Secret Service, so tests can stand in for D-Bus. secrets reads a +// secretStore is what the lookups need from the Secret Service, so tests can stand in for D-Bus. itemSecrets reads a // batch in one call, the only way to read gnome-keyring's portal items, whose D-Bus objects it never exports. type secretStore interface { searchItems(ctx context.Context, attributes map[string]string) (unlocked, locked []dbus.ObjectPath, err error) unlock(ctx context.Context, items []dbus.ObjectPath) ([]dbus.ObjectPath, error) itemLabel(ctx context.Context, item dbus.ObjectPath) (string, error) itemSecret(ctx context.Context, item dbus.ObjectPath) ([]byte, error) - secrets(ctx context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) + itemSecrets(ctx context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) } // searchQueries find the storage item by libsecret's schema (GNOME), KWallet's schema, and KWallet's entry-name @@ -127,7 +112,7 @@ func findStorageSecret(ctx context.Context, store secretStore, storage string) ( // searchStorageSecret relies on SearchItems, which resolves only live items, and reads each match on its own, so a // stale path that fails is skipped (a whole-collection read aborts on it instead). func searchStorageSecret(ctx context.Context, store secretStore, attributes map[string]string, storage string) ([]byte, error) { - items, allOpened, err := searchAndUnlock(ctx, store, attributes) + items, stillLocked, err := searchAndUnlock(ctx, store, attributes) if err != nil { return nil, err } @@ -149,47 +134,42 @@ func searchStorageSecret(ctx context.Context, store secretStore, attributes map[ return secret, nil } } - if !allOpened { + if stillLocked { return nil, errKeyringLocked } return nil, errStorageNotFound } -// searchAndUnlock resolves a query to live item paths, unlocking any that open without a prompt; allOpened is false +// searchAndUnlock resolves a query to live item paths, unlocking any that open without a prompt; stillLocked is set // when a locked item stayed locked, which the callers report as errKeyringLocked rather than as not found. -func searchAndUnlock(ctx context.Context, store secretStore, attributes map[string]string) (items []dbus.ObjectPath, allOpened bool, err error) { +func searchAndUnlock(ctx context.Context, store secretStore, attributes map[string]string) ([]dbus.ObjectPath, bool, error) { unlocked, locked, err := store.searchItems(ctx, attributes) if err != nil { return nil, false, err } - items = unlocked - allOpened = true - if len(locked) > 0 { - opened, err := store.unlock(ctx, locked) - if err != nil { - log.Debugf("secret service: %v", err) - } - items = append(items, opened...) - allOpened = len(opened) >= len(locked) + if len(locked) == 0 { + return unlocked, false, nil + } + opened, err := store.unlock(ctx, locked) + if err != nil { + log.Debugf("secret service: %v", err) } - return items, allOpened, nil + return append(unlocked, opened...), len(opened) < len(locked), nil } -// findPortalSecret looks up the XDG portal app secret for each candidate app id; a secret behind a wallet that stays -// locked reads as locked, and no match at all steps aside so a profile without v12 gets no error row. -func findPortalSecret(ctx context.Context, store secretStore, appIDs []string) ([]byte, error) { +// findPortalSecret looks up the XDG portal app secret by its app id; a secret behind a wallet that stays locked reads +// as locked, and no match steps aside so a profile whose browser never wrote a v12 value gets no error row. +func findPortalSecret(ctx context.Context, store secretStore, appID string) ([]byte, error) { locked := false - for _, appID := range appIDs { - for _, attributes := range portalQueries(appID) { - secret, err := searchPortalSecret(ctx, store, attributes) - switch { - case err == nil: - return secret, nil - case errors.Is(err, errKeyringLocked): - locked = true - case !errors.Is(err, errStorageNotFound): - log.Debugf("portal secret %v: %v", attributes, err) - } + for _, attributes := range portalQueries(appID) { + secret, err := searchPortalSecret(ctx, store, attributes) + switch { + case err == nil: + return secret, nil + case errors.Is(err, errKeyringLocked): + locked = true + case !errors.Is(err, errStorageNotFound): + log.Debugf("portal secret %v: %v", attributes, err) } } switch { @@ -210,32 +190,23 @@ func portalQueries(appID string) []map[string]string { } } -// searchPortalSecret reads matches with GetSecrets first, since gnome-keyring's portal items answer nothing else, -// and falls back to a per-item read for stores that leave GetSecrets empty. +// searchPortalSecret reads matches with GetSecrets, the one call both gnome-keyring (whose portal item objects are +// never exported) and ksecretd answer; GetSecrets is mandatory in the Secret Service API, so there is no fallback. func searchPortalSecret(ctx context.Context, store secretStore, attributes map[string]string) ([]byte, error) { - items, allOpened, err := searchAndUnlock(ctx, store, attributes) + items, stillLocked, err := searchAndUnlock(ctx, store, attributes) if err != nil { return nil, err } - secrets, err := store.secrets(ctx, items) + secrets, err := store.itemSecrets(ctx, items) if err != nil { - log.Debugf("portal secret batch: %v", err) - secrets = nil + return nil, err } for _, item := range items { - secret := secrets[item] - if len(secret) == 0 { - secret, err = store.itemSecret(ctx, item) - if err != nil { - log.Debugf("portal secret %s: %v", item, err) - continue - } - } - if len(secret) > 0 { + if secret := secrets[item]; len(secret) > 0 { return secret, nil } } - if !allOpened { + if stillLocked { return nil, errKeyringLocked } return nil, errStorageNotFound @@ -325,8 +296,8 @@ func (s *secretService) itemSecret(ctx context.Context, item dbus.ObjectPath) ([ return reply.Value, nil } -// secrets reads several items in one call; gnome-keyring answers here for portal items it never exports as objects. -func (s *secretService) secrets(ctx context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) { +// itemSecrets reads several items in one call; gnome-keyring answers here for portal items it never exports as objects. +func (s *secretService) itemSecrets(ctx context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) { if len(items) == 0 { return nil, nil } @@ -357,7 +328,7 @@ type portalRetriever struct{} func (portalRetriever) Version() Version { return V12 } func (portalRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, error) { - if len(locator.PortalAppIDs) == 0 { + if locator.PortalAppID == "" { return nil, errNotApplicable } ctx, cancel := context.WithTimeout(ctx, secretCallTimeout) @@ -370,14 +341,14 @@ func (portalRetriever) Retrieve(ctx context.Context, locator Locator) ([]byte, e } defer service.Close() - secret, err := findPortalSecret(ctx, service, locator.PortalAppIDs) + secret, err := findPortalSecret(ctx, service, locator.PortalAppID) switch { case errors.Is(err, errStorageNotFound): return nil, errNotApplicable case err != nil: return nil, err } - return portalParams.deriveKey(secret), nil + return portalKey(secret), nil } // posixRetriever covers hosts without a keyring (headless, Docker, CI), mirroring Chromium's PosixKeyProvider. diff --git a/internal/masterkey/retriever_linux_test.go b/internal/masterkey/retriever_linux_test.go index f029d0a..16933c1 100644 --- a/internal/masterkey/retriever_linux_test.go +++ b/internal/masterkey/retriever_linux_test.go @@ -143,62 +143,45 @@ func TestFindStorageSecret(t *testing.T) { } func TestFindPortalSecret(t *testing.T) { - gnome := func(appID string) map[string]string { - return map[string]string{"xdg:schema": "org.freedesktop.portal.Secret", "app_id": appID} - } - kde := func(appID string) map[string]string { - return map[string]string{"server": "xdg-desktop-portal", "user": appID} - } + const appID = "com.google.Chrome" + gnome := map[string]string{"xdg:schema": "org.freedesktop.portal.Secret", "app_id": appID} + kde := map[string]string{"server": "xdg-desktop-portal", "user": appID} tests := []struct { name string store fakeSecretStore - appIDs []string + appID string want string wantErr error }{ { - name: "gnome portal item read via GetSecrets", - store: fakeSecretStore{{attributes: gnome("com.google.Chrome"), secret: "gnome", stale: true, batchReadable: true}}, - appIDs: []string{"com.google.Chrome"}, - want: "gnome", - }, - { - name: "kde portal item falls back to a per-item read", - store: fakeSecretStore{{attributes: kde("com.google.Chrome"), label: "xdg-desktop-portal/com.google.Chrome", secret: "kde"}}, - appIDs: []string{"com.google.Chrome"}, - want: "kde", - }, - { - name: "flatpak id is tried before the table id", - store: fakeSecretStore{ - {attributes: gnome("com.google.Chrome"), secret: "deb", stale: true, batchReadable: true}, - {attributes: gnome("org.chromium.Chromium"), secret: "flatpak", stale: true, batchReadable: true}, - }, - appIDs: []string{"org.chromium.Chromium", "com.google.Chrome"}, - want: "flatpak", + // gnome-keyring never exports the object, so a per-item read fails (stale); only GetSecrets returns it. + name: "gnome portal item read via GetSecrets", + store: fakeSecretStore{{attributes: gnome, secret: "gnome", stale: true, batchReadable: true}}, + appID: appID, + want: "gnome", }, { - name: "empty app id is the final candidate", - store: fakeSecretStore{{attributes: gnome(""), secret: "shared", stale: true, batchReadable: true}}, - appIDs: []string{"com.brave.Browser", ""}, - want: "shared", + name: "kde portal item read via GetSecrets", + store: fakeSecretStore{{attributes: kde, label: "xdg-desktop-portal/" + appID, secret: "kde", batchReadable: true}}, + appID: appID, + want: "kde", }, { name: "portal item that stays locked reads as locked", - store: fakeSecretStore{{attributes: gnome("com.google.Chrome"), secret: "hidden", stale: true, batchReadable: true, locked: true}}, - appIDs: []string{"com.google.Chrome"}, + store: fakeSecretStore{{attributes: gnome, secret: "hidden", stale: true, batchReadable: true, locked: true}}, + appID: appID, wantErr: errKeyringLocked, }, { name: "no matching app id is not found", - store: fakeSecretStore{{attributes: gnome("com.google.Chrome"), secret: "x", stale: true, batchReadable: true}}, - appIDs: []string{"org.chromium.Chromium"}, + store: fakeSecretStore{{attributes: gnome, secret: "x", stale: true, batchReadable: true}}, + appID: "org.chromium.Chromium", wantErr: errStorageNotFound, }, } for _, testCase := range tests { t.Run(testCase.name, func(t *testing.T) { - secret, err := findPortalSecret(context.Background(), testCase.store, testCase.appIDs) + secret, err := findPortalSecret(context.Background(), testCase.store, testCase.appID) if testCase.wantErr != nil { require.ErrorIs(t, err, testCase.wantErr) return @@ -209,15 +192,14 @@ func TestFindPortalSecret(t *testing.T) { } } -// TestPortalParams_Vector pins the v12 key derivation to an independently computed HKDF-SHA256 output. -func TestPortalParams_Vector(t *testing.T) { +// TestPortalKey_Vector pins the v12 key derivation to an independently computed HKDF-SHA256 output. +func TestPortalKey_Vector(t *testing.T) { secret := make([]byte, 64) for i := range secret { secret[i] = byte(i) } want := "39ba5df998f8f1c032fac27b67d7359f8feda53482637745b35e4778295d32e7" - assert.Equal(t, want, hex.EncodeToString(portalParams.deriveKey(secret))) - assert.Len(t, portalParams.deriveKey(secret), 32) + assert.Equal(t, want, hex.EncodeToString(portalKey(secret))) } func TestPortalRetriever_StepsAside(t *testing.T) { @@ -311,7 +293,7 @@ func (s fakeSecretStore) itemSecret(_ context.Context, path dbus.ObjectPath) ([] return []byte(item.secret), nil } -func (s fakeSecretStore) secrets(_ context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) { +func (s fakeSecretStore) itemSecrets(_ context.Context, items []dbus.ObjectPath) (map[dbus.ObjectPath][]byte, error) { values := make(map[dbus.ObjectPath][]byte) for _, path := range items { if item := s.item(path); item.batchReadable && !item.locked {