Fix: reject revoked tokens on all replicas when Redis writes fail
This commit is contained in:
+152
@@ -0,0 +1,152 @@
|
||||
package com.mtusi.messenger.main.infrastructure.services.authentication
|
||||
|
||||
import com.mtusi.messenger.main.config.authentication.SerialAuthenticationConfig
|
||||
import com.mtusi.messenger.main.config.redis.SerialRedisConfig
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession
|
||||
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.ExposedSessionRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.RedisSessionCacheRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation.ExposedSessionRevocationRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.user.ExposedUserRepository
|
||||
import com.mtusi.messenger.main.infrastructure.services.hashing.DefaultHashingService
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import com.mtusi.messenger.main.plugins.applyDatabaseMigrations
|
||||
import com.mtusi.messenger.main.support.TestDatabase
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.support.uniqueUsername
|
||||
import com.mtusi.messenger.main.utils.computeSha256
|
||||
import com.zaxxer.hikari.HikariDataSource
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.jetbrains.exposed.v1.jdbc.Database
|
||||
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
|
||||
import org.testcontainers.containers.GenericContainer
|
||||
import kotlin.test.AfterTest
|
||||
import kotlin.test.BeforeTest
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
/**
|
||||
* Two services sharing PostgreSQL and Redis model two API replicas. Redis keeps serving reads while writes are
|
||||
* paused (CLIENT PAUSE ... WRITE), so the replica that did not handle the logout still finds the cached session.
|
||||
*/
|
||||
class CrossReplicaRevocationTest {
|
||||
|
||||
private lateinit var redis: GenericContainer<*>
|
||||
private val connections = mutableListOf<RedisConnection>()
|
||||
|
||||
@BeforeTest
|
||||
fun start() {
|
||||
redis = TestRedis.create().also { it.start() }
|
||||
HikariDataSource().apply {
|
||||
jdbcUrl = TestDatabase.container.jdbcUrl
|
||||
username = TestDatabase.USERNAME
|
||||
password = TestDatabase.PASSWORD
|
||||
}.use(::applyDatabaseMigrations)
|
||||
TestDatabase.container.let { Database.connect(it.jdbcUrl, user = it.username, password = it.password) }
|
||||
}
|
||||
|
||||
@AfterTest
|
||||
fun stop() {
|
||||
connections.forEach { it.close() }
|
||||
redis.stop()
|
||||
}
|
||||
|
||||
private fun replica(revokeTimeoutMs: Long): DefaultAuthenticationService {
|
||||
val endpoint = TestRedis.endpoint(redis)
|
||||
val connection = RedisConnection(
|
||||
SerialRedisConfig(
|
||||
host = endpoint.host,
|
||||
port = endpoint.port,
|
||||
password = TestRedis.PASSWORD,
|
||||
connectTimeoutMs = 500,
|
||||
commandTimeoutMs = 500
|
||||
)
|
||||
).also(connections::add)
|
||||
|
||||
return DefaultAuthenticationService(
|
||||
userRepository = ExposedUserRepository(),
|
||||
sessionRepository = ExposedSessionRepository(),
|
||||
sessionCacheRepository = RedisSessionCacheRepository(connection),
|
||||
sessionRevocationRepository = ExposedSessionRevocationRepository(),
|
||||
hashingService = DefaultHashingService(),
|
||||
config = SerialAuthenticationConfig(
|
||||
realm = "messenger",
|
||||
sessionTtlSeconds = 3600,
|
||||
sessionCacheTtlSeconds = 60,
|
||||
sessionRevokeTimeoutMs = revokeTimeoutMs
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun login(service: DefaultAuthenticationService): IssuedSession = transaction {
|
||||
val user = checkNotNull(ExposedUserRepository().create(uniqueUsername("replica"), "replica", "not-a-real-hash"))
|
||||
service.createSession(user.id)
|
||||
}
|
||||
|
||||
private fun cached(issued: IssuedSession): String {
|
||||
return TestRedis.cli(redis, "GET", "session:${issued.token.toByteArray().computeSha256()}")
|
||||
}
|
||||
|
||||
private fun pauseWrites(ms: Long) {
|
||||
assertEquals("OK", TestRedis.cli(redis, "CLIENT", "PAUSE", ms.toString(), "WRITE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout waits for paused Redis writes and then no replica accepts the token`() = runBlocking {
|
||||
val a = replica(revokeTimeoutMs = 8000)
|
||||
val b = replica(revokeTimeoutMs = 8000)
|
||||
val issued = login(a)
|
||||
|
||||
// Both replicas have read the session, Redis holds the active copy.
|
||||
assertNotNull(a.findSessionByToken(issued.token))
|
||||
assertNotNull(b.findSessionByToken(issued.token))
|
||||
assertTrue(cached(issued).contains(issued.session.id.toString()))
|
||||
|
||||
pauseWrites(3000)
|
||||
|
||||
val started = TimeSource.Monotonic.markNow()
|
||||
a.revokeSession(issued.session)
|
||||
assertTrue(started.elapsedNow() > 2.seconds, "the logout must wait for the tombstone, not answer early")
|
||||
|
||||
assertEquals("revoked", cached(issued))
|
||||
assertNull(b.findSessionByToken(issued.token), "the other replica must reject the token")
|
||||
assertNull(a.findSessionByToken(issued.token))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unconfirmed logout makes every replica bypass the cache`() = runBlocking {
|
||||
val a = replica(revokeTimeoutMs = 1000)
|
||||
val b = replica(revokeTimeoutMs = 1000)
|
||||
val issued = login(a)
|
||||
|
||||
assertNotNull(a.findSessionByToken(issued.token))
|
||||
assertNotNull(b.findSessionByToken(issued.token))
|
||||
|
||||
pauseWrites(6000)
|
||||
val paused = TimeSource.Monotonic.markNow()
|
||||
|
||||
val error = assertFailsWith<ApiException> { a.revokeSession(issued.session) }
|
||||
assertEquals(ErrorCode.UNAVAILABLE, error.code)
|
||||
|
||||
// The periodic check (once a second on every replica) sees the pending revocation in PostgreSQL.
|
||||
b.syncPendingRevocations()
|
||||
assertNull(b.findSessionByToken(issued.token), "a replica that saw no Redis failure must not trust the cache")
|
||||
assertNull(a.findSessionByToken(issued.token))
|
||||
|
||||
// Once Redis accepts writes again the tombstone is written and the cache is trusted again.
|
||||
while (paused.elapsedNow() < 7.seconds) {
|
||||
Thread.sleep(200)
|
||||
}
|
||||
b.syncPendingRevocations()
|
||||
assertEquals("revoked", cached(issued))
|
||||
assertNull(b.findSessionByToken(issued.token))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -31,6 +31,11 @@ import kotlin.test.assertTrue
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
/**
|
||||
* Short logout deadline: with Redis paused or down the tombstone cannot be written and the logout answers 503.
|
||||
*/
|
||||
private const val REVOKE_TIMEOUT_MS = 1000L
|
||||
|
||||
class DependencyFailureTest {
|
||||
|
||||
/**
|
||||
@@ -54,7 +59,8 @@ class DependencyFailureTest {
|
||||
|
||||
@Test
|
||||
fun `without Redis requests bypass the cache`() = runApp(
|
||||
redis = TestRedis.unreachableEndpoint()
|
||||
redis = TestRedis.unreachableEndpoint(),
|
||||
sessionRevokeTimeoutMs = REVOKE_TIMEOUT_MS
|
||||
) { client ->
|
||||
assertEquals(HttpStatusCode.OK, client.get("/health/ready").status)
|
||||
|
||||
@@ -66,8 +72,9 @@ class DependencyFailureTest {
|
||||
|
||||
client.assertAnonymousRejected()
|
||||
|
||||
// PostgreSQL is the source of truth: logout still works and is visible immediately.
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
// Without the tombstone another replica could still accept the token from the cache, so the logout is not
|
||||
// confirmed (503). The session is gone from PostgreSQL, so this replica rejects the token anyway.
|
||||
assertUnavailable(client.delete("/api/v1/auth/sessions/current") { auth(alice) })
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
}
|
||||
|
||||
@@ -77,7 +84,7 @@ class DependencyFailureTest {
|
||||
val docker = redis.dockerClient
|
||||
|
||||
try {
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
runApp(redis = TestRedis.endpoint(redis), sessionRevokeTimeoutMs = REVOKE_TIMEOUT_MS) { client ->
|
||||
val alice = client.register("alice")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
@@ -89,7 +96,7 @@ class DependencyFailureTest {
|
||||
|
||||
client.assertAnonymousRejected()
|
||||
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
assertUnavailable(client.delete("/api/v1/auth/sessions/current") { auth(alice) })
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
docker.unpauseContainerCmd(redis.containerId).exec()
|
||||
@@ -128,19 +135,25 @@ class DependencyFailureTest {
|
||||
val docker = redis.dockerClient
|
||||
|
||||
try {
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
runApp(redis = TestRedis.endpoint(redis), sessionRevokeTimeoutMs = REVOKE_TIMEOUT_MS) { client ->
|
||||
val alice = client.register("alice")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
val copy = cachedCopy(redis, alice)
|
||||
|
||||
docker.pauseContainerCmd(redis.containerId).exec()
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
assertUnavailable(client.delete("/api/v1/auth/sessions/current") { auth(alice) })
|
||||
docker.unpauseContainerCmd(redis.containerId).exec()
|
||||
|
||||
loseTombstone(redis, alice, copy)
|
||||
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertEquals("revoked", TestRedis.cli(redis, "GET", "session:${alice.token.toByteArray().computeSha256()}"))
|
||||
|
||||
// The background check writes the pending tombstone once Redis accepts writes (retry every 1 s).
|
||||
val deadline = TimeSource.Monotonic.markNow() + 3.seconds
|
||||
while (TestRedis.cli(redis, "GET", "session:${alice.token.toByteArray().computeSha256()}") != "revoked") {
|
||||
assertTrue(deadline.hasNotPassedNow(), "pending tombstone was not written after recovery")
|
||||
Thread.sleep(200)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
redis.stop()
|
||||
@@ -157,20 +170,20 @@ class DependencyFailureTest {
|
||||
lateinit var copy: String
|
||||
|
||||
try {
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
runApp(redis = TestRedis.endpoint(redis), sessionRevokeTimeoutMs = REVOKE_TIMEOUT_MS) { client ->
|
||||
alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
chat = client.createChat(alice, "restart", listOf(alice.id, bob.id))
|
||||
copy = cachedCopy(redis, alice)
|
||||
|
||||
docker.pauseContainerCmd(redis.containerId).exec()
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
assertUnavailable(client.delete("/api/v1/auth/sessions/current") { auth(alice) })
|
||||
}
|
||||
|
||||
docker.unpauseContainerCmd(redis.containerId).exec()
|
||||
loseTombstone(redis, alice, copy)
|
||||
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
runApp(redis = TestRedis.endpoint(redis), sessionRevokeTimeoutMs = REVOKE_TIMEOUT_MS) { client ->
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/chats/${chat.id}/messages") { auth(alice) }.status)
|
||||
assertEquals(
|
||||
|
||||
@@ -58,6 +58,7 @@ private fun testConfig(
|
||||
databaseConnectionTimeoutMs: Long,
|
||||
redis: RedisEndpoint,
|
||||
idempotencyTtlSeconds: Long,
|
||||
sessionRevokeTimeoutMs: Long,
|
||||
) = HoconApplicationConfig(
|
||||
ConfigFactory.parseMap(
|
||||
mapOf(
|
||||
@@ -77,6 +78,7 @@ private fun testConfig(
|
||||
"authentication.realm" to "messenger",
|
||||
"authentication.sessionTtlSeconds" to sessionTtlSeconds,
|
||||
"authentication.sessionCacheTtlSeconds" to 60,
|
||||
"authentication.sessionRevokeTimeoutMs" to sessionRevokeTimeoutMs,
|
||||
"messages.idempotencyTtlSeconds" to idempotencyTtlSeconds,
|
||||
"instance.id" to "test-instance",
|
||||
"cors.allowSameOrigin" to true,
|
||||
@@ -93,10 +95,11 @@ fun runApp(
|
||||
databaseConnectionTimeoutMs: Long = 10000,
|
||||
redis: RedisEndpoint = TestRedis.endpoint(),
|
||||
idempotencyTtlSeconds: Long = 86400,
|
||||
sessionRevokeTimeoutMs: Long = 8000,
|
||||
block: suspend ApplicationTestBuilder.(HttpClient) -> Unit
|
||||
) = testApplication {
|
||||
environment {
|
||||
config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis, idempotencyTtlSeconds)
|
||||
config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis, idempotencyTtlSeconds, sessionRevokeTimeoutMs)
|
||||
}
|
||||
application {
|
||||
module()
|
||||
|
||||
Reference in New Issue
Block a user