<NME> BdbAuthInterceptor.kt
<BEF> /**
 * BreadWallet
 *
 * Created by Drew Carlson <drew.carlson@breadwallet.com> on 1/7/20.
 * Copyright (c) 2020 breadwallet LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.breadwallet.breadbox

import android.util.Base64
import com.breadwallet.BuildConfig
import com.breadwallet.app.BreadApp
import com.breadwallet.crypto.Key
import com.breadwallet.logger.logDebug
import com.breadwallet.logger.logError
import com.breadwallet.tools.crypto.CryptoHelper
import com.breadwallet.tools.crypto.CryptoHelper.sha256
import com.breadwallet.tools.crypto.CryptoHelper.signBasicDer
import com.breadwallet.tools.crypto.CryptoHelper.signJose
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.security.BrdUserState
import com.google.android.gms.tasks.Tasks
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ktx.remoteConfig
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.util.Date
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit

private const val JWT_EXP_DAYS = 7L
private const val MAX_TOKEN_RETRIES = 3
private const val FIREBASE_MAX_RETRIES = 5
private const val FIREBASE_RETRY_DELAY = 1_000L
private const val BDB_TOKEN_KEY = "BDB_TOKEN"

class BdbAuthInterceptor(
    private val httpClient: OkHttpClient,
    private val userManager: BrdUserManager
) : Interceptor {

    private val mutex = Mutex()

    private val jwtHeader = JSONObject()
        .put("alg", "ES256")
        .put("typ", "JWT")
        .toString()
        .jwtEncode()

    private var clientToken: String

    init {
        if (BuildConfig.USE_REMOTE_CONFIG) {
            clientToken = Firebase.remoteConfig.getString(BDB_TOKEN_KEY)
            BreadApp.applicationScope.launch { fetchClientToken() }
        } else {
            clientToken = BuildConfig.BDB_CLIENT_TOKEN
        }
    }

    private val authKeyBytes by lazy {
        checkNotNull(userManager.getAuthKey()) {
            "BdbAuthInterceptor created before API Auth Key was set."
        }
    }

    private val authKey by lazy {
        checkNotNull(Key.createFromPrivateKeyString(authKeyBytes).orNull()) {
            "Failed to create Key from Auth Key Bytes"
        }
    }

    private val tokenRequestSignature by lazy {
        val signingData = checkNotNull(sha256(clientToken.toByteArray()))
        signBasicDer(signingData, authKey).base64EncodedString()
    }

    private val publicKeyString by lazy {
        val decodedKey = String(authKey.encodeAsPublic())
            .run(CryptoHelper::hexDecode)
        checkNotNull(decodedKey) {
            "Failed to decode authKey public bytes."
        }.base64EncodedString()
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        if (!chain.request().url.host.endsWith("blockset.com")) {
            return chain.proceed(chain.request())
        }

        val tokenString = runBlocking {
            if (BuildConfig.USE_REMOTE_CONFIG) {
                // Wait for initial remote-config fetch
                if (mutex.isLocked) mutex.withLock { }
            } else {
                waitForUserReady()
            }
            if (userManager.getBdbJwt() == null) {
                createAndSetJwt()
            }
            // Fallback to client token if needed, try creating a token later
            userManager.getBdbJwt() ?: clientToken
        }

        return chain.request()
            .newBuilder()
            .addHeader("Authorization", "Bearer $tokenString")
            .build()
            .run(chain::proceed)
    }

    suspend fun refreshClientToken() {
        fetchClientToken(overwrite = true)
    }

    private suspend fun createAndSetJwt() {
        val (newJwt, expiration) = try {
            createAccountJwt()
        } catch (e: IOException) {
            logError("Failed to create JWT", e)
            return
        }
        if (newJwt != null) {
            userManager.putBdbJwt(newJwt, expiration)
        }
    }

    private suspend fun createAccountJwt(): Pair<String?, Long> = mutex.withLock {
        // Lock acquired after successful jwt creation
        if (userManager.getBdbJwt() != null) return@withLock null to 0

        val (token, clientId) = requestToken() ?: return@withLock null to 0

        // The JWT deals with exp in seconds, but we will use millis everywhere else.
        // Remove 5 second from our current time to ensure the issued at time is not
        // in the future.
        val now = TimeUnit.MILLISECONDS.toSeconds(Date().time) - 5
        val expiration = now + TimeUnit.DAYS.toSeconds(JWT_EXP_DAYS)

        val jwtBody = JSONObject()
            .put("sub", token)
            .put("iat", now)
            .put("exp", expiration)
            .put("brd:ct", "usr")
            .put("brd:cli", clientId)
            .toString()
            .jwtEncode()

        val signingData = "$jwtHeader.$jwtBody".toByteArray()

        val hashedData = checkNotNull(sha256(signingData))
        val jwtSignature = signJose(hashedData, authKey).jwtEncode()
        "$jwtHeader.$jwtBody.$jwtSignature" to TimeUnit.SECONDS.toMillis(expiration)
    }

    private fun requestToken(attempt: Int = 0): Pair<String, String>? {
        val request = Request.Builder()
            .addHeader("Authorization", "Bearer $clientToken")
            .url("https://api.blockset.com/users/token")
            .method(
                "POST",
                JSONObject()
                    .put("device_id", BRSharedPrefs.getDeviceId())
                    .put("pub_key", publicKeyString)
                    .put("signature", tokenRequestSignature)
                    .toString()
                    .toRequestBody("application/json".toMediaType())
            )
            .build()

        val response = try {
            httpClient.newCall(request).execute()
        } catch (e: IOException) {
            return if (attempt == MAX_TOKEN_RETRIES) {
                logError("Failed to create account token.", e)
                throw e
            } else {
                requestToken(attempt + 1)
            }
        }

        val body = if (response.isSuccessful) {
            val bodyString = checkNotNull(response.body).string()
            try {
                JSONObject(bodyString)
        logDebug("Fetching client token from remote-config.")
        val remoteConfig = Firebase.remoteConfig
        var attempt = 1L
        while (clientToken.isBlank()) {
            val success = try {
                Tasks.await(remoteConfig.fetchAndActivate())
            } catch (e: ExecutionException) {
                logError("Failed to fetch and activate remote-config data.", e)

            }

            when {
                success -> {
                    logDebug("remote-config synced successfully.")
                    clientToken = remoteConfig.getString(BDB_TOKEN_KEY)
                }
                attempt - 1 >= FIREBASE_MAX_RETRIES -> {
                    logDebug("Max remote-config attempts exhausted.")

            when {
                overwrite || changesActivated -> {
                    logDebug("remote-config synced and activated.")
                    val newClientToken = remoteConfig.getString(BDB_TOKEN_KEY)
                    attempt++
                }
            }
        }
        logDebug("Done fetching client token")
    }

                    // No changes to remote config data and token is loaded, ignore.
                }
                attempt - 1 >= FIREBASE_MAX_RETRIES -> {
                    logDebug("Max remote-config attempts exhausted.")
                    clientToken = BuildConfig.BDB_CLIENT_TOKEN
                }
                else -> {
                    logDebug("Retrying remote-config sync.")
                    delay(attempt * FIREBASE_RETRY_DELAY)
                    attempt++
                }
            }
        } while (clientToken.isBlank())
        logDebug("Done fetching client token")
    }

    private fun String.jwtEncode() =
        base64EncodedString().base64ToBase64URL()

    private fun ByteArray.jwtEncode() =
        base64EncodedString().base64ToBase64URL()

    private fun String.base64EncodedString() =
        Base64.encodeToString(toByteArray(), Base64.NO_WRAP)

    private fun ByteArray.base64EncodedString() =
        Base64.encodeToString(this, Base64.NO_WRAP)

    private fun String.base64ToBase64URL() =
        replace("+", "-")
            .replace("/", "_")
            .replace("=", "")

    private suspend fun waitForUserReady() {
        userManager.stateChanges()
            .filter { it is BrdUserState.Enabled || it is BrdUserState.Locked }
            .first()
    }
}

<MSG> Invalidated bdb jwt when client token changes

<DFF> @@ -218,8 +218,8 @@ class BdbAuthInterceptor(
         logDebug("Fetching client token from remote-config.")
         val remoteConfig = Firebase.remoteConfig
         var attempt = 1L
-        while (clientToken.isBlank()) {
-            val success = try {
+        do {
+            val changesActivated = try {
                 Tasks.await(remoteConfig.fetchAndActivate())
             } catch (e: ExecutionException) {
                 logError("Failed to fetch and activate remote-config data.", e)
@@ -227,9 +227,16 @@ class BdbAuthInterceptor(
             }
 
             when {
-                success -> {
-                    logDebug("remote-config synced successfully.")
-                    clientToken = remoteConfig.getString(BDB_TOKEN_KEY)
+                changesActivated -> {
+                    logDebug("remote-config synced and activated.")
+                    val newClientToken = remoteConfig.getString(BDB_TOKEN_KEY)
+                    if (clientToken != newClientToken) {
+                        userManager.putBdbJwt("", 0)
+                    }
+                    clientToken = newClientToken
+                }
+                clientToken.isNotBlank() -> {
+                    // No changes to remote config data and token is loaded, ignore.
                 }
                 attempt - 1 >= FIREBASE_MAX_RETRIES -> {
                     logDebug("Max remote-config attempts exhausted.")
@@ -241,7 +248,7 @@ class BdbAuthInterceptor(
                     attempt++
                 }
             }
-        }
+        } while (clientToken.isBlank())
         logDebug("Done fetching client token")
     }
 

{'commit': 'diff --git a/app/src/main/java/com/breadwallet/breadbox/BdbAuthInterceptor.kt b/app/src/main/java/com/breadwallet/breadbox/BdbAuthInterceptor.kt\nindex e17e6ab14..136406e73 100644\n--- a/app/src/main/java/com/breadwallet/breadbox/BdbAuthInterceptor.kt\n+++ b/app/src/main/java/com/breadwallet/breadbox/BdbAuthInterceptor.kt\n@@ -218,8 +218,8 @@ class BdbAuthInterceptor(\n         logDebug("Fetching client token from remote-config.")\n         val remoteConfig = Firebase.remoteConfig\n         var attempt = 1L\n-        while (clientToken.isBlank()) {\n-            val success = try {\n+        do {\n+            val changesActivated = try {\n                 Tasks.await(remoteConfig.fetchAndActivate())\n             } catch (e: ExecutionException) {\n                 logError("Failed to fetch and activate remote-config data.", e)\n@@ -227,9 +227,16 @@ class BdbAuthInterceptor(\n             }\n \n             when {\n-                success -> {\n-                    logDebug("remote-config synced successfully.")\n-                    clientToken = remoteConfig.getString(BDB_TOKEN_KEY)\n+                changesActivated -> {\n+                    logDebug("remote-config synced and activated.")\n+                    val newClientToken = remoteConfig.getString(BDB_TOKEN_KEY)\n+                    if (clientToken != newClientToken) {\n+                        userManager.putBdbJwt("", 0)\n+                    }\n+                    clientToken = newClientToken\n+                }\n+                clientToken.isNotBlank() -> {\n+                    // No changes to remote config data and token is loaded, ignore.\n                 }\n                 attempt - 1 >= FIREBASE_MAX_RETRIES -> {\n                     logDebug("Max remote-config attempts exhausted.")\n@@ -241,7 +248,7 @@ class BdbAuthInterceptor(\n                     attempt++\n                 }\n             }\n-        }\n+        } while (clientToken.isBlank())\n         logDebug("Done fetching client token")\n     }\n \n', 'commit_subject': 'Invalidated bdb jwt when client token changes', 'repo_name': 'breadwallet/breadwallet-android', 'committer': {'name': 'Drew Carlson', 'email': '1f79e7fe2d2c1c8d3b12f32a29059cb0abe5f590@breadwallet.com', 'time_sec': '1588888428', 'tz_offset': '-420', 'date': {'seconds': '1588888428'}}, 'commit_tree': 'b0c354b92086a8f386549e7d3fdb803e253d1b16', 'commit_message': 'Invalidated bdb jwt when client token changes\n', 'language_name': 'Java', 'license': 'mit', 'hunks': '@@ -218,8 +218,8 @@ class BdbAuthInterceptor(\n         logDebug("Fetching client token from remote-config.")\n         val remoteConfig = Firebase.remoteConfig\n         var attempt = 1L\n-        while (clientToken.isBlank()) {\n-            val success = try {\n+        do {\n+            val changesActivated = try {\n                 Tasks.await(remoteConfig.fetchAndActivate())\n             } catch (e: ExecutionException) {\n                 logError("Failed to fetch and activate remote-config data.", e)\n@@ -227,9 +227,16 @@ class BdbAuthInterceptor(\n             }\n \n             when {\n-                success -> {\n-                    logDebug("remote-config synced successfully.")\n-                    clientToken = remoteConfig.getString(BDB_TOKEN_KEY)\n+                changesActivated -> {\n+                    logDebug("remote-config synced and activated.")\n+                    val newClientToken = remoteConfig.getString(BDB_TOKEN_KEY)\n+                    if (clientToken != newClientToken) {\n+                        userManager.putBdbJwt("", 0)\n+                    }\n+                    clientToken = newClientToken\n+                }\n+                clientToken.isNotBlank() -> {\n+                    // No changes to remote config data and token is loaded, ignore.\n                 }\n                 attempt - 1 >= FIREBASE_MAX_RETRIES -> {\n                     logDebug("Max remote-config attempts exhausted.")\n@@ -241,7 +248,7 @@ class BdbAuthInterceptor(\n                     attempt++\n                 }\n             }\n-        }\n+        } while (clientToken.isBlank())\n         logDebug("Done fetching client token")\n     }\n \n', 'addition_count': 13, 'deletion_count': 6, 'src_file': 'a/app/src/main/java/com/breadwallet/breadbox/BdbAuthInterceptor.kt', 'tgt_file': 'b/app/src/main/java/com/breadwallet/breadbox/BdbAuthInterceptor.kt', 'file_extension': '.kt', 'before_file': '/**\n * BreadWallet\n *\n * Created by Drew Carlson <drew.carlson@breadwallet.com> on 1/7/20.\n * Copyright (c) 2020 breadwallet LLC\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the "Software"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage com.breadwallet.breadbox\n\nimport android.util.Base64\nimport com.breadwallet.BuildConfig\nimport com.breadwallet.app.BreadApp\nimport com.breadwallet.crypto.Key\nimport com.breadwallet.logger.logDebug\nimport com.breadwallet.logger.logError\nimport com.breadwallet.tools.crypto.CryptoHelper\nimport com.breadwallet.tools.crypto.CryptoHelper.sha256\nimport com.breadwallet.tools.crypto.CryptoHelper.signBasicDer\nimport com.breadwallet.tools.crypto.CryptoHelper.signJose\nimport com.breadwallet.tools.manager.BRSharedPrefs\nimport com.breadwallet.tools.security.BrdUserManager\nimport com.breadwallet.tools.security.BrdUserState\nimport com.google.android.gms.tasks.Tasks\nimport com.google.firebase.ktx.Firebase\nimport com.google.firebase.remoteconfig.ktx.remoteConfig\nimport kotlinx.coroutines.delay\nimport kotlinx.coroutines.flow.filter\nimport kotlinx.coroutines.flow.first\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.runBlocking\nimport kotlinx.coroutines.sync.Mutex\nimport kotlinx.coroutines.sync.withLock\nimport okhttp3.Interceptor\nimport okhttp3.MediaType.Companion.toMediaType\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport okhttp3.Response\nimport org.json.JSONException\nimport org.json.JSONObject\nimport java.io.IOException\nimport java.util.Date\nimport java.util.concurrent.ExecutionException\nimport java.util.concurrent.TimeUnit\n\nprivate const val JWT_EXP_DAYS = 7L\nprivate const val MAX_TOKEN_RETRIES = 3\nprivate const val FIREBASE_MAX_RETRIES = 5\nprivate const val FIREBASE_RETRY_DELAY = 1_000L\nprivate const val BDB_TOKEN_KEY = "BDB_TOKEN"\n\nclass BdbAuthInterceptor(\n    private val httpClient: OkHttpClient,\n    private val userManager: BrdUserManager\n) : Interceptor {\n\n    private val mutex = Mutex()\n\n    private val jwtHeader = JSONObject()\n        .put("alg", "ES256")\n        .put("typ", "JWT")\n        .toString()\n        .jwtEncode()\n\n    private var clientToken: String\n\n    init {\n        if (BuildConfig.USE_REMOTE_CONFIG) {\n            clientToken = Firebase.remoteConfig.getString(BDB_TOKEN_KEY)\n            BreadApp.applicationScope.launch { fetchClientToken() }\n        } else {\n            clientToken = BuildConfig.BDB_CLIENT_TOKEN\n        }\n    }\n\n    private val authKeyBytes by lazy {\n        checkNotNull(userManager.getAuthKey()) {\n            "BdbAuthInterceptor created before API Auth Key was set."\n        }\n    }\n\n    private val authKey by lazy {\n        checkNotNull(Key.createFromPrivateKeyString(authKeyBytes).orNull()) {\n            "Failed to create Key from Auth Key Bytes"\n        }\n    }\n\n    private val tokenRequestSignature by lazy {\n        val signingData = checkNotNull(sha256(clientToken.toByteArray()))\n        signBasicDer(signingData, authKey).base64EncodedString()\n    }\n\n    private val publicKeyString by lazy {\n        val decodedKey = String(authKey.encodeAsPublic())\n            .run(CryptoHelper::hexDecode)\n        checkNotNull(decodedKey) {\n            "Failed to decode authKey public bytes."\n        }.base64EncodedString()\n    }\n\n    override fun intercept(chain: Interceptor.Chain): Response {\n        if (!chain.request().url.host.endsWith("blockset.com")) {\n            return chain.proceed(chain.request())\n        }\n\n        val tokenString = runBlocking {\n            if (BuildConfig.USE_REMOTE_CONFIG) {\n                // Wait for initial remote-config fetch\n                if (mutex.isLocked) mutex.withLock { }\n            } else {\n                waitForUserReady()\n            }\n            if (userManager.getBdbJwt() == null) {\n                createAndSetJwt()\n            }\n            // Fallback to client token if needed, try creating a token later\n            userManager.getBdbJwt() ?: clientToken\n        }\n\n        return chain.request()\n            .newBuilder()\n            .addHeader("Authorization", "Bearer $tokenString")\n            .build()\n            .run(chain::proceed)\n    }\n\n    suspend fun refreshClientToken() {\n        fetchClientToken(overwrite = true)\n    }\n\n    private suspend fun createAndSetJwt() {\n        val (newJwt, expiration) = try {\n            createAccountJwt()\n        } catch (e: IOException) {\n            logError("Failed to create JWT", e)\n            return\n        }\n        if (newJwt != null) {\n            userManager.putBdbJwt(newJwt, expiration)\n        }\n    }\n\n    private suspend fun createAccountJwt(): Pair<String?, Long> = mutex.withLock {\n        // Lock acquired after successful jwt creation\n        if (userManager.getBdbJwt() != null) return@withLock null to 0\n\n        val (token, clientId) = requestToken() ?: return@withLock null to 0\n\n        // The JWT deals with exp in seconds, but we will use millis everywhere else.\n        // Remove 5 second from our current time to ensure the issued at time is not\n        // in the future.\n        val now = TimeUnit.MILLISECONDS.toSeconds(Date().time) - 5\n        val expiration = now + TimeUnit.DAYS.toSeconds(JWT_EXP_DAYS)\n\n        val jwtBody = JSONObject()\n            .put("sub", token)\n            .put("iat", now)\n            .put("exp", expiration)\n            .put("brd:ct", "usr")\n            .put("brd:cli", clientId)\n            .toString()\n            .jwtEncode()\n\n        val signingData = "$jwtHeader.$jwtBody".toByteArray()\n\n        val hashedData = checkNotNull(sha256(signingData))\n        val jwtSignature = signJose(hashedData, authKey).jwtEncode()\n        "$jwtHeader.$jwtBody.$jwtSignature" to TimeUnit.SECONDS.toMillis(expiration)\n    }\n\n    private fun requestToken(attempt: Int = 0): Pair<String, String>? {\n        val request = Request.Builder()\n            .addHeader("Authorization", "Bearer $clientToken")\n            .url("https://api.blockset.com/users/token")\n            .method(\n                "POST",\n                JSONObject()\n                    .put("device_id", BRSharedPrefs.getDeviceId())\n                    .put("pub_key", publicKeyString)\n                    .put("signature", tokenRequestSignature)\n                    .toString()\n                    .toRequestBody("application/json".toMediaType())\n            )\n            .build()\n\n        val response = try {\n            httpClient.newCall(request).execute()\n        } catch (e: IOException) {\n            return if (attempt == MAX_TOKEN_RETRIES) {\n                logError("Failed to create account token.", e)\n                throw e\n            } else {\n                requestToken(attempt + 1)\n            }\n        }\n\n        val body = if (response.isSuccessful) {\n            val bodyString = checkNotNull(response.body).string()\n            try {\n                JSONObject(bodyString)\n        logDebug("Fetching client token from remote-config.")\n        val remoteConfig = Firebase.remoteConfig\n        var attempt = 1L\n        while (clientToken.isBlank()) {\n            val success = try {\n                Tasks.await(remoteConfig.fetchAndActivate())\n            } catch (e: ExecutionException) {\n                logError("Failed to fetch and activate remote-config data.", e)\n\n            }\n\n            when {\n                success -> {\n                    logDebug("remote-config synced successfully.")\n                    clientToken = remoteConfig.getString(BDB_TOKEN_KEY)\n                }\n                attempt - 1 >= FIREBASE_MAX_RETRIES -> {\n                    logDebug("Max remote-config attempts exhausted.")\n\n            when {\n                overwrite || changesActivated -> {\n                    logDebug("remote-config synced and activated.")\n                    val newClientToken = remoteConfig.getString(BDB_TOKEN_KEY)\n                    attempt++\n                }\n            }\n        }\n        logDebug("Done fetching client token")\n    }\n\n                    // No changes to remote config data and token is loaded, ignore.\n                }\n                attempt - 1 >= FIREBASE_MAX_RETRIES -> {\n                    logDebug("Max remote-config attempts exhausted.")\n                    clientToken = BuildConfig.BDB_CLIENT_TOKEN\n                }\n                else -> {\n                    logDebug("Retrying remote-config sync.")\n                    delay(attempt * FIREBASE_RETRY_DELAY)\n                    attempt++\n                }\n            }\n        } while (clientToken.isBlank())\n        logDebug("Done fetching client token")\n    }\n\n    private fun String.jwtEncode() =\n        base64EncodedString().base64ToBase64URL()\n\n    private fun ByteArray.jwtEncode() =\n        base64EncodedString().base64ToBase64URL()\n\n    private fun String.base64EncodedString() =\n        Base64.encodeToString(toByteArray(), Base64.NO_WRAP)\n\n    private fun ByteArray.base64EncodedString() =\n        Base64.encodeToString(this, Base64.NO_WRAP)\n\n    private fun String.base64ToBase64URL() =\n        replace("+", "-")\n            .replace("/", "_")\n            .replace("=", "")\n\n    private suspend fun waitForUserReady() {\n        userManager.stateChanges()\n            .filter { it is BrdUserState.Enabled || it is BrdUserState.Locked }\n            .first()\n    }\n}\n', 'message': 'Invalidated bdb jwt when client token changes\n', 'author_name': 'Drew Carlson', 'lang': 'kt'}