On-device signing: Make sure Keystore key has the correct boot level.

While Keystore itself enforces that these keys can only be created/used
during a certain boot level, we need to verify ourselves that the key
actually *has* the correct boot level.

Bug: 167516462
Test: atest
Change-Id: I096d63323e0faf7a97ec5f571d2fdcee75d47c6e
diff --git a/ondevice-signing/KeystoreKey.cpp b/ondevice-signing/KeystoreKey.cpp
index de7033f..7f290e3 100644
--- a/ondevice-signing/KeystoreKey.cpp
+++ b/ondevice-signing/KeystoreKey.cpp
@@ -151,8 +151,25 @@
     KeyEntryResponse keyEntryResponse;
     LOG(INFO) << "Trying to retrieve existing keystore key...";
     status = mService->getKeyEntry(descriptor, &keyEntryResponse);
-    if (!status.isOk()) {
-        LOG(INFO) << "Existing keystore key not found, creating new key";
+    bool keyValid = false;
+
+    if (status.isOk()) {
+        // Make sure this is an early boot key
+        for (const auto& auth : keyEntryResponse.metadata.authorizations) {
+            if (auth.keyParameter.tag == Tag::MAX_BOOT_LEVEL) {
+                if (auth.keyParameter.value.get<KeyParameterValue::integer>() == kOdsignBootLevel) {
+                    keyValid = true;
+                    break;
+                }
+            }
+        }
+        if (!keyValid) {
+            LOG(WARNING) << "Found invalid keystore key without MAX_BOOT_LEVEL tag";
+        }
+    }
+
+    if (!keyValid) {
+        LOG(INFO) << "Existing keystore key not found or invalid, creating new key";
         auto newKeyStatus = createNewKey(descriptor);
         if (!newKeyStatus.ok()) {
             LOG(ERROR) << "Failed to create new key";