No need to use @SuppressLint("NewApi") when @ChecksSdkIntAtLeast is used - more cleanup

This commit is contained in:
Benoit Marty 2022-09-16 18:02:40 +02:00 committed by Benoit Marty
parent 658a09ea6a
commit 7f5c712e88
13 changed files with 15 additions and 40 deletions

View File

@ -131,11 +131,10 @@ class SecretStoringUtils @Inject constructor(
* *
* The secret is encrypted using the following method: AES/GCM/NoPadding * The secret is encrypted using the following method: AES/GCM/NoPadding
*/ */
@SuppressLint("NewApi")
@Throws(Exception::class) @Throws(Exception::class)
fun securelyStoreBytes(secret: ByteArray, keyAlias: String): ByteArray { fun securelyStoreBytes(secret: ByteArray, keyAlias: String): ByteArray {
return when { return when {
buildVersionSdkIntProvider.get() >= Build.VERSION_CODES.M -> encryptBytesM(secret, keyAlias) buildVersionSdkIntProvider.isAtLeast(Build.VERSION_CODES.M) -> encryptBytesM(secret, keyAlias)
else -> encryptBytes(secret, keyAlias) else -> encryptBytes(secret, keyAlias)
} }
} }
@ -156,10 +155,9 @@ class SecretStoringUtils @Inject constructor(
} }
} }
@SuppressLint("NewApi")
fun securelyStoreObject(any: Any, keyAlias: String, output: OutputStream) { fun securelyStoreObject(any: Any, keyAlias: String, output: OutputStream) {
when { when {
buildVersionSdkIntProvider.get() >= Build.VERSION_CODES.M -> saveSecureObjectM(keyAlias, output, any) buildVersionSdkIntProvider.isAtLeast(Build.VERSION_CODES.M) -> saveSecureObjectM(keyAlias, output, any)
else -> saveSecureObject(keyAlias, output, any) else -> saveSecureObject(keyAlias, output, any)
} }
} }
@ -189,7 +187,6 @@ class SecretStoringUtils @Inject constructor(
return cipher return cipher
} }
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.M) @RequiresApi(Build.VERSION_CODES.M)
private fun getOrGenerateSymmetricKeyForAliasM(alias: String): SecretKey { private fun getOrGenerateSymmetricKeyForAliasM(alias: String): SecretKey {
val secretKeyEntry = (keyStore.getEntry(alias, null) as? KeyStore.SecretKeyEntry) val secretKeyEntry = (keyStore.getEntry(alias, null) as? KeyStore.SecretKeyEntry)

View File

@ -16,7 +16,6 @@
package im.vector.app.core.extensions package im.vector.app.core.extensions
import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import android.net.ConnectivityManager import android.net.ConnectivityManager
@ -91,10 +90,9 @@ fun Context.safeOpenOutputStream(uri: Uri): OutputStream? {
* *
* @return true if no active connection is found * @return true if no active connection is found
*/ */
@SuppressLint("NewApi") // false positive
fun Context.inferNoConnectivity(sdkIntProvider: BuildVersionSdkIntProvider): Boolean { fun Context.inferNoConnectivity(sdkIntProvider: BuildVersionSdkIntProvider): Boolean {
val connectivityManager = getSystemService<ConnectivityManager>()!! val connectivityManager = getSystemService<ConnectivityManager>()!!
return if (sdkIntProvider.get() > Build.VERSION_CODES.M) { return if (sdkIntProvider.isAtLeast(Build.VERSION_CODES.M)) {
val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
when { when {
networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true -> false networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true -> false

View File

@ -16,7 +16,6 @@
package im.vector.app.features.lifecycle package im.vector.app.features.lifecycle
import android.annotation.SuppressLint
import android.app.Activity import android.app.Activity
import android.app.ActivityManager import android.app.ActivityManager
import android.app.Application import android.app.Application
@ -91,7 +90,6 @@ class VectorActivityLifecycleCallbacks constructor(private val popupAlertManager
* *
* @return true if an app task is corrupted by a potentially malicious activity * @return true if an app task is corrupted by a potentially malicious activity
*/ */
@SuppressLint("NewApi")
private suspend fun isTaskCorrupted(activity: Activity): Boolean = withContext(Dispatchers.Default) { private suspend fun isTaskCorrupted(activity: Activity): Boolean = withContext(Dispatchers.Default) {
val context = activity.applicationContext val context = activity.applicationContext
val packageManager: PackageManager = context.packageManager val packageManager: PackageManager = context.packageManager

View File

@ -144,7 +144,6 @@ class LoginCaptchaFragment :
// runOnUiThread(Runnable { finish() }) // runOnUiThread(Runnable { finish() })
} }
@SuppressLint("NewApi")
override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, errorResponse: WebResourceResponse) { override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, errorResponse: WebResourceResponse) {
super.onReceivedHttpError(view, request, errorResponse) super.onReceivedHttpError(view, request, errorResponse)

View File

@ -218,7 +218,6 @@ class NotificationUtils @Inject constructor(
* @param withProgress true to show indeterminate progress on the notification * @param withProgress true to show indeterminate progress on the notification
* @return the polling thread listener notification * @return the polling thread listener notification
*/ */
@SuppressLint("NewApi")
fun buildForegroundServiceNotification(@StringRes subTitleResId: Int, withProgress: Boolean = true): Notification { fun buildForegroundServiceNotification(@StringRes subTitleResId: Int, withProgress: Boolean = true): Notification {
// build the pending intent go to the home screen if this is clicked. // build the pending intent go to the home screen if this is clicked.
val i = HomeActivity.newIntent(context, firstStartMainActivity = false) val i = HomeActivity.newIntent(context, firstStartMainActivity = false)
@ -287,7 +286,6 @@ class NotificationUtils @Inject constructor(
* @param fromBg true if the app is in background when posting the notification * @param fromBg true if the app is in background when posting the notification
* @return the call notification. * @return the call notification.
*/ */
@SuppressLint("NewApi")
fun buildIncomingCallNotification( fun buildIncomingCallNotification(
call: WebRtcCall, call: WebRtcCall,
title: String, title: String,
@ -420,7 +418,6 @@ class NotificationUtils @Inject constructor(
* @param title title of the notification * @param title title of the notification
* @return the call notification. * @return the call notification.
*/ */
@SuppressLint("NewApi")
fun buildPendingCallNotification( fun buildPendingCallNotification(
call: WebRtcCall, call: WebRtcCall,
title: String title: String

View File

@ -92,7 +92,6 @@ class CaptchaWebview @Inject constructor(
Timber.e("## onError() : $errorMessage") Timber.e("## onError() : $errorMessage")
} }
@SuppressLint("NewApi")
override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, errorResponse: WebResourceResponse) { override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, errorResponse: WebResourceResponse) {
super.onReceivedHttpError(view, request, errorResponse) super.onReceivedHttpError(view, request, errorResponse)
when { when {

View File

@ -16,7 +16,6 @@
package im.vector.app.features.pin.lockscreen.biometrics package im.vector.app.features.pin.lockscreen.biometrics
import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.os.Build import android.os.Build
import androidx.annotation.MainThread import androidx.annotation.MainThread
@ -156,7 +155,6 @@ class BiometricHelper @AssistedInject constructor(
return authenticate(activity) return authenticate(activity)
} }
@SuppressLint("NewApi")
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
private fun authenticateInternal( private fun authenticateInternal(
activity: FragmentActivity, activity: FragmentActivity,

View File

@ -16,7 +16,6 @@
package im.vector.app.features.pin.lockscreen.crypto package im.vector.app.features.pin.lockscreen.crypto
import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.os.Build import android.os.Build
import android.security.keystore.KeyPermanentlyInvalidatedException import android.security.keystore.KeyPermanentlyInvalidatedException
@ -55,7 +54,6 @@ class KeyStoreCrypto @AssistedInject constructor(
* Ensures a [Key] for the [alias] exists and validates it. * Ensures a [Key] for the [alias] exists and validates it.
* @throws KeyPermanentlyInvalidatedException if key is not valid. * @throws KeyPermanentlyInvalidatedException if key is not valid.
*/ */
@SuppressLint("NewApi")
@Throws(KeyPermanentlyInvalidatedException::class) @Throws(KeyPermanentlyInvalidatedException::class)
fun ensureKey() = secretStoringUtils.ensureKey(alias).also { fun ensureKey() = secretStoringUtils.ensureKey(alias).also {
// Check validity of Key by initializing an encryption Cipher // Check validity of Key by initializing an encryption Cipher
@ -109,10 +107,9 @@ class KeyStoreCrypto @AssistedInject constructor(
/** /**
* Check if the key associated with the [alias] is valid. * Check if the key associated with the [alias] is valid.
*/ */
@SuppressLint("NewApi")
fun hasValidKey(): Boolean { fun hasValidKey(): Boolean {
val keyExists = hasKey() val keyExists = hasKey()
return if (buildVersionSdkIntProvider.get() >= Build.VERSION_CODES.M && keyExists) { return if (buildVersionSdkIntProvider.isAtLeast(Build.VERSION_CODES.M) && keyExists) {
val initializedKey = tryOrNull("Error validating lockscreen system key.") { ensureKey() } val initializedKey = tryOrNull("Error validating lockscreen system key.") { ensureKey() }
initializedKey != null initializedKey != null
} else { } else {

View File

@ -16,7 +16,6 @@
package im.vector.app.features.pin.lockscreen.crypto package im.vector.app.features.pin.lockscreen.crypto
import android.annotation.SuppressLint
import android.os.Build import android.os.Build
import im.vector.app.features.pin.lockscreen.crypto.migrations.LegacyPinCodeMigrator import im.vector.app.features.pin.lockscreen.crypto.migrations.LegacyPinCodeMigrator
import im.vector.app.features.pin.lockscreen.crypto.migrations.MissingSystemKeyMigrator import im.vector.app.features.pin.lockscreen.crypto.migrations.MissingSystemKeyMigrator

View File

@ -16,7 +16,6 @@
package im.vector.app.features.pin.lockscreen.crypto.migrations package im.vector.app.features.pin.lockscreen.crypto.migrations
import android.annotation.SuppressLint
import android.os.Build import android.os.Build
import im.vector.app.features.pin.lockscreen.crypto.KeyStoreCrypto import im.vector.app.features.pin.lockscreen.crypto.KeyStoreCrypto
import im.vector.app.features.pin.lockscreen.di.BiometricKeyAlias import im.vector.app.features.pin.lockscreen.di.BiometricKeyAlias
@ -38,9 +37,9 @@ class MissingSystemKeyMigrator @Inject constructor(
/** /**
* If user had biometric auth enabled, ensure system key exists, creating one if needed. * If user had biometric auth enabled, ensure system key exists, creating one if needed.
*/ */
@SuppressLint("NewApi")
fun migrateIfNeeded() { fun migrateIfNeeded() {
if (buildVersionSdkIntProvider.get() >= Build.VERSION_CODES.M && vectorPreferences.useBiometricsToUnlock()) { if (buildVersionSdkIntProvider.isAtLeast(Build.VERSION_CODES.M) &&
vectorPreferences.useBiometricsToUnlock()) {
val systemKeyStoreCrypto = keystoreCryptoFactory.provide(systemKeyAlias, true) val systemKeyStoreCrypto = keystoreCryptoFactory.provide(systemKeyAlias, true)
runCatching { runCatching {
systemKeyStoreCrypto.ensureKey() systemKeyStoreCrypto.ensureKey()

View File

@ -16,7 +16,6 @@
package im.vector.app.features.pin.lockscreen.ui package im.vector.app.features.pin.lockscreen.ui
import android.annotation.SuppressLint
import android.app.KeyguardManager import android.app.KeyguardManager
import android.os.Build import android.os.Build
import android.security.keystore.KeyPermanentlyInvalidatedException import android.security.keystore.KeyPermanentlyInvalidatedException
@ -139,12 +138,12 @@ class LockScreenViewModel @AssistedInject constructor(
} }
}.launchIn(viewModelScope) }.launchIn(viewModelScope)
@SuppressLint("NewApi")
private fun showBiometricPrompt(activity: FragmentActivity) = flow { private fun showBiometricPrompt(activity: FragmentActivity) = flow {
emitAll(biometricHelper.authenticate(activity)) emitAll(biometricHelper.authenticate(activity))
}.catch { error -> }.catch { error ->
when { when {
versionProvider.get() >= Build.VERSION_CODES.M && error is KeyPermanentlyInvalidatedException -> { versionProvider.isAtLeast(Build.VERSION_CODES.M) &&
error is KeyPermanentlyInvalidatedException -> {
onBiometricKeyInvalidated() onBiometricKeyInvalidated()
} }
else -> { else -> {
@ -168,15 +167,14 @@ class LockScreenViewModel @AssistedInject constructor(
_viewEvents.post(LockScreenViewEvent.ShowBiometricKeyInvalidatedMessage) _viewEvents.post(LockScreenViewEvent.ShowBiometricKeyInvalidatedMessage)
} }
@SuppressLint("NewApi")
private suspend fun updateStateWithBiometricInfo() { private suspend fun updateStateWithBiometricInfo() {
// This is a terrible hack, but I found no other way to ensure this would be called only after the device is considered unlocked on Android 12+ // This is a terrible hack, but I found no other way to ensure this would be called only after the device is considered unlocked on Android 12+
waitUntilKeyguardIsUnlocked() waitUntilKeyguardIsUnlocked()
setState { setState {
val isBiometricKeyInvalidated = biometricHelper.hasSystemKey && !biometricHelper.isSystemKeyValid val isBiometricKeyInvalidated = biometricHelper.hasSystemKey && !biometricHelper.isSystemKeyValid
val canUseBiometricAuth = lockScreenConfiguration.mode == LockScreenMode.VERIFY && val canUseBiometricAuth = lockScreenConfiguration.mode == LockScreenMode.VERIFY &&
!isSystemAuthTemporarilyDisabledByBiometricPrompt && !isSystemAuthTemporarilyDisabledByBiometricPrompt &&
biometricHelper.isSystemAuthEnabledAndValid biometricHelper.isSystemAuthEnabledAndValid
val showBiometricPromptAutomatically = canUseBiometricAuth && lockScreenConfiguration.autoStartBiometric val showBiometricPromptAutomatically = canUseBiometricAuth && lockScreenConfiguration.autoStartBiometric
copy( copy(
canUseBiometricAuth = canUseBiometricAuth, canUseBiometricAuth = canUseBiometricAuth,
@ -191,12 +189,12 @@ class LockScreenViewModel @AssistedInject constructor(
* after an Activity's `onResume` method. If we mix that with the system keys needing the device to be unlocked before they're used, we get crashes. * after an Activity's `onResume` method. If we mix that with the system keys needing the device to be unlocked before they're used, we get crashes.
* See issue [#6768](https://github.com/vector-im/element-android/issues/6768). * See issue [#6768](https://github.com/vector-im/element-android/issues/6768).
*/ */
@SuppressLint("NewApi")
private suspend fun waitUntilKeyguardIsUnlocked() { private suspend fun waitUntilKeyguardIsUnlocked() {
if (versionProvider.get() < Build.VERSION_CODES.S) return if (versionProvider.isAtLeast(Build.VERSION_CODES.S)) {
withTimeoutOrNull(5.seconds) { withTimeoutOrNull(5.seconds) {
while (keyguardManager.isDeviceLocked) { while (keyguardManager.isDeviceLocked) {
delay(50.milliseconds) delay(50.milliseconds)
}
} }
} }
} }

View File

@ -17,7 +17,6 @@
package im.vector.app.features.settings package im.vector.app.features.settings
import android.annotation.SuppressLint
import android.app.Activity import android.app.Activity
import android.content.Intent import android.content.Intent
import android.net.Uri import android.net.Uri
@ -448,7 +447,6 @@ class VectorSettingsSecurityPrivacyFragment :
/** /**
* Manage the e2e keys import. * Manage the e2e keys import.
*/ */
@SuppressLint("NewApi")
private fun importKeys() { private fun importKeys() {
openFileSelection( openFileSelection(
requireActivity(), requireActivity(),

View File

@ -16,7 +16,6 @@
package im.vector.app.features.widgets.webview package im.vector.app.features.widgets.webview
import android.annotation.SuppressLint
import android.app.Activity import android.app.Activity
import android.view.ViewGroup import android.view.ViewGroup
import android.webkit.CookieManager import android.webkit.CookieManager
@ -29,7 +28,6 @@ import im.vector.app.features.themes.ThemeUtils
import im.vector.app.features.webview.VectorWebViewClient import im.vector.app.features.webview.VectorWebViewClient
import im.vector.app.features.webview.WebEventListener import im.vector.app.features.webview.WebEventListener
@SuppressLint("NewApi")
fun WebView.setupForWidget(activity: Activity, fun WebView.setupForWidget(activity: Activity,
checkWebViewPermissionsUseCase: CheckWebViewPermissionsUseCase, checkWebViewPermissionsUseCase: CheckWebViewPermissionsUseCase,
eventListener: WebEventListener, eventListener: WebEventListener,