package com.mtusi.messenger.main.plugins import com.mtusi.messenger.main.extensions.ErrorBody import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest import com.mtusi.messenger.main.infrastructure.dto.Chat import com.mtusi.messenger.main.support.TestDatabase import com.mtusi.messenger.main.support.TestRedis import com.mtusi.messenger.main.support.TestUser import com.mtusi.messenger.main.support.auth import com.mtusi.messenger.main.support.createChat import com.mtusi.messenger.main.support.idempotencyKey import com.mtusi.messenger.main.support.register import com.mtusi.messenger.main.support.runApp import com.mtusi.messenger.main.utils.computeSha256 import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.basicAuth import io.ktor.client.request.delete import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import org.testcontainers.containers.GenericContainer import kotlin.test.Test import kotlin.test.assertEquals 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 { /** * An unknown token can only be checked against PostgreSQL, so without it the answer is 503, never a success. */ private suspend fun HttpClient.assertAnonymousRejected( unknownTokenStatus: HttpStatusCode = HttpStatusCode.Unauthorized ) { assertEquals(HttpStatusCode.Unauthorized, get("/api/v1/users/me").status) assertEquals(HttpStatusCode.Unauthorized, get("/api/v1/users/me") { header("X-User-Id", "1") }.status) assertEquals( unknownTokenStatus, get("/api/v1/users/me") { header("Authorization", "Bearer never-issued-token") }.status ) } private suspend fun assertUnavailable(response: HttpResponse) { assertEquals(HttpStatusCode.ServiceUnavailable, response.status) assertEquals("unavailable", response.body().error.code) } @Test fun `without Redis requests bypass the cache`() = runApp( redis = TestRedis.unreachableEndpoint(), sessionRevokeTimeoutMs = REVOKE_TIMEOUT_MS ) { client -> assertEquals(HttpStatusCode.OK, client.get("/health/ready").status) val alice = client.register("alice") val bob = client.register("bob") assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) client.createChat(alice, "no redis", listOf(alice.id, bob.id)) client.assertAnonymousRejected() // 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) } @Test fun `hanging Redis costs one command timeout and recovers`() { val redis = TestRedis.create().also { it.start() } val docker = redis.dockerClient try { 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) docker.pauseContainerCmd(redis.containerId).exec() val started = TimeSource.Monotonic.markNow() assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) assertTrue(started.elapsedNow() < 2.seconds, "cache lookup must be bounded by the command timeout") client.assertAnonymousRejected() 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() // The copy cached before the pause is replaced by the delayed tombstone, not resurrected. assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status) val bob = client.register("bob") assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(bob) }.status) assertTrue( TestRedis.cli(redis, "EXISTS", "session:${bob.token.toByteArray().computeSha256()}") == "1", "cache is used again after recovery" ) } } finally { redis.stop() } } /** * The tombstone written by a logout during an outage can be lost while the copy cached before it survives * (here: put back by hand). The revocation kept in PostgreSQL must still win once Redis is reachable again. */ private fun loseTombstone(redis: GenericContainer<*>, user: TestUser, cachedCopy: String) { TestRedis.cli(redis, "SET", "session:${user.token.toByteArray().computeSha256()}", cachedCopy, "PX", "60000") } private fun cachedCopy(redis: GenericContainer<*>, user: TestUser): String { return TestRedis.cli(redis, "GET", "session:${user.token.toByteArray().computeSha256()}") .also { assertTrue(it.contains(user.id.toString()), "session must be cached before the outage") } } @Test fun `logout during a Redis outage is not undone by a stale cached copy`() { val redis = TestRedis.create().also { it.start() } val docker = redis.dockerClient try { 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() 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) // 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() } } @Test fun `logout during a Redis outage survives an API restart`() { val redis = TestRedis.create().also { it.start() } val docker = redis.dockerClient lateinit var alice: TestUser lateinit var chat: Chat lateinit var copy: String try { 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() assertUnavailable(client.delete("/api/v1/auth/sessions/current") { auth(alice) }) } docker.unpauseContainerCmd(redis.containerId).exec() loseTombstone(redis, alice, copy) 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( HttpStatusCode.Unauthorized, client.post("/api/v1/chats/${chat.id}/messages") { auth(alice) idempotencyKey() contentType(ContentType.Application.Json) setBody(CreateMessageRequest(text = "after logout")) }.status ) } } finally { redis.stop() } } @Test fun `without PostgreSQL requests fail with a bounded 503`() { val database = TestDatabase.create().also { it.start() } TestDatabase.awaitConnectable(database) try { runApp(database = database, databaseConnectionTimeoutMs = 2000) { client -> val alice = client.register("alice") assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status) database.dockerClient.stopContainerCmd(database.containerId).exec() val started = TimeSource.Monotonic.markNow() // The session itself is still served from Redis, the user lookup needs PostgreSQL. assertUnavailable(client.get("/api/v1/users/me") { auth(alice) }) assertUnavailable(client.post("/api/v1/auth/sessions") { basicAuth(alice.user.username, alice.password) }) assertEquals(HttpStatusCode.ServiceUnavailable, client.get("/health/ready").status) assertEquals(HttpStatusCode.OK, client.get("/health/live").status) assertTrue(started.elapsedNow() < 15.seconds, "every request must fail within the pool timeout") client.assertAnonymousRejected(unknownTokenStatus = HttpStatusCode.ServiceUnavailable) } } finally { database.stop() } } }