Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Update the limit before sending a sentry about access token errors #275

Merged
merged 13 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
* Infomaniak Core - Android
* Copyright (C) 2022-2024 Infomaniak Network SA
* Copyright (C) 2022-2025 Infomaniak Network SA
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
Expand Down Expand Up @@ -30,8 +30,9 @@ class TokenInterceptor(
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()

runBlocking(Dispatchers.IO) {
val apiToken = tokenInterceptorListener.getApiToken() ?: return@runBlocking
runBlocking(Dispatchers.Default) {
tokenInterceptorListener.getApiToken()
}?.let { apiToken ->
val authorization = request.header("Authorization")
if (apiToken.accessToken != authorization?.replaceFirst("Bearer ", "")) {
request = changeAccessToken(request, apiToken)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*
* Infomaniak Core - Android
* Copyright (C) 2024 Infomaniak Network SA
* Copyright (C) 2024-2025 Infomaniak Network SA
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
Expand All @@ -21,51 +21,75 @@ import com.infomaniak.lib.core.auth.TokenInterceptorListener
import com.infomaniak.lib.core.utils.ApiTokenExt.isInfinite
import io.sentry.Sentry
import io.sentry.SentryLevel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.Serializable
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import javax.net.ssl.HttpsURLConnection

private var lastReportEpoch: Long? = null
private val lastReportMutex = Mutex()

class AccessTokenUsageInterceptor(
private val tokenInterceptorListener: TokenInterceptorListener,
private val previousApiCall: ApiCallRecord?,
private val updateLastApiCall: (ApiCallRecord) -> Unit,
) : Interceptor {

private val coroutineScope = CoroutineScope(Dispatchers.Default)

override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val response = chain.proceed(request)

runBlocking(Dispatchers.IO) {
processAccessTokenUsageAsync(request, response.code)

return response
}

private fun processAccessTokenUsageAsync(request: Request, responseCode: Int) {
coroutineScope.launch {
// Only log api calls if we have an ApiToken
val apiToken = tokenInterceptorListener.getApiToken() ?: return@runBlocking
val apiToken = tokenInterceptorListener.getApiToken() ?: return@launch

// Only log api calls if we're not using refresh tokens
if (!apiToken.isInfinite) return@runBlocking
if (!apiToken.isInfinite) return@launch

val currentApiCall = ApiCallRecord(
accessToken = request.header("Authorization")?.replaceFirst("Bearer ", "") ?: return@runBlocking,
accessToken = request.header("Authorization")?.replaceFirst("Bearer ", "") ?: return@launch,
date = System.currentTimeMillis() / 1_000L,
responseCode = response.code,
responseCode = responseCode,
)

if (currentApiCall.responseCode != HttpsURLConnection.HTTP_UNAUTHORIZED) {
// Only report api calls that triggered an unauthorized response else record the call for future checks
if (responseCode != HttpsURLConnection.HTTP_UNAUTHORIZED) {
updateLastApiCall(currentApiCall)
return@runBlocking
return@launch
}

// If multiple unauthorized calls are received at the same time, only send the first one to sentry
lastReportMutex.withLock {
val lastReport = lastReportEpoch
if (lastReport != null && lastReport <= currentApiCall.date && currentApiCall.date - lastReport < TEN_SECONDS) {
return@launch
}
lastReportEpoch = currentApiCall.date
}

if (previousApiCall != null &&
currentApiCall.accessToken == previousApiCall.accessToken &&
currentApiCall.date < previousApiCall.date + ONE_YEAR
currentApiCall.date < previousApiCall.date + SIX_MONTHS
) {
Sentry.captureMessage(
"Got disconnected due to non-working access token but it's not been a year yet",
"Got disconnected due to non-working access token but it's not been six months yet",
SentryLevel.FATAL,
) { scope ->
scope.setExtra("Current api call date epoch", currentApiCall.date.toString())
scope.setExtra("Current api call response code", currentApiCall.responseCode.toString())
scope.setExtra("Current api call token", formatAccessTokenForSentry(currentApiCall.accessToken))

scope.setExtra("Last known api call date epoch", previousApiCall.date.toString())
Expand All @@ -74,8 +98,6 @@ class AccessTokenUsageInterceptor(
}
}
}

return response
}

private fun formatAccessTokenForSentry(accessToken: String): String = accessToken.take(2) + "..." + accessToken.takeLast(2)
Expand All @@ -84,6 +106,7 @@ class AccessTokenUsageInterceptor(
data class ApiCallRecord(val accessToken: String, val date: Long, val responseCode: Int)

companion object {
private const val ONE_YEAR = 60 * 60 * 24 * 365L // In seconds
private const val SIX_MONTHS = 60 * 60 * 24 * 182L // In seconds
private const val TEN_SECONDS = 10 // In seconds
}
}