diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicy.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicy.kt new file mode 100644 index 000000000..391d4847b --- /dev/null +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicy.kt @@ -0,0 +1,142 @@ +/* + * Copyright 2025 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.firebase.ui.auth.configuration.password_policy + +import org.json.JSONException +import org.json.JSONObject + +/** + * A Firebase project's password policy, as returned by Identity Toolkit `v2/passwordPolicy`. + * + * [minPasswordLength] defaults to 6 when the server omits it. A `null` length or `false` + * character flag means the policy does not configure that requirement. + */ +internal data class PasswordPolicy( + val minPasswordLength: Int, + val maxPasswordLength: Int?, + val containsLowercaseCharacter: Boolean, + val containsUppercaseCharacter: Boolean, + val containsNumericCharacter: Boolean, + val containsNonAlphanumericCharacter: Boolean, + val allowedNonAlphanumericCharacters: List, + val enforcementState: EnforcementState, +) { + internal enum class EnforcementState { ENFORCE, OFF } + + private val allowedSymbols: Set by lazy { + allowedNonAlphanumericCharacters.joinToString("").toSet() + } + + /** + * Evaluates [password] the way the JS SDK's `PasswordPolicyImpl.validatePassword` does. + * + * Length is UTF-16 code units (`String.length`, same as JS). Character classes are ASCII + * only and checked independently, so a character in [allowedNonAlphanumericCharacters] + * counts as a symbol even if it is also alphanumeric. Any other character is neither + * counted nor rejected. + */ + fun validate(password: String): PasswordValidationStatus { + var lower = false + var upper = false + var numeric = false + var symbol = false + for (c in password) { + if (c in 'a'..'z') lower = true + if (c in 'A'..'Z') upper = true + if (c in '0'..'9') numeric = true + if (c in allowedSymbols) symbol = true + } + return PasswordValidationStatus( + meetsMinPasswordLength = password.length >= minPasswordLength, + meetsMaxPasswordLength = maxPasswordLength?.let { password.length <= it }, + containsLowercaseLetter = lower.takeIf { containsLowercaseCharacter }, + containsUppercaseLetter = upper.takeIf { containsUppercaseCharacter }, + containsNumericCharacter = numeric.takeIf { containsNumericCharacter }, + containsNonAlphanumericCharacter = symbol.takeIf { containsNonAlphanumericCharacter }, + ) + } + + companion object { + internal const val DEFAULT_MIN_PASSWORD_LENGTH = 6 + private const val SUPPORTED_SCHEMA_VERSION = 1 + + /** + * Parses a `v2/passwordPolicy` response body. Returns `null` for malformed JSON or a + * `schemaVersion` that is not the number 1 (missing, `"1"` and `1.9` are rejected, as with + * the JS SDK's `!== 1`). Unknown enforcement states are OFF. A JSON `null` length is + * treated as absent, as is a `maxPasswordLength` of 0 or less, as JS does for a falsy value. + */ + fun parse(body: String): PasswordPolicy? = try { + val json = JSONObject(body) + val schemaVersion = json.opt("schemaVersion") as? Number + if (schemaVersion?.toDouble() != SUPPORTED_SCHEMA_VERSION.toDouble()) { + null + } else { + val options = json.optJSONObject("customStrengthOptions") ?: JSONObject() + val symbols = json.optJSONArray("allowedNonAlphanumericCharacters") + PasswordPolicy( + minPasswordLength = if (options.isNull("minPasswordLength")) { + DEFAULT_MIN_PASSWORD_LENGTH + } else { + options.getInt("minPasswordLength") + }, + maxPasswordLength = if (options.isNull("maxPasswordLength")) { + null + } else { + options.getInt("maxPasswordLength").takeIf { it > 0 } + }, + containsLowercaseCharacter = options.optBoolean("containsLowercaseCharacter"), + containsUppercaseCharacter = options.optBoolean("containsUppercaseCharacter"), + containsNumericCharacter = options.optBoolean("containsNumericCharacter"), + containsNonAlphanumericCharacter = + options.optBoolean("containsNonAlphanumericCharacter"), + allowedNonAlphanumericCharacters = if (symbols == null) { + emptyList() + } else { + List(symbols.length()) { symbols.getString(it) } + }, + enforcementState = if (json.optString("enforcementState") == "ENFORCE") { + EnforcementState.ENFORCE + } else { + EnforcementState.OFF + }, + ) + } + } catch (_: JSONException) { + null + } + } +} + +/** + * Per-requirement result of [PasswordPolicy.validate]. A `null` field is a requirement the + * policy does not configure; [isValid] is true when every configured requirement is met. + */ +internal data class PasswordValidationStatus( + val meetsMinPasswordLength: Boolean, + val meetsMaxPasswordLength: Boolean?, + val containsLowercaseLetter: Boolean?, + val containsUppercaseLetter: Boolean?, + val containsNumericCharacter: Boolean?, + val containsNonAlphanumericCharacter: Boolean?, +) { + val isValid: Boolean + get() = meetsMinPasswordLength && + meetsMaxPasswordLength != false && + containsLowercaseLetter != false && + containsUppercaseLetter != false && + containsNumericCharacter != false && + containsNonAlphanumericCharacter != false +} diff --git a/auth/src/main/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyRepository.kt b/auth/src/main/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyRepository.kt new file mode 100644 index 000000000..02bac2c91 --- /dev/null +++ b/auth/src/main/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyRepository.kt @@ -0,0 +1,230 @@ +/* + * Copyright 2025 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.firebase.ui.auth.configuration.password_policy + +import android.content.Context +import android.util.Log +import com.google.android.gms.common.util.AndroidUtilsLight +import com.google.android.gms.common.util.Hex +import com.google.firebase.auth.FirebaseAuth +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder +import java.util.concurrent.ConcurrentHashMap + +/** Blocking HTTP GET seam. Throws [java.io.IOException] on transport failure. */ +internal fun interface PasswordPolicyHttpClient { + fun get(url: String, headers: Map): HttpResponse + + /** [body] is read only for 2xx responses. */ + data class HttpResponse(val code: Int, val body: String?) +} + +/** Returns the uppercase hex SHA-1 of the app's signing certificate, or `null`. */ +internal fun interface CertificateHashProvider { + fun sha1Hex(context: Context, packageName: String): String? +} + +/** + * [HttpURLConnection] client. A 2xx body larger than [maxBodyBytes] throws [IOException] instead + * of being buffered. + */ +internal class UrlConnectionPasswordPolicyHttpClient( + private val connectTimeoutMs: Int = DEFAULT_TIMEOUT_MS, + private val readTimeoutMs: Int = DEFAULT_TIMEOUT_MS, + private val maxBodyBytes: Int = DEFAULT_MAX_BODY_BYTES, +) : PasswordPolicyHttpClient { + override fun get( + url: String, + headers: Map, + ): PasswordPolicyHttpClient.HttpResponse { + val connection = URL(url).openConnection() as HttpURLConnection + try { + connection.requestMethod = "GET" + connection.connectTimeout = connectTimeoutMs + connection.readTimeout = readTimeoutMs + connection.useCaches = false + headers.forEach { (name, value) -> connection.setRequestProperty(name, value) } + val code = connection.responseCode + val body = if (code in 200..299) { + connection.inputStream.use { readCapped(it) } + } else { + null + } + return PasswordPolicyHttpClient.HttpResponse(code, body) + } finally { + connection.disconnect() + } + } + + private fun readCapped(input: InputStream): String { + val out = ByteArrayOutputStream() + val buffer = ByteArray(BUFFER_BYTES) + while (true) { + val read = input.read(buffer) + if (read == -1) break + if (out.size() + read > maxBodyBytes) { + throw IOException("Response body exceeds $maxBodyBytes bytes") + } + out.write(buffer, 0, read) + } + return out.toString(Charsets.UTF_8.name()) + } + + internal companion object { + const val DEFAULT_TIMEOUT_MS = 10_000 + const val DEFAULT_MAX_BODY_BYTES = 64 * 1024 + private const val BUFFER_BYTES = 8 * 1024 + } +} + +/** Returns `null` instead of throwing, e.g. for an unknown package. */ +internal object PlayServicesCertificateHashProvider : CertificateHashProvider { + override fun sha1Hex(context: Context, packageName: String): String? = try { + AndroidUtilsLight.getPackageCertificateHashBytes(context, packageName) + ?.let { Hex.bytesToStringUppercase(it, false) } + } catch (_: Exception) { + null + } +} + +/** + * Fetches and caches the project password policy per FirebaseApp name and tenant ID. + * + * A fetched policy is cached until [refetchIfCached] replaces it. A failed fetch is cached as + * "no policy" for [failureTtlMs] so an offline or emulator setup does not refetch on every call. + * Every failure resolves to `null`; only exception class names are logged, never URLs or keys. + */ +internal class PasswordPolicyRepository( + private val httpClient: PasswordPolicyHttpClient = UrlConnectionPasswordPolicyHttpClient(), + private val certificateHash: CertificateHashProvider = PlayServicesCertificateHashProvider, + private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, + private val baseUrl: String = DEFAULT_BASE_URL, + private val failureTtlMs: Long = DEFAULT_FAILURE_TTL_MS, + private val clockMs: () -> Long = { System.nanoTime() / 1_000_000 }, + private val log: (String) -> Unit = { Log.w(TAG, it) }, +) { + private data class Key(val appName: String, val tenantId: String?) + + private sealed interface Entry { + data class Fetched(val policy: PasswordPolicy) : Entry + data class Failed(val atMs: Long) : Entry + } + + private val cache = ConcurrentHashMap() + private val locks = ConcurrentHashMap() + + /** Returns the cached policy for [auth], fetching it if absent or a failure has expired. */ + suspend fun getPolicy(context: Context, auth: FirebaseAuth): PasswordPolicy? { + val key = Key(auth.app.name, auth.tenantId) + return lockFor(key).withLock { + val entry = cache[key] + when { + entry is Entry.Fetched -> entry.policy + entry is Entry.Failed && clockMs() - entry.atMs < failureTtlMs -> null + else -> fetchAndStore(context, auth, key) + } + } + } + + /** + * Refetches only when a policy is already cached for [auth], matching the JS SDK's recache + * after `PASSWORD_DOES_NOT_MEET_REQUIREMENTS`. A failed refetch keeps the previous policy. + */ + suspend fun refetchIfCached(context: Context, auth: FirebaseAuth): PasswordPolicy? { + val key = Key(auth.app.name, auth.tenantId) + return lockFor(key).withLock { + val previous = (cache[key] as? Entry.Fetched)?.policy ?: return@withLock null + fetch(context, auth)?.also { cache[key] = Entry.Fetched(it) } ?: previous + } + } + + private fun lockFor(key: Key): Mutex = locks.getOrPut(key) { Mutex() } + + private suspend fun fetchAndStore( + context: Context, + auth: FirebaseAuth, + key: Key, + ): PasswordPolicy? { + val policy = fetch(context, auth) + cache[key] = if (policy != null) Entry.Fetched(policy) else Entry.Failed(clockMs()) + return policy + } + + private suspend fun fetch(context: Context, auth: FirebaseAuth): PasswordPolicy? = try { + withContext(ioDispatcher) { + val response = httpClient.get(buildUrl(auth), buildHeaders(context)) + if (response.code !in 200..299 || response.body == null) { + log("Password policy fetch failed: HTTP ${response.code}") + null + } else { + PasswordPolicy.parse(response.body) + ?: run { + log("Password policy response rejected") + null + } + } + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log("Password policy fetch failed: ${e.javaClass.name}") + null + } + + private fun buildUrl(auth: FirebaseAuth): String { + val apiKey = auth.app.options.apiKey + val tenantId = auth.tenantId + return buildString { + append(baseUrl).append("?key=").append(URLEncoder.encode(apiKey, UTF_8)) + if (tenantId != null) { + append("&tenantId=").append(URLEncoder.encode(tenantId, UTF_8)) + } + } + } + + private fun buildHeaders(context: Context): Map { + val packageName = context.packageName + val cert = try { + certificateHash.sha1Hex(context, packageName) + } catch (e: Exception) { + log("Certificate hash unavailable: ${e.javaClass.name}") + null + } + return buildMap { + put(HEADER_PACKAGE, packageName) + if (cert != null) put(HEADER_CERT, cert) + } + } + + companion object { + internal const val HEADER_PACKAGE = "X-Android-Package" + internal const val HEADER_CERT = "X-Android-Cert" + internal const val DEFAULT_BASE_URL = + "https://identitytoolkit.googleapis.com/v2/passwordPolicy" + internal const val DEFAULT_FAILURE_TTL_MS = 60_000L + private const val TAG = "PasswordPolicy" + private const val UTF_8 = "UTF-8" + } +} diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyRepositoryTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyRepositoryTest.kt new file mode 100644 index 000000000..e2c672f49 --- /dev/null +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyRepositoryTest.kt @@ -0,0 +1,351 @@ +/* + * Copyright 2025 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.firebase.ui.auth.configuration.password_policy + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.firebase.ui.auth.configuration.password_policy.PasswordPolicyHttpClient.HttpResponse +import com.firebase.ui.auth.configuration.password_policy.PasswordPolicyRepository.Companion.HEADER_CERT +import com.firebase.ui.auth.configuration.password_policy.PasswordPolicyRepository.Companion.HEADER_PACKAGE +import com.firebase.ui.auth.configuration.password_policy.PasswordPolicyTest.Companion.SAMPLE_RESPONSE +import com.google.common.truth.Truth.assertThat +import com.google.firebase.FirebaseApp +import com.google.firebase.FirebaseOptions +import com.google.firebase.auth.FirebaseAuth +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.asCoroutineDispatcher +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.IOException +import java.net.SocketTimeoutException +import java.util.concurrent.Executors + +/** + * Unit tests for [PasswordPolicyRepository] request shape, failure handling and caching. + * + * @suppress Internal test class + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE) +class PasswordPolicyRepositoryTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + + private class Request(val url: String, val headers: Map) + + private class FakeHttpClient( + var respond: (String) -> HttpResponse = { HttpResponse(200, SAMPLE_RESPONSE) }, + ) : PasswordPolicyHttpClient { + val requests = mutableListOf() + val threadNames = mutableListOf() + override fun get(url: String, headers: Map): HttpResponse { + synchronized(requests) { + requests += Request(url, headers) + threadNames += Thread.currentThread().name + } + return respond(url) + } + } + + private val http = FakeHttpClient() + private val logs = mutableListOf() + private var now = 0L + + private fun repository( + certificateHash: CertificateHashProvider = CertificateHashProvider { _, _ -> CERT }, + ioDispatcher: CoroutineDispatcher = Dispatchers.Unconfined, + ) = PasswordPolicyRepository( + httpClient = http, + certificateHash = certificateHash, + ioDispatcher = ioDispatcher, + clockMs = { now }, + log = { synchronized(logs) { logs += it } }, + ) + + private fun auth(appName: String = "[DEFAULT]", tenantId: String? = null): FirebaseAuth { + val options = FirebaseOptions.Builder() + .setApiKey(API_KEY) + .setApplicationId("1:123:android:abc") + .setProjectId("test-project") + .build() + val app = mock { + on { name } doReturn appName + on { this.options } doReturn options + } + return mock { + on { this.app } doReturn app + on { this.tenantId } doReturn tenantId + } + } + + // ============================================================================================= + // Request shape + // ============================================================================================= + + @Test + fun `success returns the parsed policy`() = runTest { + val policy = repository().getPolicy(context, auth()) + + assertThat(policy).isEqualTo(PasswordPolicy.parse(SAMPLE_RESPONSE)) + assertThat(http.requests.single().url).isEqualTo( + "https://identitytoolkit.googleapis.com/v2/passwordPolicy?key=$API_KEY" + ) + } + + @Test + fun `tenantId is sent as a query param when set`() = runTest { + repository().getPolicy(context, auth(tenantId = "tenant-1")) + + assertThat(http.requests.single().url).endsWith("?key=$API_KEY&tenantId=tenant-1") + } + + @Test + fun `tenantId query param is absent when tenantId is null`() = runTest { + repository().getPolicy(context, auth()) + + assertThat(http.requests.single().url).doesNotContain("tenantId") + } + + @Test + fun `package and certificate headers are sent`() = runTest { + repository().getPolicy(context, auth()) + + assertThat(http.requests.single().headers).containsExactly( + HEADER_PACKAGE, context.packageName, + HEADER_CERT, CERT, + ) + } + + @Test + fun `certificate header is omitted when the hash is null`() = runTest { + repository(certificateHash = { _, _ -> null }).getPolicy(context, auth()) + + assertThat(http.requests.single().headers) + .containsExactly(HEADER_PACKAGE, context.packageName) + } + + @Test + fun `certificate header is omitted when hashing throws`() = runTest { + val repo = repository(certificateHash = { _, _ -> throw IllegalStateException("boom") }) + + val policy = repo.getPolicy(context, auth()) + + assertThat(policy).isNotNull() + assertThat(http.requests.single().headers) + .containsExactly(HEADER_PACKAGE, context.packageName) + } + + // ============================================================================================= + // Failures resolve to no policy + // ============================================================================================= + + @Test + fun `offline IOException returns null`() = runTest { + http.respond = { url -> throw IOException("Unable to resolve host for $url") } + + assertThat(repository().getPolicy(context, auth())).isNull() + } + + @Test + fun `timeout returns null`() = runTest { + http.respond = { throw SocketTimeoutException("timeout") } + + assertThat(repository().getPolicy(context, auth())).isNull() + } + + @Test + fun `403 returns null`() = runTest { + http.respond = { HttpResponse(403, null) } + + assertThat(repository().getPolicy(context, auth())).isNull() + } + + @Test + fun `emulator 501 NOT_IMPLEMENTED returns null`() = runTest { + http.respond = { HttpResponse(501, null) } + + assertThat(repository().getPolicy(context, auth())).isNull() + } + + @Test + fun `malformed JSON returns null`() = runTest { + http.respond = { HttpResponse(200, "") } + + assertThat(repository().getPolicy(context, auth())).isNull() + } + + @Test + fun `unsupported schemaVersion returns null`() = runTest { + http.respond = { HttpResponse(200, """{"schemaVersion":2}""") } + + assertThat(repository().getPolicy(context, auth())).isNull() + } + + @Test + fun `cancellation is rethrown`() = runTest { + http.respond = { throw CancellationException("cancelled") } + + val result = runCatching { repository().getPolicy(context, auth()) } + + assertThat(result.exceptionOrNull()).isInstanceOf(CancellationException::class.java) + } + + @Test + fun `logs never contain the API key or URL`() = runTest { + val repo = repository(certificateHash = { _, _ -> throw IllegalStateException(API_KEY) }) + http.respond = { url -> throw IOException("failed to connect to $url") } + + repo.getPolicy(context, auth()) + + assertThat(logs).isNotEmpty() + logs.forEach { line -> + assertThat(line).doesNotContain("key=") + assertThat(line).doesNotContain(API_KEY) + assertThat(line).doesNotContain("googleapis") + } + assertThat(logs).contains("Password policy fetch failed: java.io.IOException") + } + + // ============================================================================================= + // Cache + // ============================================================================================= + + @Test + fun `cache hit does not send a second request`() = runTest { + val repo = repository() + + val first = repo.getPolicy(context, auth()) + val second = repo.getPolicy(context, auth()) + + assertThat(second).isEqualTo(first) + assertThat(http.requests).hasSize(1) + } + + @Test + fun `concurrent callers share one request`() = runTest { + // A separate StandardTestDispatcher makes withContext suspend, so every caller reaches + // the cache check before the first fetch completes. Only the lock serialises them. + val repo = repository(ioDispatcher = StandardTestDispatcher(testScheduler)) + + val results = List(5) { async { repo.getPolicy(context, auth()) } }.awaitAll() + + assertThat(results).doesNotContain(null) + assertThat(results.toSet()).containsExactly(PasswordPolicy.parse(SAMPLE_RESPONSE)) + assertThat(http.requests).hasSize(1) + } + + @Test + fun `fetch runs on the injected io dispatcher`() = runTest { + val executor = Executors.newSingleThreadExecutor { Thread(it, IO_THREAD) } + executor.asCoroutineDispatcher().use { dispatcher -> + repository(ioDispatcher = dispatcher).getPolicy(context, auth()) + } + + assertThat(http.threadNames).containsExactly(IO_THREAD) + } + + @Test + fun `cache is keyed by app name and tenantId`() = runTest { + val repo = repository() + + repo.getPolicy(context, auth()) + repo.getPolicy(context, auth(appName = "secondary")) + repo.getPolicy(context, auth(tenantId = "tenant-1")) + repo.getPolicy(context, auth(tenantId = "tenant-2")) + repo.getPolicy(context, auth(tenantId = "tenant-1")) + + assertThat(http.requests).hasSize(4) + } + + @Test + fun `failed fetch is retried after the failure TTL, not before`() = runTest { + val repo = repository() + http.respond = { HttpResponse(503, null) } + + assertThat(repo.getPolicy(context, auth())).isNull() + now += PasswordPolicyRepository.DEFAULT_FAILURE_TTL_MS - 1 + assertThat(repo.getPolicy(context, auth())).isNull() + assertThat(http.requests).hasSize(1) + + http.respond = { HttpResponse(200, SAMPLE_RESPONSE) } + now += 1 + assertThat(repo.getPolicy(context, auth())).isNotNull() + assertThat(http.requests).hasSize(2) + } + + @Test + fun `refetchIfCached sends no request when nothing is cached`() = runTest { + assertThat(repository().refetchIfCached(context, auth())).isNull() + assertThat(http.requests).isEmpty() + } + + @Test + fun `refetchIfCached sends no request when only a failure is cached`() = runTest { + val repo = repository() + http.respond = { HttpResponse(403, null) } + repo.getPolicy(context, auth()) + + assertThat(repo.refetchIfCached(context, auth())).isNull() + assertThat(http.requests).hasSize(1) + } + + @Test + fun `refetchIfCached replaces a cached policy`() = runTest { + val repo = repository() + repo.getPolicy(context, auth()) + val updated = SAMPLE_RESPONSE.replace("\"minPasswordLength\":10", "\"minPasswordLength\":12") + http.respond = { HttpResponse(200, updated) } + + assertThat(repo.refetchIfCached(context, auth())!!.minPasswordLength).isEqualTo(12) + assertThat(repo.getPolicy(context, auth())!!.minPasswordLength).isEqualTo(12) + assertThat(http.requests).hasSize(2) + } + + @Test + fun `failed refetch keeps the previous policy`() = runTest { + val repo = repository() + val original = repo.getPolicy(context, auth()) + http.respond = { throw IOException() } + + assertThat(repo.refetchIfCached(context, auth())).isEqualTo(original) + assertThat(repo.getPolicy(context, auth())).isEqualTo(original) + assertThat(http.requests).hasSize(2) + } + + @Test + fun `refetchIfCached only touches its own key`() = runTest { + val repo = repository() + repo.getPolicy(context, auth(tenantId = "tenant-1")) + + assertThat(repo.refetchIfCached(context, auth(tenantId = "tenant-2"))).isNull() + assertThat(http.requests).hasSize(1) + } + + private companion object { + const val API_KEY = "AIzaFakeKeyForTests123" + const val CERT = "0123456789ABCDEF0123456789ABCDEF01234567" + const val IO_THREAD = "password-policy-test-io" + } +} diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyTest.kt new file mode 100644 index 000000000..5f26252e8 --- /dev/null +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PasswordPolicyTest.kt @@ -0,0 +1,267 @@ +/* + * Copyright 2025 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.firebase.ui.auth.configuration.password_policy + +import com.firebase.ui.auth.configuration.password_policy.PasswordPolicy.EnforcementState +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Unit tests for [PasswordPolicy] parsing and evaluation. + * + * @suppress Internal test class + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE) +class PasswordPolicyTest { + + // ============================================================================================= + // Parsing + // ============================================================================================= + + @Test + fun `parse reads the sample response`() { + val policy = PasswordPolicy.parse(SAMPLE_RESPONSE)!! + + assertThat(policy.minPasswordLength).isEqualTo(10) + assertThat(policy.maxPasswordLength).isEqualTo(4096) + assertThat(policy.containsLowercaseCharacter).isTrue() + assertThat(policy.containsUppercaseCharacter).isTrue() + assertThat(policy.containsNumericCharacter).isTrue() + assertThat(policy.containsNonAlphanumericCharacter).isFalse() + assertThat(policy.allowedNonAlphanumericCharacters).hasSize(30) + assertThat(policy.allowedNonAlphanumericCharacters).containsAtLeast("^", "\"", "\\", "`") + assertThat(policy.enforcementState).isEqualTo(EnforcementState.ENFORCE) + } + + @Test + fun `parse rejects schemaVersion 2`() { + assertThat(PasswordPolicy.parse("""{"schemaVersion":2,"enforcementState":"ENFORCE"}""")) + .isNull() + } + + @Test + fun `parse rejects a string or fractional schemaVersion`() { + assertThat(PasswordPolicy.parse("""{"schemaVersion":"1"}""")).isNull() + assertThat(PasswordPolicy.parse("""{"schemaVersion":1.9}""")).isNull() + assertThat(PasswordPolicy.parse("""{"schemaVersion":true}""")).isNull() + } + + @Test + fun `parse accepts schemaVersion 1 point 0`() { + assertThat(PasswordPolicy.parse("""{"schemaVersion":1.0}""")).isNotNull() + } + + @Test + fun `explicit null minPasswordLength falls back to the default`() { + val body = """{"schemaVersion":1,"customStrengthOptions":{"minPasswordLength":null}}""" + val policy = PasswordPolicy.parse(body)!! + + assertThat(policy.minPasswordLength).isEqualTo(PasswordPolicy.DEFAULT_MIN_PASSWORD_LENGTH) + } + + @Test + fun `explicit null maxPasswordLength is treated as absent`() { + val body = """{"schemaVersion":1,"customStrengthOptions":{"maxPasswordLength":null}}""" + val policy = PasswordPolicy.parse(body)!! + + assertThat(policy.maxPasswordLength).isNull() + } + + @Test + fun `maxPasswordLength of 0 is treated as absent`() { + val body = """{"schemaVersion":1,"customStrengthOptions":{"maxPasswordLength":0}}""" + val policy = PasswordPolicy.parse(body)!! + + assertThat(policy.maxPasswordLength).isNull() + assertThat(policy.validate("abcdefg").meetsMaxPasswordLength).isNull() + } + + @Test + fun `parse rejects missing schemaVersion`() { + assertThat(PasswordPolicy.parse("""{"enforcementState":"ENFORCE"}""")).isNull() + } + + @Test + fun `parse rejects malformed JSON`() { + assertThat(PasswordPolicy.parse("{not json")).isNull() + assertThat(PasswordPolicy.parse("[]")).isNull() + assertThat(PasswordPolicy.parse("")).isNull() + } + + @Test + fun `parse rejects a non-numeric length`() { + val body = """{"schemaVersion":1,"customStrengthOptions":{"minPasswordLength":"x"}}""" + assertThat(PasswordPolicy.parse(body)).isNull() + } + + @Test + fun `enforcementState OFF, UNSPECIFIED, unknown and missing all parse as OFF`() { + listOf( + """{"schemaVersion":1,"enforcementState":"OFF"}""", + """{"schemaVersion":1,"enforcementState":"ENFORCEMENT_STATE_UNSPECIFIED"}""", + """{"schemaVersion":1,"enforcementState":"SOMETHING_NEW"}""", + """{"schemaVersion":1}""", + ).forEach { body -> + assertThat(PasswordPolicy.parse(body)!!.enforcementState).isEqualTo(EnforcementState.OFF) + } + } + + @Test + fun `missing customStrengthOptions defaults min length to 6 and configures nothing else`() { + val policy = PasswordPolicy.parse("""{"schemaVersion":1}""")!! + + assertThat(policy.minPasswordLength).isEqualTo(PasswordPolicy.DEFAULT_MIN_PASSWORD_LENGTH) + assertThat(policy.maxPasswordLength).isNull() + assertThat(policy.allowedNonAlphanumericCharacters).isEmpty() + } + + // ============================================================================================= + // Evaluation + // ============================================================================================= + + @Test + fun `min length defaults to 6 and is the only requirement when nothing is configured`() { + val policy = PasswordPolicy.parse("""{"schemaVersion":1}""")!! + + val short = policy.validate("abcde") + assertThat(short.meetsMinPasswordLength).isFalse() + assertThat(short.isValid).isFalse() + assertThat(short.meetsMaxPasswordLength).isNull() + assertThat(short.containsLowercaseLetter).isNull() + assertThat(short.containsUppercaseLetter).isNull() + assertThat(short.containsNumericCharacter).isNull() + assertThat(short.containsNonAlphanumericCharacter).isNull() + + assertThat(policy.validate("abcdef").isValid).isTrue() + } + + @Test + fun `max length is checked only when present`() { + val capped = policy(min = 1, max = 3) + assertThat(capped.validate("abcd").meetsMaxPasswordLength).isFalse() + assertThat(capped.validate("abcd").isValid).isFalse() + assertThat(capped.validate("abc").meetsMaxPasswordLength).isTrue() + + val uncapped = policy(min = 1) + assertThat(uncapped.validate("a".repeat(10_000)).meetsMaxPasswordLength).isNull() + assertThat(uncapped.validate("a".repeat(10_000)).isValid).isTrue() + } + + @Test + fun `length counts UTF-16 code units`() { + // U+1F600 is one code point and two UTF-16 code units, like JS password.length. + val status = policy(min = 2, max = 2).validate("😀") + assertThat(status.meetsMinPasswordLength).isTrue() + assertThat(status.meetsMaxPasswordLength).isTrue() + } + + @Test + fun `character classes are ASCII only`() { + val p = policy(min = 1, lower = true, upper = true, numeric = true) + + val accented = p.validate("Éé٣") + assertThat(accented.containsUppercaseLetter).isFalse() + assertThat(accented.containsLowercaseLetter).isFalse() + assertThat(accented.containsNumericCharacter).isFalse() + + val ascii = p.validate("aZ9") + assertThat(ascii.containsLowercaseLetter).isTrue() + assertThat(ascii.containsUppercaseLetter).isTrue() + assertThat(ascii.containsNumericCharacter).isTrue() + assertThat(ascii.isValid).isTrue() + } + + @Test + fun `symbol counts only when allowed and a disallowed symbol is not rejected`() { + val p = policy(min = 1, symbol = true, allowed = listOf("!", "#")) + + assertThat(p.validate("a!").containsNonAlphanumericCharacter).isTrue() + + val disallowed = p.validate("a+") + assertThat(disallowed.containsNonAlphanumericCharacter).isFalse() + assertThat(disallowed.meetsMinPasswordLength).isTrue() + + // A disallowed character never invalidates an otherwise valid password. + assertThat(p.validate("a+#é").isValid).isTrue() + } + + @Test + fun `character classes are independent, so an allowed alphanumeric also counts as a symbol`() { + val p = policy(min = 1, lower = true, symbol = true, allowed = listOf("a")) + + val status = p.validate("a") + assertThat(status.containsLowercaseLetter).isTrue() + assertThat(status.containsNonAlphanumericCharacter).isTrue() + } + + @Test + fun `unconfigured requirements are absent even when the password would fail them`() { + val p = policy(min = 1, lower = true) + val status = p.validate("a") + + assertThat(status.containsUppercaseLetter).isNull() + assertThat(status.containsNumericCharacter).isNull() + assertThat(status.containsNonAlphanumericCharacter).isNull() + assertThat(status.isValid).isTrue() + } + + @Test + fun `all unmet requirements are reported together`() { + val p = PasswordPolicy.parse( + SAMPLE_RESPONSE.replace( + "\"containsNonAlphanumericCharacter\":false", + "\"containsNonAlphanumericCharacter\":true", + ) + )!! + + val status = p.validate("é") + assertThat(status.meetsMinPasswordLength).isFalse() + assertThat(status.meetsMaxPasswordLength).isTrue() + assertThat(status.containsLowercaseLetter).isFalse() + assertThat(status.containsUppercaseLetter).isFalse() + assertThat(status.containsNumericCharacter).isFalse() + assertThat(status.containsNonAlphanumericCharacter).isFalse() + assertThat(status.isValid).isFalse() + + assertThat(p.validate("Abcdefgh1!").isValid).isTrue() + } + + private fun policy( + min: Int, + max: Int? = null, + lower: Boolean = false, + upper: Boolean = false, + numeric: Boolean = false, + symbol: Boolean = false, + allowed: List = emptyList(), + ) = PasswordPolicy( + minPasswordLength = min, + maxPasswordLength = max, + containsLowercaseCharacter = lower, + containsUppercaseCharacter = upper, + containsNumericCharacter = numeric, + containsNonAlphanumericCharacter = symbol, + allowedNonAlphanumericCharacters = allowed, + enforcementState = EnforcementState.ENFORCE, + ) + + internal companion object { + const val SAMPLE_RESPONSE = """{"customStrengthOptions":{"minPasswordLength":10,"maxPasswordLength":4096,"containsLowercaseCharacter":true,"containsUppercaseCharacter":true,"containsNumericCharacter":true,"containsNonAlphanumericCharacter":false},"schemaVersion":1,"allowedNonAlphanumericCharacters":["^","$","*",".","[","]","{","}","(",")","?","\"","!","@","#","%","&","/","\\",",",">","<","'",":",";","|","_","~","`","-"],"enforcementState":"ENFORCE","forceUpgradeOnSignin":true}""" + } +} diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PlayServicesCertificateHashProviderTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PlayServicesCertificateHashProviderTest.kt new file mode 100644 index 000000000..33624e0bd --- /dev/null +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/PlayServicesCertificateHashProviderTest.kt @@ -0,0 +1,65 @@ +/* + * Copyright 2025 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.firebase.ui.auth.configuration.password_policy + +import android.content.Context +import android.content.pm.PackageInfo +import android.content.pm.Signature +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import java.security.MessageDigest +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +/** + * Tests that [PlayServicesCertificateHashProvider] returns uppercase SHA-1 hex or `null`, never throws. + * + * @suppress Internal test class + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE) +class PlayServicesCertificateHashProviderTest { + + private val context: Context = ApplicationProvider.getApplicationContext() + + @Test + fun `package with one signature returns its uppercase SHA-1 hex`() { + val signatureBytes = byteArrayOf(0x30, 0x0A, 0x1B, 0x7F, 0x00, 0xFF.toByte(), 0x42) + shadowOf(context.packageManager).installPackage( + PackageInfo().apply { + packageName = SIGNED_PACKAGE + signatures = arrayOf(Signature(signatureBytes)) + } + ) + val expected = MessageDigest.getInstance("SHA-1").digest(signatureBytes) + .joinToString("") { "%02X".format(it) } + + assertThat(PlayServicesCertificateHashProvider.sha1Hex(context, SIGNED_PACKAGE)) + .isEqualTo(expected) + } + + @Test + fun `unknown package returns null`() { + assertThat(PlayServicesCertificateHashProvider.sha1Hex(context, "com.example.missing")) + .isNull() + } + + private companion object { + const val SIGNED_PACKAGE = "com.example.signed" + } +} diff --git a/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/UrlConnectionPasswordPolicyHttpClientTest.kt b/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/UrlConnectionPasswordPolicyHttpClientTest.kt new file mode 100644 index 000000000..34c5ed59b --- /dev/null +++ b/auth/src/test/java/com/firebase/ui/auth/configuration/password_policy/UrlConnectionPasswordPolicyHttpClientTest.kt @@ -0,0 +1,141 @@ +/* + * Copyright 2025 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.firebase.ui.auth.configuration.password_policy + +import com.google.common.truth.Truth.assertThat +import org.junit.After +import org.junit.Assert.assertThrows +import org.junit.Test +import java.io.IOException +import java.io.OutputStream +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketTimeoutException +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread + +/** + * Tests [UrlConnectionPasswordPolicyHttpClient] against a loopback socket server. + * + * @suppress Internal test class + */ +class UrlConnectionPasswordPolicyHttpClientTest { + + private val server = ServerSocket(0, 1, InetAddress.getLoopbackAddress()) + private val receivedHeaders = ConcurrentHashMap() + private val released = CountDownLatch(1) + private val url = "http://127.0.0.1:${server.localPort}/v2/passwordPolicy?key=k" + + @After + fun tearDown() { + released.countDown() + server.close() + } + + /** Serves one request, recording its headers, then lets [respond] write the response. */ + private fun serve(respond: (OutputStream) -> Unit) { + thread(isDaemon = true) { + runCatching { + server.accept().use { socket: Socket -> + val reader = socket.getInputStream().bufferedReader() + reader.readLine() + while (true) { + val line = reader.readLine() + if (line.isNullOrEmpty()) break + val (name, value) = line.split(":", limit = 2) + receivedHeaders[name.trim().lowercase()] = value.trim() + } + respond(socket.getOutputStream()) + socket.getOutputStream().flush() + } + } + } + } + + private fun respondWith(code: Int, body: String) = serve { out -> + val bytes = body.toByteArray() + out.write( + "HTTP/1.1 $code X\r\nContent-Length: ${bytes.size}\r\nConnection: close\r\n\r\n" + .toByteArray() + ) + out.write(bytes) + } + + @Test + fun `2xx returns the body`() { + respondWith(200, """{"schemaVersion":1}""") + + val response = UrlConnectionPasswordPolicyHttpClient().get(url, emptyMap()) + + assertThat(response.code).isEqualTo(200) + assertThat(response.body).isEqualTo("""{"schemaVersion":1}""") + } + + @Test + fun `non-2xx returns the code with a null body and does not throw`() { + respondWith(403, """{"error":{"code":403}}""") + + val response = UrlConnectionPasswordPolicyHttpClient().get(url, emptyMap()) + + assertThat(response.code).isEqualTo(403) + assertThat(response.body).isNull() + } + + @Test + fun `request headers are sent`() { + respondWith(200, "{}") + + UrlConnectionPasswordPolicyHttpClient().get( + url, + mapOf("X-Android-Package" to "com.example", "X-Android-Cert" to "ABCDEF"), + ) + + assertThat(receivedHeaders).containsEntry("x-android-package", "com.example") + assertThat(receivedHeaders).containsEntry("x-android-cert", "ABCDEF") + } + + @Test + fun `read timeout fails fast when the server never responds`() { + serve { released.await(30, TimeUnit.SECONDS) } + val client = UrlConnectionPasswordPolicyHttpClient(readTimeoutMs = 200) + + val start = System.nanoTime() + assertThrows(SocketTimeoutException::class.java) { client.get(url, emptyMap()) } + val elapsedMs = (System.nanoTime() - start) / 1_000_000 + + assertThat(elapsedMs).isLessThan(5_000L) + } + + @Test + fun `body at the size cap is returned`() { + val body = "a".repeat(UrlConnectionPasswordPolicyHttpClient.DEFAULT_MAX_BODY_BYTES) + respondWith(200, body) + + assertThat(UrlConnectionPasswordPolicyHttpClient().get(url, emptyMap()).body) + .hasLength(body.length) + } + + @Test + fun `body over the size cap throws IOException`() { + respondWith(200, "a".repeat(UrlConnectionPasswordPolicyHttpClient.DEFAULT_MAX_BODY_BYTES + 1)) + + assertThrows(IOException::class.java) { + UrlConnectionPasswordPolicyHttpClient().get(url, emptyMap()) + } + } +}