Skip to content
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,17 @@ All notable changes to this project are documented here.
### Breaking changes

- `ListCommunities.sort` is now a `CommunitySortType` instead of the post `SortType`.
- `connect` and `connectForVersion` fail with a `LemmyConnectException` (`NodeInfoUnavailable`, `NotLemmy`, `InvalidVersion`, `UnsupportedVersion`) instead of `NotSupportedException`.
- `NodeInfoClient.getLemmyVersion` fails with `LemmyConnectException.NotLemmy` for other software.
- On Lemmy 0.18, a request failure whose message would contain the token (error statuses without a Lemmy error, timeouts) is now a `TokenRedactedException`.

### Added

- `LemmyApiOptions.onAuthRejected`: called with the token of a request the server rejected as not logged in.

### Fixed

- `connect` no longer throws when the instance reports a version that isn't a version number; it fails with `LemmyConnectException.InvalidVersion`.
- Lemmy 1.0: `Top*` sorts work; they are sent as `top` with a `time_range_seconds`.
- Lemmy 1.0: a `top` default post sort no longer makes `getSite` and `getMyUser` fail.

Expand Down
7 changes: 1 addition & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ val client = LemmyApiClient(
maxRetries = 5,
userAgent = "MyApp/1.0",
versionPolicy = VersionPolicy.LatestKnownCompatible,
onAuthRejected = { rejected -> if (rejected.token == currentToken) signOut() },
),
)
val api = client.connect(LemmyInstance("voyager.lemmy.ml")).getOrThrow()
Expand Down Expand Up @@ -105,16 +106,10 @@ It is a non-goal to provide a stable API. The API can change with every iteratio


[badge-android]: http://img.shields.io/badge/-android-6EDB8D.svg?style=flat
[badge-android-native]: http://img.shields.io/badge/support-[AndroidNative]-6EDB8D.svg?style=flat
[badge-wearos]: http://img.shields.io/badge/-wearos-8ECDA0.svg?style=flat
[badge-jvm]: http://img.shields.io/badge/-jvm-DB413D.svg?style=flat
[badge-js]: http://img.shields.io/badge/-js-F8DB5D.svg?style=flat
[badge-js-ir]: https://img.shields.io/badge/support-[IR]-AAC4E0.svg?style=flat
[badge-nodejs]: https://img.shields.io/badge/-nodejs-68a063.svg?style=flat
[badge-linux]: http://img.shields.io/badge/-linux-2D3F6C.svg?style=flat
[badge-windows]: http://img.shields.io/badge/-windows-4D76CD.svg?style=flat
[badge-wasm]: https://img.shields.io/badge/-wasm-624FE8.svg?style=flat
[badge-apple-silicon]: http://img.shields.io/badge/support-[AppleSilicon]-43BBFF.svg?style=flat
[badge-ios]: http://img.shields.io/badge/-ios-CDCDCD.svg?style=flat
[badge-mac]: http://img.shields.io/badge/-macos-111111.svg?style=flat
[badge-watchos]: http://img.shields.io/badge/-watchos-C0C0C0.svg?style=flat
31 changes: 23 additions & 8 deletions app/src/commonMain/kotlin/it/vercruysse/lemmyapi/LemmyApiClient.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package it.vercruysse.lemmyapi

import io.ktor.client.*
import it.vercruysse.lemmyapi.exception.LemmyConnectException
import it.vercruysse.lemmyapi.nodeinfo.NodeInfoClient
import it.vercruysse.lemmyapi.utils.runCatchingPreservingCancellation

Expand All @@ -22,24 +23,37 @@ class LemmyApiClient(
/**
* Connects to an instance after discovering its Lemmy version.
*
* Returns a failure if the instance isn't available, isn't a Lemmy host, or isn't supported.
* Fails with a [LemmyConnectException]:
* - [LemmyConnectException.NodeInfoUnavailable] when the NodeInfo document can't be loaded or read,
* - [LemmyConnectException.NotLemmy] when the instance runs other software,
* - [LemmyConnectException.InvalidVersion] when the reported version isn't a version number,
* - [LemmyConnectException.UnsupportedVersion] when the version isn't supported.
*
* Use the Feature Flags before using certain endpoints as they can be or not available depending
* on the version of the Lemmy Server instance.
*/
suspend fun connect(
instance: LemmyInstance,
auth: LemmyAuth = LemmyAuth.Anonymous,
): Result<LemmyApiBaseController> =
nodeInfoClient.getLemmyVersion(instance).fold(
onSuccess = { version -> connectForVersion(instance, auth, LemmyVersion(version)) },
onFailure = { Result.failure(it) },
)
): Result<LemmyApiBaseController> {
val nodeInfo = nodeInfoClient.getNodeInfo(instance)
.getOrElse { return Result.failure(LemmyConnectException.NodeInfoUnavailable(it)) }
if (!nodeInfoClient.isLemmyInstance(nodeInfo)) {
return Result.failure(LemmyConnectException.NotLemmy(nodeInfo))
}
val rawVersion = nodeInfo.software.version
val version = try {
LemmyVersion(rawVersion)
} catch (exception: IllegalArgumentException) {
return Result.failure(LemmyConnectException.InvalidVersion(rawVersion, exception))
}
return connectForVersion(instance, auth, version)
}

/**
* Connects to an instance with a known Lemmy version.
*
* Returns a failure if the version is unsupported.
* Fails with [LemmyConnectException.UnsupportedVersion] if the version is unsupported.
*
* Be warned that this function assumes that the instance and the version are correct.
*
Expand All @@ -57,13 +71,14 @@ class LemmyApiClient(
version,
auth,
options.versionPolicy,
options.onAuthRejected,
)
}

/**
* Connects to an instance with a known Lemmy version.
*
* Returns a failure if the version is unsupported.
* Fails with [LemmyConnectException.UnsupportedVersion] if the version is unsupported.
*
* Be warned that this function assumes that the instance and the version are correct.
*
Expand Down
12 changes: 12 additions & 0 deletions app/src/commonMain/kotlin/it/vercruysse/lemmyapi/LemmyApiTypes.kt
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ data class LemmyApiOptions(
val maxRetries: Int = 3,
val userAgent: String = "LemmyKotlinApi",
val versionPolicy: VersionPolicy = VersionPolicy.LatestKnownCompatible,
/**
* Called with the token of an API request the server rejected as not logged in: a 401, or the Lemmy error
* `not_logged_in` or `incorrect_login`. Password checks (login, change password, delete account) are left out,
* as there `incorrect_login` means a wrong password.
*
* It gets the token the request was sent with, so a token replaced since can be told apart. It runs on the
* requesting coroutine before the result is returned; keep it quick. Exceptions it throws are ignored.
*/
val onAuthRejected: AuthRejectedListener? = null,
) {
init {
require(requestTimeout.isPositive() && requestTimeout.isFinite()) { "Request timeout must be positive and finite" }
Expand All @@ -69,3 +78,6 @@ data class LemmyApiOptions(

internal val LemmyAuth.token: String?
get() = (this as? LemmyAuth.Bearer)?.token

/** See [LemmyApiOptions.onAuthRejected]. */
typealias AuthRejectedListener = (LemmyAuth.Bearer) -> Unit
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package it.vercruysse.lemmyapi

import io.ktor.client.HttpClient
import it.vercruysse.lemmyapi.exception.NotSupportedException
import it.vercruysse.lemmyapi.exception.LemmyConnectException

internal object LemmyApiWrapperFactory {

Expand All @@ -14,6 +14,7 @@ internal object LemmyApiWrapperFactory {
version: LemmyVersion,
auth: LemmyAuth,
versionPolicy: VersionPolicy,
onAuthRejected: AuthRejectedListener? = null,
): LemmyApiBaseController {
val baseUrlInstance = instance.baseUrl
val semanticVersion = version.semanticVersion
Expand All @@ -23,41 +24,41 @@ internal object LemmyApiWrapperFactory {
return when (semanticVersion.major) {
0 -> when (semanticVersion.minor) {
18 -> if (semanticVersion.patch <= 5 || versionPolicy == VersionPolicy.LatestKnownCompatible) {
it.vercruysse.lemmyapi.v0.x18.x5.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token)
it.vercruysse.lemmyapi.v0.x18.x5.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token, onAuthRejected)
} else {
throw NotSupportedException("Unsupported Lemmy version: $version")
throw LemmyConnectException.UnsupportedVersion(version)
}

19 -> when (semanticVersion.patch) {
0, 1 -> it.vercruysse.lemmyapi.v0.x19.x0.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token)
0, 1 -> it.vercruysse.lemmyapi.v0.x19.x0.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token, onAuthRejected)

2, 3 -> it.vercruysse.lemmyapi.v0.x19.x3.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token)
2, 3 -> it.vercruysse.lemmyapi.v0.x19.x3.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token, onAuthRejected)

4, 5 -> it.vercruysse.lemmyapi.v0.x19.x4.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token)
4, 5 -> it.vercruysse.lemmyapi.v0.x19.x4.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token, onAuthRejected)

6, 7, 8, 9, 10 -> it.vercruysse.lemmyapi.v0.x19.x6.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token)
6, 7, 8, 9, 10 -> it.vercruysse.lemmyapi.v0.x19.x6.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token, onAuthRejected)

11 -> it.vercruysse.lemmyapi.v0.x19.x11.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token)
11 -> it.vercruysse.lemmyapi.v0.x19.x11.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token, onAuthRejected)

else -> if (versionPolicy == VersionPolicy.LatestKnownCompatible) {
it.vercruysse.lemmyapi.v0.x19.x11.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token)
it.vercruysse.lemmyapi.v0.x19.x11.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, baseUrlInstance, token, onAuthRejected)
} else {
throw NotSupportedException("Unsupported Lemmy version: $version")
throw LemmyConnectException.UnsupportedVersion(version)
}
}

else -> throw NotSupportedException("Unsupported Lemmy minor version: $version")
else -> throw LemmyConnectException.UnsupportedVersion(version)
}

1 -> if (
versionPolicy == VersionPolicy.LatestKnownCompatible || semanticVersion.minor == 0
) {
it.vercruysse.lemmyapi.v1.x0.x0.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, token)
it.vercruysse.lemmyapi.v1.x0.x0.LemmyApiUniWrapper(client, apiBaseUrl, instance, version, token, onAuthRejected)
} else {
throw NotSupportedException("Unsupported Lemmy version: $version")
throw LemmyConnectException.UnsupportedVersion(version)
}

else -> throw NotSupportedException("Unsupported Lemmy major version: $version")
else -> throw LemmyConnectException.UnsupportedVersion(version)
}
}
}
142 changes: 115 additions & 27 deletions app/src/commonMain/kotlin/it/vercruysse/lemmyapi/LemmyRequestClient.kt
Original file line number Diff line number Diff line change
@@ -1,67 +1,155 @@
package it.vercruysse.lemmyapi

import io.ktor.client.HttpClient
import io.ktor.client.plugins.ResponseException
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import it.vercruysse.lemmyapi.exception.LemmyBadRequestException
import it.vercruysse.lemmyapi.exception.TokenRedactedException
import it.vercruysse.lemmyapi.utils.addQueryParams
import it.vercruysse.lemmyapi.utils.deleteResult
import it.vercruysse.lemmyapi.utils.getResult
import it.vercruysse.lemmyapi.utils.postResult
import it.vercruysse.lemmyapi.utils.postUploadResult
import it.vercruysse.lemmyapi.utils.putResult
import it.vercruysse.lemmyapi.utils.setJsonBody
import kotlinx.coroutines.CancellationException
import kotlinx.io.IOException

internal class LemmyRequestClient(
val client: HttpClient,
val apiBaseUrl: String,
val authProvider: AuthProvider?,
private val sendAuthHeader: Boolean = true,
private val onAuthRejected: AuthRejectedListener? = null,
private val redactToken: Boolean = false,
) {
suspend inline fun <reified R, reified T> deleteResult(path: String, body: T): Result<R> =
client.deleteResult(resolve(path)) {
authenticate()
suspend inline fun <reified R, reified T> deleteResult(path: String, body: T): Result<R> {
val token = currentToken()
return client.deleteResult<R>(resolve(path)) {
authenticate(token)
setJsonBody(body)
}
}.checked(HttpMethod.Delete, path, token)
}

suspend inline fun <reified R> deleteResult(path: String): Result<R> =
client.deleteResult(resolve(path)) { authenticate() }
suspend inline fun <reified R> deleteResult(path: String): Result<R> {
val token = currentToken()
return client.deleteResult<R>(resolve(path)) { authenticate(token) }.checked(HttpMethod.Delete, path, token)
}

suspend inline fun <reified R, reified T> getResult(path: String, form: T): Result<R> =
client.getResult(resolve(path)) {
authenticate()
suspend inline fun <reified R, reified T> getResult(path: String, form: T): Result<R> {
val token = currentToken()
return client.getResult<R>(resolve(path)) {
authenticate(token)
addQueryParams(form)
}
}.checked(HttpMethod.Get, path, token)
}

suspend inline fun <reified R> getResult(path: String): Result<R> =
client.getResult(resolve(path)) { authenticate() }
suspend inline fun <reified R> getResult(path: String): Result<R> {
val token = currentToken()
return client.getResult<R>(resolve(path)) { authenticate(token) }.checked(HttpMethod.Get, path, token)
}

suspend inline fun <reified R, reified T> postResult(path: String, body: T): Result<R> =
client.postResult(resolve(path)) {
authenticate()
suspend inline fun <reified R, reified T> postResult(path: String, body: T): Result<R> {
val token = currentToken()
return client.postResult<R>(resolve(path)) {
authenticate(token)
setJsonBody(body)
}
}.checked(HttpMethod.Post, path, token)
}

suspend inline fun <reified R> postResult(path: String): Result<R> =
client.postResult(resolve(path)) { authenticate() }
suspend inline fun <reified R> postResult(path: String): Result<R> {
val token = currentToken()
return client.postResult<R>(resolve(path)) { authenticate(token) }.checked(HttpMethod.Post, path, token)
}

suspend inline fun <reified R> postUploadResult(
path: String,
image: ByteArray,
noinline builder: HttpRequestBuilder.() -> Unit = {},
): Result<R> = client.postUploadResult(resolve(path), image) {
authenticate()
builder()
): Result<R> {
val token = currentToken()
return client.postUploadResult<R>(resolve(path), image) {
authenticate(token)
builder()
}.checked(HttpMethod.Post, path, token)
}

suspend inline fun <reified R, reified T> putResult(path: String, body: T): Result<R> =
client.putResult(resolve(path)) {
authenticate()
suspend inline fun <reified R, reified T> putResult(path: String, body: T): Result<R> {
val token = currentToken()
return client.putResult<R>(resolve(path)) {
authenticate(token)
setJsonBody(body)
}
}.checked(HttpMethod.Put, path, token)
}

private fun currentToken(): String? = authProvider?.invoke()

private fun resolve(path: String): String = "$apiBaseUrl/$path"

private fun HttpRequestBuilder.authenticate() {
private fun HttpRequestBuilder.authenticate(token: String?) {
headers.remove(HttpHeaders.Authorization)
authProvider?.invoke()?.let { token -> headers[HttpHeaders.Authorization] = "Bearer $token" }
if (sendAuthHeader && token != null) headers[HttpHeaders.Authorization] = "Bearer $token"
}

private fun <R> Result<R>.checked(method: HttpMethod, path: String, token: String?): Result<R> {
val failure = exceptionOrNull() ?: return this
if (token.isNullOrEmpty()) return this
if (failure.rejectsAuth() && !isCredentialCheck(method, path)) notifyAuthRejected(token)
return if (redactToken) Result.failure(failure.redacting(token)) else this
}

private fun notifyAuthRejected(token: String) {
val listener = onAuthRejected ?: return
try {
listener(LemmyAuth.Bearer(token))
} catch (exception: CancellationException) {
throw exception
} catch (_: Exception) {
// A failing listener must not turn the request's Result into a thrown exception
}
}

private companion object {
/** Lemmy error ids that mean the request's token is not (or no longer) valid. */
val REJECTED_AUTH_ERRORS = setOf("not_logged_in", "incorrect_login")

/** Requests that check a password, where `incorrect_login` means a wrong password rather than a bad token. */
val CREDENTIAL_CHECKS = setOf(
HttpMethod.Post to "user/login",
HttpMethod.Post to "account/auth/login",
HttpMethod.Put to "user/change_password",
HttpMethod.Put to "account/auth/change_password",
HttpMethod.Post to "user/delete_account",
HttpMethod.Delete to "account",
)

fun isCredentialCheck(method: HttpMethod, path: String): Boolean = (method to path) in CREDENTIAL_CHECKS

fun Throwable.rejectsAuth(): Boolean = when (this) {
is LemmyBadRequestException -> statusCode == 401 || id in REJECTED_AUTH_ERRORS
is ResponseException -> response.status.value == 401
else -> false
}
}
}

private const val REDACTED = "<redacted>"
private const val MAX_CAUSE_DEPTH = 16

/**
* Replaces this failure by a [TokenRedactedException] when its message, or a cause's, contains [token].
* Lemmy 0.18 sends the token in the query of GET requests, and Ktor puts the address in its exception messages.
*/
internal fun Throwable.redacting(token: String): Throwable {
// Bounded, as a cause chain can loop back on itself
val leaks = generateSequence(this) { it.cause }.take(MAX_CAUSE_DEPTH).any { it.message?.contains(token) == true }
if (!leaks) return this
val original = listOfNotNull(this::class.simpleName, message).joinToString(": ")
return TokenRedactedException(
message = original.replace(token, REDACTED),
statusCode = (this as? ResponseException)?.response?.status?.value,
isNetworkFailure = this is IOException,
)
}
Loading
Loading