Add PackageRemovedReceiver to remove keys of uninstalled packages.

We are adding a class to receive ACTION_PACKAGE_FULLY_REMOVED broadcast
from the system and using that to delete the appropriate keys from our
database.

Bug: 416768355
Test: Tested that the API works fine locally. Also tested in Pixel 9.
Flag: EXEMPT bugfix
Change-Id: Iff0f645deba25cf7839db0b7e53264e190cc1346
diff --git a/app/AndroidManifest.xml b/app/AndroidManifest.xml
index 7f054b9..392a8ec 100644
--- a/app/AndroidManifest.xml
+++ b/app/AndroidManifest.xml
@@ -24,10 +24,17 @@
         android:label="@string/app_name">
         <receiver android:name=".BootReceiver"
             android:exported="false">
-            <intent-filter >
+            <intent-filter>
                 <action android:name="android.intent.action.BOOT_COMPLETED"/>
             </intent-filter>
         </receiver>
+        <receiver android:name=".PackageRemovalReceiver"
+                  android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.PACKAGE_FULLY_REMOVED" />
+                <data android:scheme="package" />
+            </intent-filter>
+        </receiver>
         <service android:name=".provisioner.PeriodicProvisioner"
             android:permission="android.permission.BIND_JOB_SERVICE"
             android:exported="false">
@@ -44,5 +51,7 @@
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
 
 </manifest>
diff --git a/app/src/com/android/rkpdapp/PackageRemovalReceiver.java b/app/src/com/android/rkpdapp/PackageRemovalReceiver.java
new file mode 100644
index 0000000..5cf8959
--- /dev/null
+++ b/app/src/com/android/rkpdapp/PackageRemovalReceiver.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.rkpdapp;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import com.android.rkpdapp.database.ProvisionedKeyDao;
+import com.android.rkpdapp.database.RkpdDatabase;
+
+/**
+ * A receiver class that listens for package removed broadcast and removes the
+ * associated attestation key.
+ */
+public class PackageRemovalReceiver extends BroadcastReceiver {
+    private static final String TAG = "RkpdBroadcast";
+    private static final int KEYSTORE_SERVICE_UID = 1017;
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Log.i(TAG, "Caught package_removed intent, waking up.");
+        ThreadPool.EXECUTOR.execute(() -> processPackageRemovalIntent(context, intent));
+    }
+
+    private void processPackageRemovalIntent(Context context, Intent intent) {
+        ProvisionedKeyDao keyDao = RkpdDatabase.getDatabase(context).provisionedKeyDao();
+        int uid = intent.getExtras().getInt(Intent.EXTRA_UID);
+        keyDao.deleteAllKeysForClientAndKeyId(KEYSTORE_SERVICE_UID, uid);
+        Log.i(TAG, "Deleted associated keys for uid: " + uid);
+    }
+}
diff --git a/app/src/com/android/rkpdapp/database/ProvisionedKeyDao.java b/app/src/com/android/rkpdapp/database/ProvisionedKeyDao.java
index af18a25..d31ec9b 100644
--- a/app/src/com/android/rkpdapp/database/ProvisionedKeyDao.java
+++ b/app/src/com/android/rkpdapp/database/ProvisionedKeyDao.java
@@ -57,6 +57,13 @@
     public abstract void deleteKey(byte[] keyBlob);
 
     /**
+     * Delete all the provisioned keys for a given key_id for keystore service.
+     * 1017 is the keystore service user id.
+     */
+    @Query("DELETE FROM provisioned_keys WHERE key_id = :keyId AND client_uid = :clientId")
+    public abstract void deleteAllKeysForClientAndKeyId(int clientId, int keyId);
+
+    /**
      * Delete all the provisioned keys.
      */
     @Query("DELETE FROM provisioned_keys")
diff --git a/app/tests/unit/src/com/android/rkpdapp/unittest/RkpdDatabaseTest.java b/app/tests/unit/src/com/android/rkpdapp/unittest/RkpdDatabaseTest.java
index a21deb5..9dd451a 100644
--- a/app/tests/unit/src/com/android/rkpdapp/unittest/RkpdDatabaseTest.java
+++ b/app/tests/unit/src/com/android/rkpdapp/unittest/RkpdDatabaseTest.java
@@ -54,6 +54,7 @@
     private static final Instant TEST_KEY_EXPIRY = Instant.now().plus(Duration.ofHours(1));
     private static final int FAKE_CLIENT_UID = 1;
     private static final int FAKE_CLIENT_UID_2 = 2;
+    private static final int KEYSTORE_CLIENT_UID = 1017;
     private static final int FAKE_KEY_ID = 1;
     private static final int FAKE_CLIENT_UID_3 = 3;
     private static final int FAKE_KEY_ID_2 = 2;
@@ -184,6 +185,36 @@
         assertThat(key.keyBlob).isEqualTo(mProvisionedKey2.keyBlob);
     }
 
+    /* TODO: Uncomment this test once the code is out in the wild to prevent API not available
+     * failures.
+     */
+    /*
+    @Test
+    public void testDeleteSingleUidKey() {
+        ProvisionedKey key3 = new ProvisionedKey(TEST_KEY_BLOB_3, TEST_HAL_2, TEST_KEY_BLOB_3,
+                TEST_KEY_BLOB_3, TEST_KEY_EXPIRY);
+
+        mKeyDao.insertKeys(List.of(mProvisionedKey1, mProvisionedKey2, key3));
+        List<ProvisionedKey> keysInDatabase = mKeyDao.getAllKeys();
+        assertThat(keysInDatabase).hasSize(3);
+
+        assertThat(mKeyDao.getOrAssignKey(TEST_HAL_1, Instant.now(), KEYSTORE_CLIENT_UID,
+                FAKE_KEY_ID)).isNotNull();
+        assertThat(mKeyDao.getOrAssignKey(TEST_HAL_2, Instant.now(), KEYSTORE_CLIENT_UID,
+                FAKE_KEY_ID_2)).isNotNull();
+        assertThat(mKeyDao.getOrAssignKey(TEST_HAL_2, Instant.now(), FAKE_CLIENT_UID,
+                FAKE_KEY_ID)).isNotNull();
+
+        mKeyDao.deleteAllKeysForClientAndKeyId(KEYSTORE_CLIENT_UID, FAKE_KEY_ID);
+        keysInDatabase = mKeyDao.getAllKeys();
+        assertThat(keysInDatabase).hasSize(2);
+        assertThat(keysInDatabase.get(0).keyId).isEqualTo(FAKE_KEY_ID_2);
+
+        mKeyDao.deleteAllKeysForClientAndKeyId(KEYSTORE_CLIENT_UID, FAKE_KEY_ID_2);
+        keysInDatabase = mKeyDao.getAllKeys();
+        assertThat(keysInDatabase).hasSize(1);
+    }*/
+
     @Test
     public void testGetTotalExpiringKeysForIrpc() {
         final Instant past = Instant.now().minus(1000, ChronoUnit.MINUTES);