-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
KTOR-7194 Deferred session fetching for public endpoints #4609
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
/* | ||
* Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package io.ktor.tests.auth | ||
|
||
import io.ktor.client.request.HttpRequestBuilder | ||
import io.ktor.client.request.get | ||
import io.ktor.client.request.header | ||
import io.ktor.client.request.post | ||
import io.ktor.http.HttpStatusCode | ||
import io.ktor.server.application.install | ||
import io.ktor.server.auth.Authentication | ||
import io.ktor.server.auth.authenticate | ||
import io.ktor.server.auth.session | ||
import io.ktor.server.response.respondText | ||
import io.ktor.server.routing.get | ||
import io.ktor.server.routing.post | ||
import io.ktor.server.routing.routing | ||
import io.ktor.server.sessions.SessionStorage | ||
import io.ktor.server.sessions.Sessions | ||
import io.ktor.server.sessions.cookie | ||
import io.ktor.server.sessions.defaultSessionSerializer | ||
import io.ktor.server.sessions.serialization.KotlinxSessionSerializer | ||
import io.ktor.server.sessions.sessions | ||
import io.ktor.server.sessions.set | ||
import io.ktor.server.testing.testApplication | ||
import kotlinx.serialization.Serializable | ||
import kotlinx.serialization.json.Json | ||
import kotlin.test.Test | ||
import kotlin.test.assertEquals | ||
import kotlin.test.assertFailsWith | ||
|
||
class SessionAuthJvmTest { | ||
|
||
@Test | ||
fun sessionIgnoredForNonPublicEndpoints() = testApplication { | ||
val brokenStorage = object : SessionStorage { | ||
override suspend fun write(id: String, value: String) = Unit | ||
override suspend fun invalidate(id: String) = error("invalidate called") | ||
override suspend fun read(id: String): String = error("read called") | ||
} | ||
application { | ||
install(Sessions) { | ||
cookie<MySession>("S", storage = brokenStorage) { | ||
serializer = KotlinxSessionSerializer(Json.Default) | ||
} | ||
deferred = true | ||
} | ||
install(Authentication.Companion) { | ||
session<MySession> { | ||
validate { it } | ||
} | ||
} | ||
routing { | ||
authenticate { | ||
get("/authenticated") { | ||
call.respondText("Secret info") | ||
} | ||
} | ||
post("/session") { | ||
call.sessions.set(MySession(1)) | ||
call.respondText("OK") | ||
} | ||
get("/public") { | ||
call.respondText("Public info") | ||
} | ||
} | ||
} | ||
val withCookie: HttpRequestBuilder.() -> Unit = { | ||
header("Cookie", "S=${defaultSessionSerializer<MySession>().serialize(MySession(1))}") | ||
} | ||
|
||
assertEquals(HttpStatusCode.Companion.OK, client.post("/session").status) | ||
assertEquals(HttpStatusCode.Companion.OK, client.get("/public", withCookie).status) | ||
assertFailsWith<IllegalStateException> { | ||
client.get("/authenticated", withCookie).status | ||
} | ||
Comment on lines
+76
to
+78
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you also add a successful call after the failed one? Maybe move one of the calls made above |
||
} | ||
|
||
@Serializable | ||
data class MySession(val id: Int) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
/* | ||
* Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package io.ktor.server.sessions | ||
|
||
import io.ktor.server.application.ApplicationCall | ||
|
||
/** | ||
* Creates a lazy loading session from the given providers. | ||
*/ | ||
internal expect fun createDeferredSession(call: ApplicationCall, providers: List<SessionProvider<*>>): StatefulSession |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,6 +18,13 @@ public class SessionsConfig { | |
*/ | ||
public val providers: List<SessionProvider<*>> get() = registered.toList() | ||
|
||
/** | ||
* When set to true, sessions will be lazily retrieved from storage. | ||
* | ||
* Note: this is only available for JVM in Ktor 3.0 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For JVM and Native? |
||
*/ | ||
public var deferred: Boolean = false | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would mark it with OptIn and look for a better explaining name There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe we should have a system property (like There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good idea, this way we don't need to change the API 👍 |
||
|
||
/** | ||
* Registers a session [provider]. | ||
*/ | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
/* | ||
* Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package io.ktor.server.sessions | ||
|
||
import io.ktor.server.application.ApplicationCall | ||
|
||
internal actual fun createDeferredSession(call: ApplicationCall, providers: List<SessionProvider<*>>): StatefulSession = | ||
TODO("Deferred session retrieval is currently only available for JVM") |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
/* | ||
* Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package io.ktor.server.sessions | ||
|
||
import io.ktor.server.application.ApplicationCall | ||
import kotlinx.coroutines.Deferred | ||
import kotlinx.coroutines.ExperimentalCoroutinesApi | ||
import kotlinx.coroutines.runBlocking | ||
import kotlin.coroutines.CoroutineContext | ||
import kotlin.reflect.KClass | ||
|
||
/** | ||
* An implementation of [StatefulSession] that lazily references session providers to | ||
* avoid unnecessary calls to session storage. | ||
* All access to the deferred providers is done through blocking calls. | ||
*/ | ||
internal class BlockingDeferredSessionData( | ||
val callContext: CoroutineContext, | ||
val providerData: Map<String, Deferred<SessionProviderData<*>>>, | ||
) : StatefulSession { | ||
|
||
private var committed = false | ||
|
||
@OptIn(ExperimentalCoroutinesApi::class) | ||
override suspend fun sendSessionData(call: ApplicationCall, onEach: (String) -> Unit) { | ||
for (deferredProvider in providerData.values) { | ||
// skip non-completed providers because they were not modified | ||
if (!deferredProvider.isCompleted) continue | ||
val data = deferredProvider.getCompleted() | ||
onEach(data.provider.name) | ||
data.sendSessionData(call) | ||
} | ||
committed = true | ||
} | ||
|
||
override fun findName(type: KClass<*>): String { | ||
val entry = providerData.values.map { | ||
it.awaitBlocking() | ||
}.firstOrNull { | ||
it.provider.type == type | ||
} ?: throw IllegalArgumentException("Session data for type `$type` was not registered") | ||
|
||
return entry.provider.name | ||
} | ||
|
||
override fun set(name: String, value: Any?) { | ||
if (committed) { | ||
throw TooLateSessionSetException() | ||
} | ||
val providerData = checkNotNull(providerData[name]) { "Session data for `$name` was not registered" } | ||
setTyped(providerData.awaitBlocking(), value) | ||
} | ||
|
||
@Suppress("UNCHECKED_CAST") | ||
private fun <S : Any> setTyped(data: SessionProviderData<S>, value: Any?) { | ||
if (value != null) { | ||
data.provider.tracker.validate(value as S) | ||
} | ||
data.newValue = value as S | ||
} | ||
|
||
override fun get(name: String): Any? { | ||
val providerDataDeferred = | ||
providerData[name] ?: throw IllegalStateException("Session data for `$name` was not registered") | ||
val providerData = providerDataDeferred.awaitBlocking() | ||
return providerData.newValue ?: providerData.oldValue | ||
} | ||
|
||
override fun clear(name: String) { | ||
val providerDataDeferred = | ||
providerData[name] ?: throw IllegalStateException("Session data for `$name` was not registered") | ||
val providerData = providerDataDeferred.awaitBlocking() | ||
providerData.oldValue = null | ||
providerData.newValue = null | ||
} | ||
|
||
private fun Deferred<SessionProviderData<*>>.awaitBlocking() = | ||
runBlocking(callContext) { await() } | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can't this test be moved to the
jvmAndPosix
source-set?