BIT-2439: Handle invalid patterns when processing regular expression matching (#3397)

This commit is contained in:
David Perez 2024-07-03 09:56:09 -05:00 committed by GitHub
parent 074979095b
commit c3d2389829
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 38 additions and 3 deletions

View file

@ -9,12 +9,12 @@ import com.x8bit.bitwarden.data.platform.util.getDomainOrNull
import com.x8bit.bitwarden.data.platform.util.getHostWithPortOrNull
import com.x8bit.bitwarden.data.platform.util.getWebHostFromAndroidUriOrNull
import com.x8bit.bitwarden.data.platform.util.isAndroidApp
import com.x8bit.bitwarden.data.platform.util.regexOrNull
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
import com.x8bit.bitwarden.data.vault.repository.model.DomainsData
import com.x8bit.bitwarden.ui.platform.feature.settings.autofill.util.toSdkUriMatchType
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.mapNotNull
import kotlin.text.Regex
import kotlin.text.RegexOption
import kotlin.text.isNullOrBlank
import kotlin.text.lowercase
@ -212,8 +212,9 @@ private fun LoginUriView.checkForMatch(
UriMatchType.NEVER -> MatchResult.NONE
UriMatchType.REGULAR_EXPRESSION -> {
val pattern = Regex(loginViewUri, RegexOption.IGNORE_CASE)
exactIfTrue(matchUri.matches(pattern))
regexOrNull(loginViewUri, RegexOption.IGNORE_CASE)
?.let { exactIfTrue(matchUri.matches(it)) }
?: MatchResult.NONE
}
UriMatchType.STARTS_WITH -> exactIfTrue(matchUri.startsWith(loginViewUri))

View file

@ -0,0 +1,16 @@
package com.x8bit.bitwarden.data.platform.util
import java.util.regex.PatternSyntaxException
/**
* Attempts to create a [Regex] and returns `null` if the [pattern] is not valid.
*/
fun regexOrNull(
pattern: String,
option: RegexOption,
): Regex? =
try {
Regex(pattern, option)
} catch (e: PatternSyntaxException) {
null
}

View file

@ -0,0 +1,18 @@
package com.x8bit.bitwarden.data.platform.util
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
class RegexUtilsTest {
@Test
fun `regexOrNull should return nonnull when pattern is valid`() {
assertNotNull(regexOrNull(pattern = ".*/", option = RegexOption.IGNORE_CASE))
}
@Test
fun `regexOrNull should return null when pattern is invalid`() {
assertNull(regexOrNull(pattern = ".*\\", option = RegexOption.IGNORE_CASE))
}
}