diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CredentialCipher.kt b/app/src/main/java/com/droiddeck/launcher/stores/CredentialCipher.kt index c0af7ac0b4..2a7e84357e 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CredentialCipher.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CredentialCipher.kt @@ -27,8 +27,23 @@ object CredentialCipher { fun interface KeyProvider { /** The key, created on first use. Throws when no key can be had (no Keystore on this ROM). */ fun key(): SecretKey + + /** The key that sealed earlier files: never a new one. Throws [KeyMissing] when there is none. */ + fun existing(): SecretKey = key() } + /** The Keystore answered and holds no key: nothing sealed before can open again. */ + class KeyMissing : java.security.GeneralSecurityException("no key") + + /** + * Whether [e], from [open], means the file can never open: it does not authenticate (tampered, + * or sealed under another key), the key is permanently invalidated or gone, or the file is not + * an envelope. Anything else - the Keystore busy or erroring, an I/O error - may pass. + */ + fun isPermanent(e: Throwable): Boolean = e is javax.crypto.AEADBadTagException || + e is android.security.keystore.KeyPermanentlyInvalidatedException || + e is KeyMissing || e is org.json.JSONException || e is IllegalArgumentException + /** * An AES-256 key in the AndroidKeyStore: not exportable, encrypt/decrypt with GCM only, no user * authentication (background downloads and launch-time code fetches use it with the screen @@ -38,6 +53,12 @@ object CredentialCipher { private const val ALIAS = "droiddeck-store-credentials" private const val PROVIDER = "AndroidKeyStore" + @Synchronized + override fun existing(): SecretKey { + val ks = KeyStore.getInstance(PROVIDER).apply { load(null) } + return ks.getKey(ALIAS, null) as? SecretKey ?: throw KeyMissing() + } + @Synchronized override fun key(): SecretKey { val ks = KeyStore.getInstance(PROVIDER).apply { load(null) } @@ -73,7 +94,7 @@ object CredentialCipher { require(envelope.optInt("v", -1) == VERSION && envelope.optString("alg") == ALG) { "unknown envelope" } val iv = Base64.decode(envelope.getString("iv"), Base64.NO_WRAP) val ct = Base64.decode(envelope.getString("ct"), Base64.NO_WRAP) - val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, keys.key(), GCMParameterSpec(TAG_BITS, iv)) } + val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, keys.existing(), GCMParameterSpec(TAG_BITS, iv)) } return String(cipher.doFinal(ct), Charsets.UTF_8) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt index 88b4f56201..77599e0a47 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt @@ -18,8 +18,9 @@ import java.io.File * start), verified by opening it again, and the plain text is replaced. * - Where the Keystore does not work (some ROMs), the file stays plain, the log says so once, and * the next start tries again. - * - A sealed file that no longer opens (the key is gone: data cleared, a backup restored on another - * device) is deleted and the store reads as signed out. + * - A sealed file that can never open again (the key is gone: data cleared, a backup restored on + * another device) is deleted and the store reads as signed out; one that fails for a reason that + * may pass is kept and tried again (see [read]). */ object StoreAccounts { private const val TAG = "StoreAccounts" @@ -39,36 +40,69 @@ object StoreAccounts { fun credentialsFile(context: Context, store: Store): File = File(dir(context, store), FILE) - /** The stored credentials, or null when signed out or unreadable (never logged: the text is the secret). */ + /** Stores whose sealed sign-in could not be opened this time for a reason that may pass (see [read]). */ + private val unavailable = java.util.concurrent.ConcurrentHashMap.newKeySet() + + @Volatile + private var unavailableLogged = false + + /** + * The stored credentials, or null when signed out or unreadable (never logged: the text is the + * secret). + * + * A sealed file is deleted - the store signs in again - only when it can never open: it does + * not authenticate (tampered, or another key: data cleared, restored on another device), the + * key is permanently invalidated or gone from the Keystore, or it is not an envelope at all. Any + * other failure (the Keystore busy or erroring, an I/O error) keeps the file, marks the store + * [isUnavailable] - signed in, its actions failing for now - and the next read tries again. + */ @Synchronized fun read(context: Context, store: Store): JSONObject? { val f = credentialsFile(context, store) - if (!f.isFile) return null - val json = try { JSONObject(f.readText()) } catch (e: Exception) { - Log.w(TAG, "${store.id}: credentials unreadable (${e.javaClass.simpleName})"); null - } ?: return null + if (!f.isFile) { unavailable.remove(store); return null } + val text = try { f.readText() } catch (e: Exception) { return markUnavailable(store, e) } + val json = try { JSONObject(text) } catch (e: Exception) { return unreadable(f, store, e) } if (!CredentialCipher.isEnvelope(json)) { + unavailable.remove(store) seal(f, json)?.let { Log.i(TAG, "stores: credentials encrypted ${store.id}") } return json } return try { - JSONObject(CredentialCipher.open(json, keys)) + JSONObject(CredentialCipher.open(json, keys)).also { unavailable.remove(store) } } catch (e: Exception) { - // The key that sealed it is gone; the sign-in cannot come back, so the store signs in again. - Log.w(TAG, "stores: credentials for ${store.id} cannot be opened (${e.javaClass.simpleName}); signed out") - f.delete() - null + if (CredentialCipher.isPermanent(e)) unreadable(f, store, e) else markUnavailable(store, e) } } + /** The store's sign-in is on disk but could not be opened this time (see [read]). */ + fun isUnavailable(store: Store): Boolean = store in unavailable + + private fun unreadable(f: File, store: Store, e: Exception): JSONObject? { + Log.w(TAG, "stores: credentials for ${store.id} cannot be opened (${e.javaClass.simpleName}); signed out") + f.delete() + unavailable.remove(store) + return null + } + + private fun markUnavailable(store: Store, e: Exception): JSONObject? { + unavailable.add(store) + if (!unavailableLogged) { + unavailableLogged = true + Log.w(TAG, "stores: credentials unreadable this start (${e.javaClass.simpleName})") + } + return null + } + @Synchronized fun write(context: Context, store: Store, json: JSONObject) { + unavailable.remove(store) val f = credentialsFile(context, store) if (seal(f, json) == null) put(f, json.toString()) } @Synchronized fun clear(context: Context, store: Store) { + unavailable.remove(store) credentialsFile(context, store).delete() File(credentialsFile(context, store).path + ".tmp").delete() } @@ -82,9 +116,13 @@ object StoreAccounts { } } - /** The account's display name when signed in (the store's own name for it, or a stand-in), else null. */ + /** + * The account's display name when signed in (the store's own name for it, or a stand-in), else + * null. A sign-in that could not be opened this time ([isUnavailable]) still counts, under the + * store's name, so the sign-in card does not ask for what is still there. + */ fun signedInAs(context: Context, store: Store): String? { - val json = read(context, store) ?: return null + val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null if (json.optString("access_token", "").isEmpty()) return null return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index 02111bed57..c969e19e14 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -118,6 +118,11 @@ object StoresState { fun isSignedIn(store: Store): Boolean = accounts.containsKey(store) + /** A store action's error line when it found no usable sign-in: gone, or on disk but unreadable for now. */ + fun notSignedInLine(store: Store): String = + if (StoreAccounts.isUnavailable(store)) "${store.shortLabel} sign-in could not be read: try again." + else "${store.shortLabel} session expired: sign in again." + /** Stores whose sign-in has run out (a launch could not get a code): their chip dims until the user signs in again. */ val expired = mutableStateMapOf() diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt index d51a284109..cf40c19e67 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt @@ -55,7 +55,7 @@ object AmazonBackend : StoreBackend { when (result) { is AmazonLibrary.SyncResult.Ok -> { publish(app, result.games); StoresState.problems.remove(store) } is AmazonLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message - AmazonLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "Amazon session expired: sign in again." + AmazonLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store) AmazonLibrary.SyncResult.Throttled -> publish(app, AmazonLibrary.cached(app)) AmazonLibrary.SyncResult.Busy -> {} } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLibrary.kt b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLibrary.kt index 75331ba2ca..401fd09cb6 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonLibrary.kt @@ -6,6 +6,7 @@ import android.util.Log import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreNet +import com.droiddeck.launcher.stores.StoresState import org.json.JSONArray import org.json.JSONObject import java.util.concurrent.Callable @@ -70,7 +71,7 @@ object AmazonLibrary { } onStatus("Checking sign-in…") val creds = AmazonCredentialStore.load(app) ?: return SyncResult.NotLoggedIn - val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed("Amazon session expired: sign in again.") + val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed(StoresState.notSignedInLine(Store.AMAZON)) onStatus("Fetching game list…") val all = AmazonApiClient.getEntitlements(token, creds.deviceSerial) if (all.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Amazon library") else SyncResult.Ok(cachedList) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt index 41d4a2367a..9fa0e05d06 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt @@ -53,7 +53,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { EpicLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) } is EpicLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message - EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "Epic session expired: sign in again." + EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store) EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached.map { EpicLibrary.toCatalogItem(app, it) }) EpicLibrary.SyncResult.Busy -> {} } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt index 0237d4de52..3de03c68d5 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt @@ -42,7 +42,7 @@ object GogBackend : StoreBackend { when (result) { is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) } is GogLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message - GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "GOG session expired: sign in again." + GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store) GogLibrary.SyncResult.Busy -> {} } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt index 109fbf9f19..b4346c7ca5 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt @@ -33,7 +33,10 @@ class StoreAccountsCipherTest { private fun file(store: Store) = StoreAccounts.credentialsFile(app, store) @Before fun setUp() { StoreAccounts.keys = fake; StoreAccounts.keystoreFailed = false } - @After fun tearDown() { StoreAccounts.keys = CredentialCipher.Keystore; StoreAccounts.keystoreFailed = false } + @After fun tearDown() { + StoreAccounts.keys = CredentialCipher.Keystore; StoreAccounts.keystoreFailed = false + for (store in Store.entries) StoreAccounts.clear(app, store) + } @Test fun envelopeRoundTrips() { val envelope = CredentialCipher.seal(creds.toString(), fake) @@ -119,4 +122,52 @@ class StoreAccountsCipherTest { assertFalse(file(Store.GOG).exists()) assertNull(StoreAccounts.read(app, Store.GOG)) } + + /** A Keystore whose key is there but which fails to hand it over [failures] times first. */ + private class Flaky(private val key: SecretKey, var failures: Int, private val error: () -> Exception) : CredentialCipher.KeyProvider { + override fun key(): SecretKey = key + override fun existing(): SecretKey { if (failures > 0) { failures--; throw error() }; return key } + } + + @Test fun aTransientKeystoreFailureKeepsTheFileAndALaterReadSucceeds() { + StoreAccounts.write(app, Store.EPIC, creds) + val sealed = file(Store.EPIC).readText() + for (error in listOf<() -> Exception>( + { java.security.ProviderException("busy") }, + { java.security.KeyStoreException("keystore down") }, + { java.security.InvalidKeyException("not now") }, + { java.io.IOException("read") }, + )) { + StoreAccounts.keys = Flaky(key, 1, error) + assertNull(StoreAccounts.read(app, Store.EPIC)) + assertTrue(StoreAccounts.isUnavailable(Store.EPIC)) + assertEquals(sealed, file(Store.EPIC).readText()) + // Still signed in for the page: no sign-in card, and an action says why it failed. + assertEquals("Epic sign-in could not be read: try again.", StoresState.notSignedInLine(Store.EPIC)) + + // The next access, once the Keystore answers. + assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString()) + assertFalse(StoreAccounts.isUnavailable(Store.EPIC)) + assertEquals("Someone", StoreAccounts.signedInAs(app, Store.EPIC)) + assertEquals("Epic session expired: sign in again.", StoresState.notSignedInLine(Store.EPIC)) + } + } + + @Test fun signedInAsKeepsTheStoreWhileItsSignInIsUnavailable() { + StoreAccounts.write(app, Store.GOG, creds) + StoreAccounts.keys = Flaky(key, 5) { java.security.ProviderException("busy") } + assertEquals("GOG", StoreAccounts.signedInAs(app, Store.GOG)) + assertTrue(file(Store.GOG).exists()) + } + + @Test fun aKeyGoneFromTheKeystoreReadsAsSignedOutAndIsDeleted() { + StoreAccounts.write(app, Store.AMAZON, creds) + StoreAccounts.keys = object : CredentialCipher.KeyProvider { + override fun key(): SecretKey = newKey() + override fun existing(): SecretKey = throw CredentialCipher.KeyMissing() + } + assertNull(StoreAccounts.read(app, Store.AMAZON)) + assertFalse(StoreAccounts.isUnavailable(Store.AMAZON)) + assertFalse(file(Store.AMAZON).exists()) + } } diff --git a/docs/development/stores.md b/docs/development/stores.md index 3933b7906f..4ce7d1aab3 100644 --- a/docs/development/stores.md +++ b/docs/development/stores.md @@ -207,8 +207,16 @@ tokens live. - **No Keystore** (some ROMs): the file stays plain, the log says `stores: keystore unavailable, credentials stay plain ()` once, and the next start tries again. -- **A file that no longer opens** (key invalidated: data cleared, a backup restored on another - device, tampering): deleted, and the store reads as signed out, so its sign-in card shows. +- **A file that can never open** - it does not authenticate (`AEADBadTagException`: tampered, or + another key after data was cleared or a backup restored on another device), the key is + permanently invalidated or gone from the Keystore, or it is not an envelope: deleted, and the + store reads as signed out, so its sign-in card shows. +- **A failure that may pass** (`KeyStoreException`, `ProviderException`, any other + `InvalidKeyException`, an I/O error, StrongBox busy): the file is kept, the store stays signed in + (no sign-in card) and is marked unavailable (`StoreAccounts.isUnavailable`), a store action shows + ` sign-in could not be read: try again.`, the log says + `stores: credentials unreadable this start ()` once, and the next access tries + again. - **The Linux session:** the app's files directory is bound into every session, so the guest can see `credentials.json` - as the envelope only; the key never leaves the Keystore. Nothing in the guest reads the files: `droiddeck-store-launch` asks the app over `/stores/req|resp` diff --git a/docs/progress-log.md b/docs/progress-log.md index 96c4faad95..7d15e1d2cc 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -15,12 +15,16 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d `StoreAccounts` is the one layer; `CredentialCipher` holds the envelope and the key. - **Upgrade:** a plain file is sealed at the first start (verified, then replaced); users stay signed in. Log: `stores: credentials encrypted `. -- **Fallbacks:** no Keystore - stays plain, logged once, retried next start; a file that will not - open - deleted, signed out (sign-in card), never a crash. +- **Fallbacks:** no Keystore - stays plain, logged once, retried next start. A file that can never + open (bad tag, key invalidated or missing, not an envelope) - deleted, signed out (sign-in card). + Any other Keystore or I/O failure - file kept, store stays signed in but unavailable (actions show + ` sign-in could not be read: try again.`), logged once, retried on the next access. Never + a crash. - **Session:** the guest sees the envelope only; it never read the files (the Epic code comes over the request channel, written beside the launcher and deleted by it). - **Tests:** `StoreAccountsCipherTest` (round trip, sealed on disk, migration of all three stores, - tampered file, lost key, garbage, no-Keystore fallback then sealed next start, sign-out). Not yet + tampered file, lost key, key missing, garbage, no-Keystore fallback then sealed next start, + transient Keystore / I/O failures keep the file and a later read succeeds, sign-out). Not yet on a device. ## 2026-10-08 - `feat/private-logs`: every log in app-private storage, shared as one scrubbed zip