Keep the sign-in through a 403 or an expired token
Any 403 counted as a rejected token: one refused track, playlist or CDN file signed the user out and deleted the stored credentials, and a 403 from /get-file-info skipped the MP3 fallback. A 403 is now its own error that only fails that request, and at start-up it shows the unreachable screen with the credentials kept. The token was also only refreshed when the app started, so one expiring while the app ran, as it can on a TV left on for weeks, signed the user out with a good refresh token in hand. Requests now renew the token on a 401 and try once more; requests rejected together share one refresh, the rotated tokens are saved, and only a refused refresh token or a second 401 signs out. The fix is in core, so the TV app gets it too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
04fb5b2b47
commit
d085c169fb
6 files changed
+303
-59
No files matched your search
@@ -0,0 +1,42 @@
|
|||||||
|
// The credentials a signed-in session sends, renewed with the refresh token when Yandex
|
||||||
|
// rejects the access token, so an expiry while the app runs doesn't sign the user out.
|
||||||
|
package it.panov.musyx.api
|
||||||
|
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
|
||||||
|
class Tokens(
|
||||||
|
initial: Credentials,
|
||||||
|
/** Swaps credentials for fresh ones; [Auth.refresh] outside tests. */
|
||||||
|
private val refresh: suspend (Credentials) -> Credentials = Auth::refresh,
|
||||||
|
/** Hears each renewal, to persist it: Yandex rotates the refresh token. */
|
||||||
|
private val renewed: (Credentials) -> Unit = {},
|
||||||
|
) {
|
||||||
|
private val lock = Mutex()
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var current: Credentials = initial
|
||||||
|
private set
|
||||||
|
|
||||||
|
val accessToken: String get() = current.accessToken
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The token to retry with after `rejected` got a 401, or null when there's nothing to
|
||||||
|
* renew with or Yandex refused the refresh token: then the user signs in again. Requests
|
||||||
|
* rejected together share one refresh. Network trouble is thrown, and the session stays.
|
||||||
|
*/
|
||||||
|
suspend fun renew(rejected: String): String? = lock.withLock {
|
||||||
|
val now = current
|
||||||
|
// Another request renewed it while this one waited.
|
||||||
|
if (now.accessToken != rejected) return now.accessToken
|
||||||
|
if (now.refreshToken == null) return null
|
||||||
|
val fresh = try {
|
||||||
|
refresh(now)
|
||||||
|
} catch (_: YmError.Unauthorized) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
current = fresh
|
||||||
|
renewed(fresh)
|
||||||
|
fresh.accessToken
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -56,16 +56,36 @@ internal object Http {
|
|||||||
internal fun isYandexHost(host: String): Boolean =
|
internal fun isYandexHost(host: String): Boolean =
|
||||||
host == "yandex.net" || host.endsWith(".yandex.net") || host == "yandex.ru" || host.endsWith(".yandex.ru")
|
host == "yandex.net" || host.endsWith(".yandex.net") || host == "yandex.ru" || host.endsWith(".yandex.ru")
|
||||||
|
|
||||||
internal class Transport(private val token: String?, val language: ContentLanguage) {
|
internal class Transport(
|
||||||
|
/** The session's credentials; null for a client that isn't signed in. */
|
||||||
|
private val tokens: Tokens?,
|
||||||
|
val language: ContentLanguage,
|
||||||
|
private val api: OkHttpClient = Http.api,
|
||||||
|
private val files: OkHttpClient = Http.client,
|
||||||
|
) {
|
||||||
|
|
||||||
private fun Request.Builder.identity(url: String): Request.Builder {
|
private fun Request.Builder.identity(url: String, token: String?): Request.Builder {
|
||||||
header("X-Yandex-Music-Client", CLIENT_HEADER)
|
header("X-Yandex-Music-Client", CLIENT_HEADER)
|
||||||
header("User-Agent", USER_AGENT)
|
header("User-Agent", USER_AGENT)
|
||||||
header("Accept-Language", language.wire)
|
header("Accept-Language", language.wire)
|
||||||
if (token != null && isYandexHost(url.toHttpUrl().host)) header("Authorization", "OAuth $token")
|
if (token != null) header("Authorization", "OAuth $token")
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs `call` with the token `url` may see. A 401 for a request that carried one renews
|
||||||
|
* it and tries once more; only a second 401, or nothing to renew with, reaches the caller.
|
||||||
|
*/
|
||||||
|
private suspend fun <T> authorized(url: String, call: suspend (token: String?) -> T): T {
|
||||||
|
val token = tokens?.accessToken?.takeIf { isYandexHost(url.toHttpUrl().host) }
|
||||||
|
return try {
|
||||||
|
call(token)
|
||||||
|
} catch (e: YmError.Unauthorized) {
|
||||||
|
val renewed = token?.let { tokens?.renew(it) } ?: throw e
|
||||||
|
call(renewed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** A JSON GET, retried twice on network trouble. Returns the unwrapped `result`. */
|
/** A JSON GET, retried twice on network trouble. Returns the unwrapped `result`. */
|
||||||
suspend fun get(path: String, params: Params = Params()): JsonElement {
|
suspend fun get(path: String, params: Params = Params()): JsonElement {
|
||||||
val url = (API_BASE + path).toHttpUrl().newBuilder().apply {
|
val url = (API_BASE + path).toHttpUrl().newBuilder().apply {
|
||||||
@@ -74,7 +94,7 @@ internal class Transport(private val token: String?, val language: ContentLangua
|
|||||||
var attempt = 0
|
var attempt = 0
|
||||||
while (true) {
|
while (true) {
|
||||||
try {
|
try {
|
||||||
return send(Request.Builder().url(url).identity(url).get().build())
|
return authorized(url) { token -> send(Request.Builder().url(url).identity(url, token).get().build()) }
|
||||||
} catch (e: YmError) {
|
} catch (e: YmError) {
|
||||||
if (!e.isRetryable || attempt >= 2) throw e
|
if (!e.isRetryable || attempt >= 2) throw e
|
||||||
delay(Random.nextLong(0, minOf(4_000L, 300L shl attempt) + 1))
|
delay(Random.nextLong(0, minOf(4_000L, 300L shl attempt) + 1))
|
||||||
@@ -86,48 +106,50 @@ internal class Transport(private val token: String?, val language: ContentLangua
|
|||||||
suspend fun postForm(path: String, params: Params = Params()): JsonElement {
|
suspend fun postForm(path: String, params: Params = Params()): JsonElement {
|
||||||
val url = API_BASE + path
|
val url = API_BASE + path
|
||||||
val body = FormBody.Builder().apply { params.pairs.forEach { (k, v) -> add(k, v) } }.build()
|
val body = FormBody.Builder().apply { params.pairs.forEach { (k, v) -> add(k, v) } }.build()
|
||||||
return send(Request.Builder().url(url).identity(url).post(body).build())
|
return authorized(url) { token -> send(Request.Builder().url(url).identity(url, token).post(body).build()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun postJson(path: String, body: JsonElement): JsonElement {
|
suspend fun postJson(path: String, body: JsonElement): JsonElement {
|
||||||
if (token == null) throw YmError.Unauthorized("not signed in")
|
if (tokens == null) throw YmError.Unauthorized("not signed in")
|
||||||
val url = API_BASE + path
|
val url = API_BASE + path
|
||||||
val request = Request.Builder().url(url).identity(url)
|
val json = body.toString().toRequestBody("application/json".toMediaType())
|
||||||
.post(body.toString().toRequestBody("application/json".toMediaType()))
|
return authorized(url) { token -> send(Request.Builder().url(url).identity(url, token).post(json).build()) }
|
||||||
.build()
|
|
||||||
return send(request)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A plain-text fetch (download-info XML, lyrics files). No retry. */
|
/** A plain-text fetch (download-info XML, lyrics files). No retry. */
|
||||||
suspend fun text(url: String): String = withContext(Dispatchers.IO) {
|
suspend fun text(url: String): String = authorized(url) { token ->
|
||||||
val request = Request.Builder().url(url).identity(url).get().build()
|
withContext(Dispatchers.IO) {
|
||||||
try {
|
val request = Request.Builder().url(url).identity(url, token).get().build()
|
||||||
Http.client.newCall(request).execute().use { response ->
|
try {
|
||||||
val text = response.body.string()
|
files.newCall(request).execute().use { response ->
|
||||||
if (!response.isSuccessful) throw statusError(response.code, parseJson(text), url)
|
val text = response.body.string()
|
||||||
text
|
if (!response.isSuccessful) throw statusError(response.code, parseJson(text), url)
|
||||||
|
text
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
throw YmError.Network(e.message ?: "io")
|
||||||
}
|
}
|
||||||
} catch (e: IOException) {
|
|
||||||
throw YmError.Network(e.message ?: "io")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A streamed fetch (audio files), handed to `read` on an IO thread. No retry. */
|
/** A streamed fetch (audio files), handed to `read` on an IO thread. No retry. */
|
||||||
suspend fun <T> file(url: String, read: (InputStream, Long) -> T): T = withContext(Dispatchers.IO) {
|
suspend fun <T> file(url: String, read: (InputStream, Long) -> T): T = authorized(url) { token ->
|
||||||
val request = Request.Builder().url(url).identity(url).get().build()
|
withContext(Dispatchers.IO) {
|
||||||
try {
|
val request = Request.Builder().url(url).identity(url, token).get().build()
|
||||||
Http.client.newCall(request).execute().use { response ->
|
try {
|
||||||
if (!response.isSuccessful) throw statusError(response.code, JsonNull, url.toHttpUrl().encodedPath)
|
files.newCall(request).execute().use { response ->
|
||||||
read(response.body.byteStream(), response.body.contentLength())
|
if (!response.isSuccessful) throw statusError(response.code, JsonNull, url.toHttpUrl().encodedPath)
|
||||||
|
read(response.body.byteStream(), response.body.contentLength())
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
throw YmError.Network(e.message ?: e.javaClass.simpleName)
|
||||||
}
|
}
|
||||||
} catch (e: IOException) {
|
|
||||||
throw YmError.Network(e.message ?: e.javaClass.simpleName)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun send(request: Request): JsonElement = withContext(Dispatchers.IO) {
|
private suspend fun send(request: Request): JsonElement = withContext(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
Http.api.newCall(request).execute().use { response ->
|
api.newCall(request).execute().use { response ->
|
||||||
val text = response.body.string()
|
val text = response.body.string()
|
||||||
val json = if (text.isBlank()) JsonNull else parseJson(text)
|
val json = if (text.isBlank()) JsonNull else parseJson(text)
|
||||||
if (!response.isSuccessful) throw statusError(response.code, json, request.url.encodedPath)
|
if (!response.isSuccessful) throw statusError(response.code, json, request.url.encodedPath)
|
||||||
@@ -161,7 +183,8 @@ internal fun errorMessage(body: JsonElement, status: Int): String {
|
|||||||
internal fun statusError(status: Int, body: JsonElement, what: String): YmError {
|
internal fun statusError(status: Int, body: JsonElement, what: String): YmError {
|
||||||
val message = "$what: ${errorMessage(body, status)}"
|
val message = "$what: ${errorMessage(body, status)}"
|
||||||
return when {
|
return when {
|
||||||
status == 401 || status == 403 -> YmError.Unauthorized(message)
|
status == 401 -> YmError.Unauthorized(message)
|
||||||
|
status == 403 -> YmError.Forbidden(message)
|
||||||
status == 404 -> YmError.NotFound(message)
|
status == 404 -> YmError.NotFound(message)
|
||||||
status == 429 || status == 502 -> YmError.Network(message)
|
status == 429 || status == 502 -> YmError.Network(message)
|
||||||
status >= 500 -> YmError.Server(message)
|
status >= 500 -> YmError.Server(message)
|
||||||
|
|||||||
@@ -19,17 +19,17 @@ const val FEATURED_PODCASTS = 48
|
|||||||
private const val BATCH = 250
|
private const val BATCH = 250
|
||||||
|
|
||||||
class YmClient private constructor(
|
class YmClient private constructor(
|
||||||
private val token: String?,
|
private val tokens: Tokens?,
|
||||||
val language: ContentLanguage,
|
val language: ContentLanguage,
|
||||||
/** The signed-in user's uid; every `/users/{uid}/…` call needs it. */
|
/** The signed-in user's uid; every `/users/{uid}/…` call needs it. */
|
||||||
val uid: Long?,
|
val uid: Long?,
|
||||||
) {
|
) {
|
||||||
private val http = Transport(token, language)
|
private val http = Transport(tokens, language)
|
||||||
|
|
||||||
private fun me(): Long = uid ?: throw YmError.Unauthorized("not signed in")
|
private fun me(): Long = uid ?: throw YmError.Unauthorized("not signed in")
|
||||||
|
|
||||||
/** The same account, with Yandex answering in `language`. */
|
/** The same account, with Yandex answering in `language`. */
|
||||||
fun inLanguage(language: ContentLanguage) = YmClient(token, language, uid)
|
fun inLanguage(language: ContentLanguage) = YmClient(tokens, language, uid)
|
||||||
|
|
||||||
/** Re-reads the account, e.g. after a subscription may have changed. */
|
/** Re-reads the account, e.g. after a subscription may have changed. */
|
||||||
suspend fun account(): Account =
|
suspend fun account(): Account =
|
||||||
@@ -488,11 +488,11 @@ class YmClient private constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
/** Builds a client for `credentials` and loads the account. */
|
/** Builds a client for `tokens` and loads the account. */
|
||||||
suspend fun connect(credentials: Credentials, language: ContentLanguage): Pair<YmClient, Account> {
|
suspend fun connect(tokens: Tokens, language: ContentLanguage): Pair<YmClient, Account> {
|
||||||
val probe = YmClient(credentials.accessToken, language, null)
|
val probe = YmClient(tokens, language, null)
|
||||||
val account = probe.account()
|
val account = probe.account()
|
||||||
return YmClient(credentials.accessToken, language, account.uid) to account
|
return YmClient(tokens, language, account.uid) to account
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A client with no token, for previews and tests. Every account call fails. */
|
/** A client with no token, for previews and tests. Every account call fails. */
|
||||||
|
|||||||
@@ -17,6 +17,12 @@ sealed class YmError(message: String) : Exception(message) {
|
|||||||
/** The server failed (5xx other than 502): worth retrying, but the connection works. */
|
/** The server failed (5xx other than 502): worth retrying, but the connection works. */
|
||||||
class Server(message: String) : YmError("server: $message")
|
class Server(message: String) : YmError("server: $message")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Yandex refused this one request (403): region, rights, someone else's playlist. The
|
||||||
|
* token is fine, so this never signs the user out.
|
||||||
|
*/
|
||||||
|
class Forbidden(message: String) : YmError("forbidden: $message")
|
||||||
|
|
||||||
/** Something isn't there (404). */
|
/** Something isn't there (404). */
|
||||||
class NotFound(message: String) : YmError("not found: $message")
|
class NotFound(message: String) : YmError("not found: $message")
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import it.panov.musyx.api.PlaylistId
|
|||||||
import it.panov.musyx.api.PlaylistPage
|
import it.panov.musyx.api.PlaylistPage
|
||||||
import it.panov.musyx.api.PlaylistSummary
|
import it.panov.musyx.api.PlaylistSummary
|
||||||
import it.panov.musyx.api.Station
|
import it.panov.musyx.api.Station
|
||||||
|
import it.panov.musyx.api.Tokens
|
||||||
import it.panov.musyx.api.Track
|
import it.panov.musyx.api.Track
|
||||||
import it.panov.musyx.api.WaveSettings
|
import it.panov.musyx.api.WaveSettings
|
||||||
import it.panov.musyx.api.YmClient
|
import it.panov.musyx.api.YmClient
|
||||||
@@ -97,7 +98,8 @@ class AppState(
|
|||||||
val nav = Navigator()
|
val nav = Navigator()
|
||||||
var settings: Settings by mutableStateOf(settingsStore.load())
|
var settings: Settings by mutableStateOf(settingsStore.load())
|
||||||
private set
|
private set
|
||||||
private var credentials: Credentials? = null
|
/** The signed-in (or unreachable) session's credentials, renewed as Yandex asks. */
|
||||||
|
private var tokens: Tokens? = null
|
||||||
|
|
||||||
// Library
|
// Library
|
||||||
var collectionTab by mutableStateOf(CollectionTab.Tracks)
|
var collectionTab by mutableStateOf(CollectionTab.Tracks)
|
||||||
@@ -159,7 +161,7 @@ class AppState(
|
|||||||
client = ::client,
|
client = ::client,
|
||||||
quality = { settings.quality },
|
quality = { settings.quality },
|
||||||
waveSettings = { waveShown },
|
waveSettings = { waveShown },
|
||||||
token = { credentials?.accessToken },
|
token = { tokens?.accessToken },
|
||||||
onSignedOut = ::signOut,
|
onSignedOut = ::signOut,
|
||||||
local = downloads::stream,
|
local = downloads::stream,
|
||||||
buffering = buffering,
|
buffering = buffering,
|
||||||
@@ -201,36 +203,40 @@ class AppState(
|
|||||||
}
|
}
|
||||||
// With no connection at all, every retry and timeout would be waited out first, a
|
// With no connection at all, every retry and timeout would be waited out first, a
|
||||||
// minute or more; the network callback restores once there's a connection.
|
// minute or more; the network callback restores once there's a connection.
|
||||||
if (!online()) return@launch unreachable(stored)
|
if (!online()) {
|
||||||
|
keep(stored)
|
||||||
|
return@launch unreachable()
|
||||||
|
}
|
||||||
var creds = stored
|
var creds = stored
|
||||||
if (creds.needsRefresh()) creds = refresh(creds) ?: creds
|
if (creds.needsRefresh()) creds = refresh(creds) ?: creds
|
||||||
|
val kept = keep(creds)
|
||||||
try {
|
try {
|
||||||
val (client, account) = YmClient.connect(creds, contentLanguage)
|
// A rejected token is renewed and tried again before this gives up on it.
|
||||||
signedIn(creds, client, account)
|
val (client, account) = YmClient.connect(kept, contentLanguage)
|
||||||
} catch (e: YmError.Unauthorized) {
|
signedIn(client, account)
|
||||||
val fresh = refresh(creds)
|
|
||||||
if (fresh == null) return@launch forget(e)
|
|
||||||
try {
|
|
||||||
val (client, account) = YmClient.connect(fresh, contentLanguage)
|
|
||||||
signedIn(fresh, client, account)
|
|
||||||
} catch (e2: Throwable) {
|
|
||||||
forget(YmError.of(e2))
|
|
||||||
}
|
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
val err = YmError.of(e)
|
val err = YmError.of(e)
|
||||||
// Credentials stay for a retry when Yandex is only unreachable.
|
// Credentials stay for a retry when Yandex is only unreachable, or refuses
|
||||||
if (err.isRetryable) unreachable(creds) else forget(err)
|
// this device (a 403, e.g. for its region) rather than the token.
|
||||||
|
if (err.isRetryable || err is YmError.Forbidden) unreachable() else forget(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun unreachable(creds: Credentials) {
|
private fun unreachable() {
|
||||||
credentials = creds
|
|
||||||
// Downloads are what's left to play; the phone shows them.
|
// Downloads are what's left to play; the phone shows them.
|
||||||
nav.reset(Route.Downloads())
|
nav.reset(Route.Downloads())
|
||||||
session = Session.Unreachable
|
session = Session.Unreachable
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Makes `creds` the session's, persisting each renewal while it still is. */
|
||||||
|
private fun keep(creds: Credentials): Tokens {
|
||||||
|
lateinit var kept: Tokens
|
||||||
|
kept = Tokens(creds, renewed = { fresh -> if (tokens === kept) credentialStore.save(fresh) })
|
||||||
|
tokens = kept
|
||||||
|
return kept
|
||||||
|
}
|
||||||
|
|
||||||
/** Refresh and persist; null when there is nothing to refresh with or Yandex said no. */
|
/** Refresh and persist; null when there is nothing to refresh with or Yandex said no. */
|
||||||
private suspend fun refresh(old: Credentials): Credentials? {
|
private suspend fun refresh(old: Credentials): Credentials? {
|
||||||
if (old.refreshToken == null) return null
|
if (old.refreshToken == null) return null
|
||||||
@@ -240,6 +246,7 @@ class AppState(
|
|||||||
private fun forget(reason: YmError) {
|
private fun forget(reason: YmError) {
|
||||||
Log.w(TAG, "stored sign-in rejected: $reason")
|
Log.w(TAG, "stored sign-in rejected: $reason")
|
||||||
credentialStore.clear()
|
credentialStore.clear()
|
||||||
|
tokens = null
|
||||||
session = signedOut()
|
session = signedOut()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,15 +257,17 @@ class AppState(
|
|||||||
val pasted = creds.refreshToken == null
|
val pasted = creds.refreshToken == null
|
||||||
session = Session.Connecting(pasted)
|
session = Session.Connecting(pasted)
|
||||||
credentialStore.save(creds)
|
credentialStore.save(creds)
|
||||||
|
val kept = keep(creds)
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
val (client, account) = YmClient.connect(creds, contentLanguage)
|
val (client, account) = YmClient.connect(kept, contentLanguage)
|
||||||
signedIn(creds, client, account)
|
signedIn(client, account)
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
val err = YmError.of(e)
|
val err = YmError.of(e)
|
||||||
Log.w(TAG, "sign-in: $err")
|
Log.w(TAG, "sign-in: $err")
|
||||||
// Don't keep credentials that just failed.
|
// Don't keep credentials that just failed.
|
||||||
credentialStore.clear()
|
credentialStore.clear()
|
||||||
|
tokens = null
|
||||||
session = Session.SignedOut(
|
session = Session.SignedOut(
|
||||||
if (err is YmError.Unauthorized && pasted) SignInState.rejectedToken(scope, ::granted)
|
if (err is YmError.Unauthorized && pasted) SignInState.rejectedToken(scope, ::granted)
|
||||||
else SignInState.withError(scope, err, ::granted),
|
else SignInState.withError(scope, err, ::granted),
|
||||||
@@ -267,8 +276,7 @@ class AppState(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun signedIn(creds: Credentials, client: YmClient, account: Account) {
|
private fun signedIn(client: YmClient, account: Account) {
|
||||||
credentials = creds
|
|
||||||
nav.reset(Route.Home)
|
nav.reset(Route.Home)
|
||||||
session = Session.SignedIn(client, account)
|
session = Session.SignedIn(client, account)
|
||||||
downloads.attach(account.uid)
|
downloads.attach(account.uid)
|
||||||
@@ -282,7 +290,7 @@ class AppState(
|
|||||||
fun signOut() {
|
fun signOut() {
|
||||||
(session as? Session.SignedOut)?.signIn?.dispose()
|
(session as? Session.SignedOut)?.signIn?.dispose()
|
||||||
credentialStore.clear()
|
credentialStore.clear()
|
||||||
credentials = null
|
tokens = null
|
||||||
playback.reset()
|
playback.reset()
|
||||||
nav.reset(Route.Home)
|
nav.reset(Route.Home)
|
||||||
liked = Liked.NotLoaded
|
liked = Liked.NotLoaded
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package it.panov.musyx.api
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Protocol
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.Response
|
||||||
|
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Assert.fail
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/** A 401 renews the token once before anything signs out; a 403 is only that request's refusal. */
|
||||||
|
class SessionTest {
|
||||||
|
/** Answers each request with the next status in line (200 once they run out), never touching the network. */
|
||||||
|
private class FakeYandex(vararg statuses: Int) {
|
||||||
|
private val queue = ArrayDeque(statuses.toList())
|
||||||
|
val seen = mutableListOf<Request>()
|
||||||
|
val client: OkHttpClient = OkHttpClient.Builder().addInterceptor { chain ->
|
||||||
|
val request = chain.request()
|
||||||
|
synchronized(seen) { seen += request }
|
||||||
|
val status = synchronized(queue) { queue.removeFirstOrNull() } ?: 200
|
||||||
|
val body = if (status == 200) """{"result":"ok"}""" else """{"error":"status $status"}"""
|
||||||
|
Response.Builder()
|
||||||
|
.request(request)
|
||||||
|
.protocol(Protocol.HTTP_1_1)
|
||||||
|
.code(status)
|
||||||
|
.message("status $status")
|
||||||
|
.body(body.toResponseBody())
|
||||||
|
.build()
|
||||||
|
}.build()
|
||||||
|
|
||||||
|
val tokensSent: List<String?> get() = seen.map { it.header("Authorization")?.removePrefix("OAuth ") }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun transport(yandex: FakeYandex, tokens: Tokens?) =
|
||||||
|
Transport(tokens, ContentLanguage.English, api = yandex.client, files = yandex.client)
|
||||||
|
|
||||||
|
private val signedIn = Credentials("old-access", "old-refresh", expiresAt = 2_000_000_000)
|
||||||
|
private val renewedCredentials = Credentials("new-access", "new-refresh", expiresAt = 2_100_000_000)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun statusErrorTellsRejectedTokensFromRefusedRequests() {
|
||||||
|
assertTrue(statusError(401, JsonPrimitive(""), "/x") is YmError.Unauthorized)
|
||||||
|
assertTrue(statusError(403, JsonPrimitive(""), "/x") is YmError.Forbidden)
|
||||||
|
assertTrue(!statusError(403, JsonPrimitive(""), "/x").isRetryable)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rejectedTokenIsRenewedOnceAndTheRequestRetried() = runTest {
|
||||||
|
val yandex = FakeYandex(401)
|
||||||
|
val saved = mutableListOf<Credentials>()
|
||||||
|
var refreshes = 0
|
||||||
|
val tokens = Tokens(signedIn, refresh = { refreshes += 1; renewedCredentials }, renewed = { saved += it })
|
||||||
|
|
||||||
|
val result = transport(yandex, tokens).get("/account/status")
|
||||||
|
|
||||||
|
assertEquals(JsonPrimitive("ok"), result)
|
||||||
|
assertEquals(listOf("old-access", "new-access"), yandex.tokensSent)
|
||||||
|
assertEquals(1, refreshes)
|
||||||
|
assertEquals(listOf(renewedCredentials), saved)
|
||||||
|
assertEquals(renewedCredentials, tokens.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun postsAndFilesAreRetriedWithTheRenewedTokenToo() = runTest {
|
||||||
|
val yandex = FakeYandex(401, 200, 401)
|
||||||
|
val issued = ArrayDeque(listOf(renewedCredentials, Credentials("newer-access", "newer-refresh")))
|
||||||
|
val tokens = Tokens(signedIn, refresh = { issued.removeFirst() })
|
||||||
|
val http = transport(yandex, tokens)
|
||||||
|
|
||||||
|
http.postForm("/users/1/likes/tracks/add-multiple", Params().add("track-ids", "1"))
|
||||||
|
val bytes = http.file("https://strm.yandex.net/a") { input, _ -> input.readBytes().size }
|
||||||
|
|
||||||
|
assertTrue(bytes > 0)
|
||||||
|
assertEquals(listOf("old-access", "new-access", "new-access", "newer-access"), yandex.tokensSent)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun secondRejectionReachesTheCaller() = runTest {
|
||||||
|
val yandex = FakeYandex(401, 401)
|
||||||
|
val tokens = Tokens(signedIn, refresh = { renewedCredentials })
|
||||||
|
try {
|
||||||
|
transport(yandex, tokens).get("/account/status")
|
||||||
|
fail("expected Unauthorized")
|
||||||
|
} catch (_: YmError.Unauthorized) {
|
||||||
|
}
|
||||||
|
assertEquals(2, yandex.seen.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun pastedTokenHasNothingToRenewWith() = runTest {
|
||||||
|
val yandex = FakeYandex(401)
|
||||||
|
val tokens = Tokens(Credentials.fromToken("pasted"), refresh = { fail("no refresh token to use"); it })
|
||||||
|
try {
|
||||||
|
transport(yandex, tokens).get("/account/status")
|
||||||
|
fail("expected Unauthorized")
|
||||||
|
} catch (_: YmError.Unauthorized) {
|
||||||
|
}
|
||||||
|
assertEquals(1, yandex.seen.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun refusedRefreshTokenEndsTheSession() = runTest {
|
||||||
|
val tokens = Tokens(signedIn, refresh = { throw YmError.fromOAuth("invalid_grant: bad refresh token") })
|
||||||
|
assertNull(tokens.renew("old-access"))
|
||||||
|
assertEquals(signedIn, tokens.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun networkTroubleDuringRefreshKeepsTheSession() = runTest {
|
||||||
|
val saved = mutableListOf<Credentials>()
|
||||||
|
val tokens = Tokens(signedIn, refresh = { throw YmError.Network("timeout") }, renewed = { saved += it })
|
||||||
|
try {
|
||||||
|
tokens.renew("old-access")
|
||||||
|
fail("expected Network")
|
||||||
|
} catch (_: YmError.Network) {
|
||||||
|
}
|
||||||
|
assertEquals(signedIn, tokens.current)
|
||||||
|
assertTrue(saved.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun requestsRejectedTogetherShareOneRefresh() = runTest {
|
||||||
|
val gate = CompletableDeferred<Unit>()
|
||||||
|
var refreshes = 0
|
||||||
|
val tokens = Tokens(signedIn, refresh = { refreshes += 1; gate.await(); renewedCredentials })
|
||||||
|
val first = async { tokens.renew("old-access") }
|
||||||
|
val second = async { tokens.renew("old-access") }
|
||||||
|
gate.complete(Unit)
|
||||||
|
assertEquals("new-access", first.await())
|
||||||
|
assertEquals("new-access", second.await())
|
||||||
|
assertEquals(1, refreshes)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun forbiddenIsNotRetriedAndLeavesTheTokenAlone() = runTest {
|
||||||
|
val yandex = FakeYandex(403)
|
||||||
|
val tokens = Tokens(signedIn, refresh = { fail("a 403 says nothing about the token"); it })
|
||||||
|
try {
|
||||||
|
transport(yandex, tokens).get("/get-file-info")
|
||||||
|
fail("expected Forbidden")
|
||||||
|
} catch (_: YmError.Forbidden) {
|
||||||
|
}
|
||||||
|
assertEquals(1, yandex.seen.size)
|
||||||
|
assertEquals(signedIn, tokens.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun otherHostsNeitherSeeTheTokenNorRenewIt() = runTest {
|
||||||
|
val yandex = FakeYandex(401)
|
||||||
|
val tokens = Tokens(signedIn, refresh = { fail("lrclib's 401 isn't Yandex's"); it })
|
||||||
|
try {
|
||||||
|
transport(yandex, tokens).text("https://lrclib.net/api/get")
|
||||||
|
fail("expected Unauthorized")
|
||||||
|
} catch (_: YmError.Unauthorized) {
|
||||||
|
}
|
||||||
|
assertEquals(listOf<String?>(null), yandex.tokensSent)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user