forked from mtusi2026/mtusi2026lab2
Completed for a grade of four
This commit is contained in:
+83
@@ -0,0 +1,83 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
|
||||
|
||||
import com.mtusi.messenger.main.config.redis.SerialRedisConfig
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.utils.nowMicros
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import java.util.UUID
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
|
||||
class RedisSessionCacheRepositoryTest {
|
||||
|
||||
private fun withRepository(block: suspend (RedisSessionCacheRepository) -> Unit) = runTest {
|
||||
val endpoint = TestRedis.endpoint()
|
||||
val connection = RedisConnection(
|
||||
SerialRedisConfig(
|
||||
host = endpoint.host,
|
||||
port = endpoint.port,
|
||||
password = TestRedis.PASSWORD,
|
||||
connectTimeoutMs = 2000,
|
||||
commandTimeoutMs = 2000
|
||||
)
|
||||
)
|
||||
connection.use { block(RedisSessionCacheRepository(it)) }
|
||||
}
|
||||
|
||||
private fun session(ttl: Duration = 10.minutes): Session {
|
||||
val now = Clock.System.nowMicros()
|
||||
return Session(
|
||||
id = UUID.randomUUID(),
|
||||
userId = UUID.randomUUID(),
|
||||
tokenHash = UUID.randomUUID().toString().replace("-", ""),
|
||||
createdAt = now,
|
||||
expiresAt = now + ttl
|
||||
)
|
||||
}
|
||||
|
||||
private fun ttlSeconds(session: Session): Long {
|
||||
return TestRedis.cli(TestRedis.container, "TTL", "session:${session.tokenHash}").toLong()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cached session round-trips and expires together with the session`() = withRepository { repository ->
|
||||
val session = session()
|
||||
|
||||
assertNull(repository.find(session.tokenHash))
|
||||
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
assertEquals(CachedSession.Active(session), repository.find(session.tokenHash))
|
||||
assertTrue(ttlSeconds(session) in 590..600, "key must expire at cachedUntil")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `revoke replaces a cached session with a tombstone`() = withRepository { repository ->
|
||||
val session = session()
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
repository.revoke(session)
|
||||
|
||||
assertEquals(CachedSession.Revoked, repository.find(session.tokenHash))
|
||||
assertTrue(ttlSeconds(session) in 590..600, "tombstone must live until the session would expire")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `late cache fill cannot overwrite a tombstone`() = withRepository { repository ->
|
||||
val session = session()
|
||||
|
||||
// A lookup read the session from PostgreSQL before logout and stores it after the logout finished.
|
||||
repository.revoke(session)
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
assertEquals(CachedSession.Revoked, repository.find(session.tokenHash))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.extensions.ErrorBody
|
||||
import com.mtusi.messenger.main.support.TestDatabase
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.support.auth
|
||||
import com.mtusi.messenger.main.support.createChat
|
||||
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.statement.HttpResponse
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
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<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without Redis requests bypass the cache`() = runApp(
|
||||
redis = TestRedis.unreachableEndpoint()
|
||||
) { 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()
|
||||
|
||||
// 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)
|
||||
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)) { 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()
|
||||
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without PostgreSQL requests fail with a bounded 503`() {
|
||||
val database = TestDatabase.create().also { it.start() }
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
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.register
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import com.mtusi.messenger.main.utils.computeSha256
|
||||
import io.ktor.client.request.delete
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class SessionCacheTest {
|
||||
|
||||
private val redis = TestRedis.container
|
||||
|
||||
private fun cached(user: TestUser): String {
|
||||
return TestRedis.cli(redis, "GET", "session:${user.token.toByteArray().computeSha256()}")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `first authenticated request fills the cache`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
|
||||
assertEquals("", cached(alice), "login does not write to the cache")
|
||||
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
assertTrue(cached(alice).contains(alice.id.toString()))
|
||||
|
||||
// The session lives for an hour, its cached copy at most sessionCacheTtlSeconds.
|
||||
val ttl = TestRedis.cli(redis, "TTL", "session:${alice.token.toByteArray().computeSha256()}").toLong()
|
||||
assertTrue(ttl in 1..60, "cached copy TTL was $ttl")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout leaves a tombstone and the token is rejected`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
client.get("/api/v1/users/me") { auth(alice) }
|
||||
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
|
||||
assertEquals("revoked", cached(alice))
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `emptied cache falls back to PostgreSQL`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
client.get("/api/v1/users/me") { auth(alice) }
|
||||
client.delete("/api/v1/auth/sessions/current") { auth(bob) }
|
||||
|
||||
TestRedis.cli(redis, "FLUSHALL")
|
||||
|
||||
// PostgreSQL is the source of truth: the live session survives, the revoked one stays revoked.
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(bob) }.status)
|
||||
assertTrue(cached(alice).contains(alice.id.toString()), "cache is filled again")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import io.ktor.server.testing.testApplication
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonNamingStrategy
|
||||
import org.testcontainers.containers.PostgreSQLContainer
|
||||
import java.util.UUID
|
||||
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
@@ -45,28 +46,51 @@ data class TestUser(
|
||||
get() = user.id
|
||||
}
|
||||
|
||||
private fun testConfig(sessionTtlSeconds: Long) = HoconApplicationConfig(
|
||||
data class RedisEndpoint(
|
||||
val host: String,
|
||||
val port: Int,
|
||||
)
|
||||
|
||||
private fun testConfig(
|
||||
sessionTtlSeconds: Long,
|
||||
database: PostgreSQLContainer<*>,
|
||||
databaseConnectionTimeoutMs: Long,
|
||||
redis: RedisEndpoint,
|
||||
) = HoconApplicationConfig(
|
||||
ConfigFactory.parseMap(
|
||||
mapOf(
|
||||
"database.host" to TestDatabase.container.host,
|
||||
"database.port" to TestDatabase.container.firstMappedPort,
|
||||
"database.name" to TestDatabase.NAME,
|
||||
"database.username" to TestDatabase.USERNAME,
|
||||
"database.password" to TestDatabase.PASSWORD,
|
||||
"database.host" to database.host,
|
||||
"database.port" to database.firstMappedPort,
|
||||
"database.name" to database.databaseName,
|
||||
"database.username" to database.username,
|
||||
"database.password" to database.password,
|
||||
"database.maxPoolSize" to 10,
|
||||
"database.connectionTimeoutMs" to 10000,
|
||||
"database.connectionTimeoutMs" to databaseConnectionTimeoutMs,
|
||||
"database.statementTimeoutMs" to 5000,
|
||||
"redis.host" to redis.host,
|
||||
"redis.port" to redis.port,
|
||||
"redis.password" to TestRedis.PASSWORD,
|
||||
"redis.connectTimeoutMs" to 500,
|
||||
"redis.commandTimeoutMs" to 500,
|
||||
"authentication.realm" to "messenger",
|
||||
"authentication.sessionTtlSeconds" to sessionTtlSeconds,
|
||||
"authentication.sessionCacheTtlSeconds" to 60,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
/**
|
||||
* Docker Desktop can be slow to accept the first connection, hence the generous default database timeout.
|
||||
*/
|
||||
fun runApp(
|
||||
sessionTtlSeconds: Long = 3600,
|
||||
database: PostgreSQLContainer<*> = TestDatabase.container,
|
||||
databaseConnectionTimeoutMs: Long = 10000,
|
||||
redis: RedisEndpoint = TestRedis.endpoint(),
|
||||
block: suspend ApplicationTestBuilder.(HttpClient) -> Unit
|
||||
) = testApplication {
|
||||
environment {
|
||||
config = testConfig(sessionTtlSeconds)
|
||||
config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis)
|
||||
}
|
||||
application {
|
||||
module()
|
||||
|
||||
@@ -14,11 +14,17 @@ object TestDatabase {
|
||||
const val PASSWORD = "messenger"
|
||||
|
||||
val container: PostgreSQLContainer<*> by lazy {
|
||||
PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres"))
|
||||
create().also { it.start() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A separate, not yet started container for tests that stop the database.
|
||||
*/
|
||||
fun create(): PostgreSQLContainer<*> {
|
||||
return PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres"))
|
||||
.withDatabaseName(NAME)
|
||||
.withUsername(USERNAME)
|
||||
.withPassword(PASSWORD)
|
||||
.also { it.start() }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.mtusi.messenger.main.support
|
||||
|
||||
import org.testcontainers.containers.GenericContainer
|
||||
import org.testcontainers.utility.DockerImageName
|
||||
import java.net.ServerSocket
|
||||
|
||||
/**
|
||||
* One Redis container per test JVM, same image and memory settings as compose.yaml.
|
||||
*/
|
||||
object TestRedis {
|
||||
|
||||
const val PASSWORD = "messenger"
|
||||
|
||||
private const val PORT = 6379
|
||||
|
||||
val container: GenericContainer<*> by lazy {
|
||||
create().also { it.start() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A separate, not yet started container for tests that pause or flush Redis.
|
||||
*/
|
||||
fun create(): GenericContainer<*> {
|
||||
return GenericContainer(DockerImageName.parse("redis:8.4.0-alpine"))
|
||||
.withExposedPorts(PORT)
|
||||
.withCommand(
|
||||
"redis-server",
|
||||
"--requirepass", PASSWORD,
|
||||
"--save", "",
|
||||
"--appendonly", "no",
|
||||
"--maxmemory-policy", "volatile-lru"
|
||||
)
|
||||
}
|
||||
|
||||
fun endpoint(container: GenericContainer<*> = this.container) = RedisEndpoint(
|
||||
host = container.host,
|
||||
port = container.getMappedPort(PORT)
|
||||
)
|
||||
|
||||
/**
|
||||
* An endpoint nobody listens on: connections are refused immediately.
|
||||
*/
|
||||
fun unreachableEndpoint(): RedisEndpoint {
|
||||
val port = ServerSocket(0).use { it.localPort }
|
||||
return RedisEndpoint(host = "127.0.0.1", port = port)
|
||||
}
|
||||
|
||||
fun cli(container: GenericContainer<*>, vararg command: String): String {
|
||||
val result = container.execInContainer("redis-cli", "--no-auth-warning", "-a", PASSWORD, *command)
|
||||
check(result.exitCode == 0) { "redis-cli failed: ${result.stderr}" }
|
||||
return result.stdout.trim()
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user