Delete grants when keypair is removed

Otherwise the grant will linger even if another keypair is installed
with the same alias. It's better if that doesn't happen.

Bug: 27335182
Change-Id: I72491201c807e3e70f0085e6f1b364d692de8d0a
diff --git a/src/com/android/keychain/KeyChainService.java b/src/com/android/keychain/KeyChainService.java
index cd2ac84..8ba71ac 100644
--- a/src/com/android/keychain/KeyChainService.java
+++ b/src/com/android/keychain/KeyChainService.java
@@ -72,6 +72,8 @@
 
     private static final String SELECTION_GRANTS_BY_UID = GRANTS_GRANTEE_UID + "=?";
 
+    private static final String SELECTION_GRANTS_BY_ALIAS = GRANTS_ALIAS + "=?";
+
     public KeyChainService() {
         super(KeyChainService.class.getSimpleName());
     }
@@ -157,6 +159,9 @@
                         + " be installed until device is unlocked");
                 return false;
             }
+            if (!removeKeyPair(alias)) {
+                return false;
+            }
             if (!mKeyStore.importKey(Credentials.USER_PRIVATE_KEY + alias, privateKey, -1,
                     KeyStore.FLAG_ENCRYPTED)) {
                 Log.e(TAG, "Failed to import private key " + alias);
@@ -176,7 +181,12 @@
 
         @Override public boolean removeKeyPair(String alias) {
             checkCertInstallerOrSystemCaller();
-            return Credentials.deleteAllTypesForAlias(mKeyStore, alias);
+            if (!Credentials.deleteAllTypesForAlias(mKeyStore, alias)) {
+                return false;
+            }
+            removeGrantsForAlias(alias);
+            broadcastStorageChange();
+            return true;
         }
 
         private X509Certificate parseCertificate(byte[] bytes) throws CertificateException {
@@ -365,6 +375,11 @@
         }
     }
 
+    private void removeGrantsForAlias(String alias) {
+        final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
+        db.delete(TABLE_GRANTS, SELECTION_GRANTS_BY_ALIAS, new String[] {alias});
+    }
+
     private void removeAllGrants(final SQLiteDatabase db) {
         db.delete(TABLE_GRANTS, null /* whereClause */, null /* whereArgs */);
     }