Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

refactor: introduce SafeEncryptedSharedPreferences to handle decryption failures and update branding in system prompts

Rishabh Bajpai5a40aa8b1d8d
diff --git a/app/src/main/java/com/gotcha/connectors/ConnectorCredentialStore.kt b/app/src/main/java/com/gotcha/connectors/ConnectorCredentialStore.kt
index cc35108..ba230d1 100644
--- a/app/src/main/java/com/gotcha/connectors/ConnectorCredentialStore.kt
+++ b/app/src/main/java/com/gotcha/connectors/ConnectorCredentialStore.kt
@@ -2,8 +2,7 @@ package com.gotcha.connectors
import android.content.Context
import android.content.SharedPreferences
-import androidx.security.crypto.EncryptedSharedPreferences
-import androidx.security.crypto.MasterKey
+import com.gotcha.data.SafeEncryptedSharedPreferences
/** Raw per-connector blob storage, implemented by the encrypted prod store and by test fakes. */
interface CredentialStore {
@@ -20,16 +19,7 @@ interface CredentialStore {
class ConnectorCredentialStore(context: Context) : CredentialStore {
private val prefs: SharedPreferences by lazy {
- val masterKey = MasterKey.Builder(context.applicationContext)
- .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
- .build()
- EncryptedSharedPreferences.create(
- context.applicationContext,
- "gotcha_connectors",
- masterKey,
- EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
- EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
- )
+ SafeEncryptedSharedPreferences.create(context, "gotcha_connectors")
}
override fun loadRaw(connectorId: String): String? = prefs.getString(connectorId, null)
diff --git a/app/src/main/java/com/gotcha/data/SafeEncryptedSharedPreferences.kt b/app/src/main/java/com/gotcha/data/SafeEncryptedSharedPreferences.kt
new file mode 100644
index 0000000..601d011
--- /dev/null
+++ b/app/src/main/java/com/gotcha/data/SafeEncryptedSharedPreferences.kt
@@ -0,0 +1,79 @@
+package com.gotcha.data
+
+import android.content.Context
+import android.content.SharedPreferences
+import android.util.Log
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+import java.security.KeyStore
+
+/**
+ * Factory for creating [EncryptedSharedPreferences] instances safely.
+ *
+ * If Android KeyStore key entries or the stored Tink keyset become corrupted or
+ * unreadable (e.g. after app reinstall, OS update, device restore, or key invalidation),
+ * [EncryptedSharedPreferences.create] throws an exception (such as [javax.crypto.AEADBadTagException]
+ * or [java.security.KeyStoreException]).
+ *
+ * This factory catches such errors, clears the corrupted shared preference file and master key,
+ * and recreates fresh encrypted preferences. If recovery still fails, it falls back to standard
+ * unencrypted [SharedPreferences] to ensure the application does not crash on startup.
+ */
+object SafeEncryptedSharedPreferences {
+ private const val TAG = "SafeEncryptedPrefs"
+
+ fun create(context: Context, fileName: String): SharedPreferences {
+ val appContext = context.applicationContext
+ return try {
+ buildEncryptedPrefs(appContext, fileName)
+ } catch (e: Throwable) {
+ Log.w(
+ TAG,
+ "EncryptedSharedPreferences creation failed for '$fileName'. Attempting recovery.",
+ e
+ )
+ recover(appContext, fileName)
+ }
+ }
+
+ private fun recover(context: Context, fileName: String): SharedPreferences {
+ try {
+ context.deleteSharedPreferences(fileName)
+ } catch (delErr: Exception) {
+ Log.w(TAG, "Failed to delete corrupt SharedPreferences file '$fileName'", delErr)
+ }
+
+ try {
+ val keyStore = KeyStore.getInstance("AndroidKeyStore")
+ keyStore.load(null)
+ keyStore.deleteEntry(MasterKey.DEFAULT_MASTER_KEY_ALIAS)
+ } catch (ksErr: Exception) {
+ Log.w(TAG, "Failed to clear master key alias from AndroidKeyStore", ksErr)
+ }
+
+ return try {
+ buildEncryptedPrefs(context, fileName)
+ } catch (retryErr: Throwable) {
+ Log.e(
+ TAG,
+ "Retry creating EncryptedSharedPreferences for '$fileName' failed. " +
+ "Falling back to unencrypted SharedPreferences.",
+ retryErr
+ )
+ context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
+ }
+ }
+
+ private fun buildEncryptedPrefs(context: Context, fileName: String): SharedPreferences {
+ val masterKey = MasterKey.Builder(context)
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
+ .build()
+ return EncryptedSharedPreferences.create(
+ context,
+ fileName,
+ masterKey,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
+ )
+ }
+}
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index 79cf2d5..d8b9e9e 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -2,8 +2,6 @@ package com.gotcha.data
import android.content.Context
import android.content.SharedPreferences
-import androidx.security.crypto.EncryptedSharedPreferences
-import androidx.security.crypto.MasterKey
import com.gotcha.audio.AudioProvider
data class Settings(
@@ -238,16 +236,7 @@ private const val LEGACY_THEME_MODE_LIGHT = "LIGHT"
class SettingsRepository(context: Context) {
val prefs: SharedPreferences by lazy {
- val masterKey = MasterKey.Builder(context.applicationContext)
- .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
- .build()
- EncryptedSharedPreferences.create(
- context.applicationContext,
- SETTINGS_PREFS_FILE,
- masterKey,
- EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
- EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
- )
+ SafeEncryptedSharedPreferences.create(context, SETTINGS_PREFS_FILE)
}
private fun stringSet(key: String, default: Set<String> = emptySet()): Set<String> =
diff --git a/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt b/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt
index 48291ae..6fe94c3 100644
--- a/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt
+++ b/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt
@@ -128,7 +128,7 @@ class PromptCacheAndTokenOptimizationTest {
val msg = engine.systemPromptMessage(com.gotcha.tools.AgentMode.OPERATOR)
assertEquals("system", msg.role)
val text = msg.textContent
- assertTrue("Should contain core Operator instructions", text.contains("You are Operator"))
+ assertTrue("Should contain core Operator instructions", text.contains("You are Gotcha"))
assertTrue("Should contain env block", text.contains("<env>"))
assertTrue("Should contain device model info", text.contains("Device model:"))
}
diff --git a/app/src/test/java/com/gotcha/data/SafeEncryptedSharedPreferencesTest.kt b/app/src/test/java/com/gotcha/data/SafeEncryptedSharedPreferencesTest.kt
new file mode 100644
index 0000000..09f9520
--- /dev/null
+++ b/app/src/test/java/com/gotcha/data/SafeEncryptedSharedPreferencesTest.kt
@@ -0,0 +1,44 @@
+package com.gotcha.data
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+
+@RunWith(RobolectricTestRunner::class)
+class SafeEncryptedSharedPreferencesTest {
+
+ private lateinit var context: Context
+
+ @Before
+ fun setUp() {
+ FakeAndroidKeyStore.setUp()
+ context = ApplicationProvider.getApplicationContext()
+ }
+
+ @Test
+ fun `create returns functional shared preferences`() {
+ val prefs = SafeEncryptedSharedPreferences.create(context, "test_safe_prefs")
+ assertNotNull(prefs)
+ prefs.edit().putString("test_key", "test_val").commit()
+ assertEquals("test_val", prefs.getString("test_key", null))
+ }
+
+ @Test
+ fun `recovery path handles corrupted preferences cleanly`() {
+ val prefName = "test_corrupt_prefs"
+ // Seed corrupt/malformed XML file
+ val rawPrefs = context.getSharedPreferences(prefName, Context.MODE_PRIVATE)
+ rawPrefs.edit().putString("corrupted_data", "invalid_encrypted_format").commit()
+
+ val safePrefs = SafeEncryptedSharedPreferences.create(context, prefName)
+ assertNotNull(safePrefs)
+ safePrefs.edit().putString("recovered_key", "recovered_val").commit()
+ assertEquals("recovered_val", safePrefs.getString("recovered_key", null))
+ }
+}