Clean up permissions when system app fails to scan

When a system APK fails to scan, the full uninstall flow
is not called for the app. So if it had a data variant
or was previously scanned before a system update, residual
data can remain.

This change only fixes up leftover permissions, and there
could be other unhandled cases.

Specifically this fixes the case where an OTA updates a
system app to a higher version that the data variant, but the APK
fails to scan due to invalid signature verification. This would
cause the app to be removed from the deviced entirely while
leaving a declared permission inside PermissionSettings which was
serialized to/from disk. This permission would be checked when
trying to manually install an update, which would verify against
a non-existent package, failing the install.

Because of the serialization, a reboot would not be enough to fix
this case. This reboot issue is technically still a problem if the
permission clean up fails for any reason. Perhaps a future refactor
can address the need to seriailize the permissions at all, and only
write the necessary state, removing state that doesn't have a valid
entry inside a known package.

If this case is ever hit, there will be no working application
on the device as it's assumed that all system packages will scan.
The data variant will be dropped.

Bug: 158567255

Test: atest com.android.server.pm.test.InvalidNewSystemAppTest

Change-Id: I7cbb6ac231a211543a6bd42c61e1c74112b81736
10 files changed