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..977b927 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, + PortalAppID: portalAppID(dir.Path, platform.PortalAppID), } path, err := dirSnapshot.Path(localState.Path) switch { @@ -175,6 +177,25 @@ func KeyLocator(dir browser.UserDataDir, dirSnapshot snapshot.Snapshot) (masterk return locator, nil } +// 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 + } + return registeredID +} + +// 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..8c6282d 100644 --- a/internal/browser/chromium/chromium_test.go +++ b/internal/browser/chromium/chromium_test.go @@ -166,3 +166,27 @@ 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 TestPortalAppID(t *testing.T) { + tests := []struct { + name string + dirPath string + registeredID string + want string + }{ + {name: "deb install uses the registered id", dirPath: "/home/u/.config/google-chrome", registeredID: "com.google.Chrome", want: "com.google.Chrome"}, + { + // 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: "io.github.ungoogled_software.ungoogled_chromium", + }, + {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, portalAppID(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..02f1fc3 --- /dev/null +++ b/internal/crypto/hkdf.go @@ -0,0 +1,31 @@ +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. +// 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()) + } + 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..f65b146 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" ) @@ -36,6 +37,7 @@ var errStorageNotFound = errors.New("not found in credential store") //nolint:un 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 + 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 09cc78d..a8f8d73 100644 --- a/internal/masterkey/retriever_linux.go +++ b/internal/masterkey/retriever_linux.go @@ -5,6 +5,7 @@ package masterkey import ( "context" "crypto/sha1" + "crypto/sha256" "errors" "fmt" "strings" @@ -12,6 +13,7 @@ import ( "github.com/godbus/dbus/v5" + "github.com/moond4rk/hackbrowserdata/internal/crypto" "github.com/moond4rk/hackbrowserdata/internal/log" ) @@ -23,8 +25,13 @@ 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{}} +// 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. +var platformRetrievers = []keyRetriever{posixRetriever{}, dbusRetriever{}, portalRetriever{}} type dbusRetriever struct{} @@ -59,12 +66,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. 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) + 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 @@ -103,18 +112,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, stillLocked, 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 +134,79 @@ func searchStorageSecret(ctx context.Context, store secretStore, attributes map[ return secret, nil } } - if len(opened) < len(locked) { + if stillLocked { + return nil, errKeyringLocked + } + return nil, errStorageNotFound +} + +// 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) ([]dbus.ObjectPath, bool, error) { + unlocked, locked, err := store.searchItems(ctx, attributes) + if err != nil { + return nil, false, err + } + if len(locked) == 0 { + return unlocked, false, nil + } + opened, err := store.unlock(ctx, locked) + if err != nil { + log.Debugf("secret service: %v", err) + } + return append(unlocked, opened...), len(opened) < len(locked), nil +} + +// 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 _, 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, 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, stillLocked, err := searchAndUnlock(ctx, store, attributes) + if err != nil { + return nil, err + } + secrets, err := store.itemSecrets(ctx, items) + if err != nil { + return nil, err + } + for _, item := range items { + if secret := secrets[item]; len(secret) > 0 { + return secret, nil + } + } + if stillLocked { return nil, errKeyringLocked } return nil, errStorageNotFound @@ -223,6 +296,23 @@ func (s *secretService) itemSecret(ctx context.Context, item dbus.ObjectPath) ([ return reply.Value, nil } +// 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 + } + 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 +321,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 locator.PortalAppID == "" { + 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.PortalAppID) + switch { + case errors.Is(err, errStorageNotFound): + return nil, errNotApplicable + case err != nil: + return nil, err + } + return portalKey(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..16933c1 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,71 @@ func TestFindStorageSecret(t *testing.T) { } } +func TestFindPortalSecret(t *testing.T) { + 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 + appID string + want string + wantErr error + }{ + { + // 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: "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, secret: "hidden", stale: true, batchReadable: true, locked: true}}, + appID: appID, + wantErr: errKeyringLocked, + }, + { + name: "no matching app id is not found", + 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.appID) + if testCase.wantErr != nil { + require.ErrorIs(t, err, testCase.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, testCase.want, string(secret)) + }) + } +} + +// 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(portalKey(secret))) +} + +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 +217,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 +293,16 @@ func (s fakeSecretStore) itemSecret(_ context.Context, path dbus.ObjectPath) ([] return []byte(item.secret), nil } +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 { + 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 {