Completed for a grade of four

This commit is contained in:
2026-10-09 00:27:36 +03:00
parent 0d831df2cf
commit 1632fe4b16
40 changed files with 1034 additions and 61 deletions
@@ -6,6 +6,7 @@ import com.mtusi.messenger.main.plugins.configureContentNegotiation
import com.mtusi.messenger.main.plugins.configureDatabase
import com.mtusi.messenger.main.plugins.configureDefaultHeaders
import com.mtusi.messenger.main.plugins.configureKoin
import com.mtusi.messenger.main.plugins.configureRedis
import com.mtusi.messenger.main.plugins.configureRequestId
import com.mtusi.messenger.main.plugins.configureRouting
import com.mtusi.messenger.main.plugins.configureStatusPages
@@ -18,6 +19,7 @@ fun Application.module() {
configureKoin()
configureDatabase()
configureRedis()
configureContentNegotiation()
configureDefaultHeaders()
@@ -4,5 +4,6 @@ interface AuthenticationConfig {
val realm: String
val sessionTtlSeconds: Long
val sessionCacheTtlSeconds: Long
}
@@ -5,5 +5,6 @@ import kotlinx.serialization.Serializable
@Serializable
data class SerialAuthenticationConfig(
override val realm: String,
override val sessionTtlSeconds: Long
override val sessionTtlSeconds: Long,
override val sessionCacheTtlSeconds: Long
) : AuthenticationConfig
@@ -12,6 +12,7 @@ interface DatabaseConfig {
val maxPoolSize: Int
val connectionTimeoutMs: Long
val statementTimeoutMs: Long
val jdbcConnectionUrl: String
get() = "jdbc:postgresql://$host:$port/$name"
@@ -11,5 +11,6 @@ data class SerialDatabaseConfig(
override val password: String? = null,
override val passwordFile: String? = null,
override val maxPoolSize: Int,
override val connectionTimeoutMs: Long
override val connectionTimeoutMs: Long,
override val statementTimeoutMs: Long
) : DatabaseConfig
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.redis
import io.ktor.server.application.Application
import io.ktor.server.config.getAs
import org.koin.core.annotation.Provided
import org.koin.core.annotation.Single
@Single
class DefaultRedisConfig(
@Provided app: Application
) : RedisConfig by app.environment.config.property("redis").getAs<SerialRedisConfig>()
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.config.redis
interface RedisConfig {
val host: String
val port: Int
val username: String?
val password: String?
val passwordFile: String?
val connectTimeoutMs: Long
val commandTimeoutMs: Long
}
@@ -0,0 +1,14 @@
package com.mtusi.messenger.main.config.redis
import kotlinx.serialization.Serializable
@Serializable
data class SerialRedisConfig(
override val host: String,
override val port: Int,
override val username: String? = null,
override val password: String? = null,
override val passwordFile: String? = null,
override val connectTimeoutMs: Long,
override val commandTimeoutMs: Long
) : RedisConfig
@@ -44,9 +44,7 @@ fun Routing.configureAuthenticationRouting() = route("/api/v1/auth/sessions") {
authenticate(SESSION_AUTH) {
delete("current") {
suspendedTransaction {
authenticationService.revokeSession(call.currentUser.sessionId)
}
authenticationService.revokeSession(call.currentUser.session)
call.respond(HttpStatusCode.NoContent)
}
@@ -6,6 +6,7 @@ import kotlin.time.Instant
data class Session(
val id: UUID,
val userId: UUID,
val tokenHash: String,
val createdAt: Instant,
val expiresAt: Instant,
)
@@ -0,0 +1,88 @@
package com.mtusi.messenger.main.infrastructure.repositories._common
import com.mtusi.messenger.main.config.redis.RedisConfig
import com.mtusi.messenger.main.utils.resolveSecret
import io.lettuce.core.ClientOptions
import io.lettuce.core.RedisClient
import io.lettuce.core.RedisConnectionException
import io.lettuce.core.RedisURI
import io.lettuce.core.SocketOptions
import io.lettuce.core.TimeoutOptions
import io.lettuce.core.api.StatefulRedisConnection
import io.lettuce.core.api.async.RedisAsyncCommands
import io.lettuce.core.codec.StringCodec
import kotlinx.coroutines.future.await
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.koin.core.annotation.Single
import java.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeSource
private val RECONNECT_BACKOFF = 1.seconds
/**
* Lazily connected Redis client. The application must start and serve requests without Redis, so the connection
* is opened on first use, a failed attempt is not retried for [RECONNECT_BACKOFF], and commands issued while
* disconnected fail immediately instead of queueing behind the reconnect.
*/
@Single
class RedisConnection(
config: RedisConfig
) : AutoCloseable {
private val uri = RedisURI.builder()
.withHost(config.host)
.withPort(config.port)
.withTimeout(Duration.ofMillis(config.commandTimeoutMs))
.apply {
val password = resolveSecret(config.password, config.passwordFile)
if (password != null) {
if (config.username != null) withAuthentication(config.username, password) else withPassword(password.toCharArray())
}
}
.build()
private val client = RedisClient.create().apply {
options = ClientOptions.builder()
.autoReconnect(true)
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
.timeoutOptions(TimeoutOptions.enabled(Duration.ofMillis(config.commandTimeoutMs)))
.socketOptions(SocketOptions.builder().connectTimeout(Duration.ofMillis(config.connectTimeoutMs)).build())
.build()
}
private val mutex = Mutex()
@Volatile
private var connection: StatefulRedisConnection<String, String>? = null
@Volatile
private var nextAttempt = TimeSource.Monotonic.markNow()
suspend fun commands(): RedisAsyncCommands<String, String> {
return (connection ?: connect()).async()
}
private suspend fun connect(): StatefulRedisConnection<String, String> = mutex.withLock {
connection?.let { return it }
if (nextAttempt.hasNotPassedNow()) {
throw RedisConnectionException("Redis is unavailable, next connection attempt is postponed")
}
return try {
client.connectAsync(StringCodec.UTF8, uri).await().also { connection = it }
} catch (e: Exception) {
nextAttempt = TimeSource.Monotonic.markNow() + RECONNECT_BACKOFF
throw e as? RedisConnectionException ?: RedisConnectionException("Unable to connect to Redis", e)
}
}
override fun close() {
connection?.close()
client.shutdown()
}
}
@@ -13,6 +13,7 @@ import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Instant
@Single
@@ -21,20 +22,24 @@ class ExposedSessionRepository : SessionRepository {
override fun create(
userId: UUID,
tokenHash: String,
expiresAt: Instant
ttl: Duration
): Session {
val createdAt = Clock.System.nowMicros()
val expiresAt = createdAt + ttl
val insertedRow = SessionModel.insert {
it[this.userId] = userId
it[this.tokenHash] = tokenHash
it[this.createdAt] = Clock.System.nowMicros()
it[this.createdAt] = createdAt
it[this.expiresAt] = expiresAt
}
return Session(
id = insertedRow[SessionModel.id].value,
userId = userId,
createdAt = insertedRow[SessionModel.createdAt],
tokenHash = tokenHash,
createdAt = createdAt,
expiresAt = expiresAt
)
}
@@ -60,6 +65,7 @@ class ExposedSessionRepository : SessionRepository {
private fun ResultRow.toSession() = Session(
id = this[SessionModel.id].value,
userId = this[SessionModel.userId].value,
tokenHash = this[SessionModel.tokenHash],
createdAt = this[SessionModel.createdAt],
expiresAt = this[SessionModel.expiresAt]
)
@@ -3,6 +3,7 @@ package com.mtusi.messenger.main.infrastructure.repositories.authentication.sess
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import java.util.UUID
import kotlin.time.Duration
import kotlin.time.Instant
interface SessionRepository : Repository<UUID, Session> {
@@ -10,7 +11,7 @@ interface SessionRepository : Repository<UUID, Session> {
fun create(
userId: UUID,
tokenHash: String,
expiresAt: Instant
ttl: Duration
): Session
fun findActiveByTokenHash(
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
sealed class CachedSession {
data class Active(val session: Session) : CachedSession()
data object Revoked : CachedSession()
}
@@ -0,0 +1,86 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
import io.lettuce.core.SetArgs
import kotlinx.coroutines.future.await
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.koin.core.annotation.Single
import kotlin.time.Instant
private const val KEY_PREFIX = "session:"
private const val REVOKED = "revoked"
@Single
class RedisSessionCacheRepository(
private val redis: RedisConnection
) : SessionCacheRepository {
override suspend fun find(
tokenHash: String
): CachedSession? {
val value = redis.commands().get(key(tokenHash)).await() ?: return null
if (value == REVOKED) {
return CachedSession.Revoked
}
return CachedSession.Active(
Json.decodeFromString<SessionEntry>(value).toSession(tokenHash)
)
}
override suspend fun putIfAbsent(
session: Session,
cachedUntil: Instant
) {
redis.commands().set(
key(session.tokenHash),
Json.encodeToString(SessionEntry.from(session)),
SetArgs.Builder.nx().pxAt(cachedUntil.toEpochMilliseconds())
).await()
}
override suspend fun revoke(
session: Session
) {
redis.commands().set(
key(session.tokenHash),
REVOKED,
SetArgs.Builder.pxAt(session.expiresAt.toEpochMilliseconds())
).await()
}
private fun key(tokenHash: String) = KEY_PREFIX + tokenHash
@Serializable
private data class SessionEntry(
val id: SerialUUID,
val userId: SerialUUID,
val createdAt: Instant,
val expiresAt: Instant
) {
fun toSession(tokenHash: String) = Session(
id = id,
userId = userId,
tokenHash = tokenHash,
createdAt = createdAt,
expiresAt = expiresAt
)
companion object {
fun from(session: Session) = SessionEntry(
id = session.id,
userId = session.userId,
createdAt = session.createdAt,
expiresAt = session.expiresAt
)
}
}
}
@@ -0,0 +1,33 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import kotlin.time.Instant
/**
* Cache-aside copy of [com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository].
* PostgreSQL stays the source of truth: losing every key only costs a database lookup.
*/
interface SessionCacheRepository : Repository<String, Session> {
suspend fun find(
tokenHash: String
): CachedSession?
/**
* Stores the session until [cachedUntil] unless the key already exists, so a lookup racing with a logout
* cannot overwrite the tombstone written by [revoke].
*/
suspend fun putIfAbsent(
session: Session,
cachedUntil: Instant
)
/**
* Replaces the entry with a tombstone that lives until the session would have expired.
*/
suspend fun revoke(
session: Session
)
}
@@ -16,12 +16,19 @@ interface AuthenticationService {
userId: UUID
): IssuedSession
fun findSessionByToken(
/**
* Opens its own transaction only on a cache miss, so it must not be called inside one.
*/
suspend fun findSessionByToken(
token: String
): Session?
fun revokeSession(
sessionId: UUID
/**
* Deletes the session in PostgreSQL, then replaces its cached copy with a tombstone. Without Redis only the
* database is updated: a copy cached before the outage can then live for at most the cache TTL.
*/
suspend fun revokeSession(
session: Session
): Boolean
}
@@ -5,16 +5,21 @@ import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.CachedSession
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.SessionCacheRepository
import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository
import com.mtusi.messenger.main.infrastructure.services.hashing.HashingService
import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.computeSha256
import com.mtusi.messenger.main.utils.nowMicros
import io.lettuce.core.RedisException
import org.koin.core.annotation.Single
import org.slf4j.LoggerFactory
import java.security.SecureRandom
import java.util.Base64
import java.util.UUID
import kotlin.time.Clock
import kotlin.time.Instant
import kotlin.time.Duration.Companion.seconds
private const val TOKEN_BYTES = 32
@@ -23,10 +28,13 @@ private const val TOKEN_BYTES = 32
class DefaultAuthenticationService(
private val userRepository: UserRepository,
private val sessionRepository: SessionRepository,
private val sessionCacheRepository: SessionCacheRepository,
private val hashingService: HashingService,
private val config: AuthenticationConfig
) : AuthenticationService {
private val logger = LoggerFactory.getLogger(DefaultAuthenticationService::class.java)
private val random = SecureRandom()
private val dummyPasswordHash by lazy {
@@ -64,7 +72,7 @@ class DefaultAuthenticationService(
val session = sessionRepository.create(
userId = userId,
tokenHash = token.toByteArray().computeSha256(),
expiresAt = Clock.System.nowMicros() + config.sessionTtlSeconds.seconds
ttl = config.sessionTtlSeconds.seconds
)
return IssuedSession(
@@ -73,19 +81,68 @@ class DefaultAuthenticationService(
)
}
override fun findSessionByToken(
override suspend fun findSessionByToken(
token: String
): Session? {
return sessionRepository.findActiveByTokenHash(
tokenHash = token.toByteArray().computeSha256(),
now = Clock.System.now()
)
val tokenHash = token.toByteArray().computeSha256()
val now = Clock.System.now()
when (val cached = findCachedSession(tokenHash)) {
is CachedSession.Revoked -> return null
is CachedSession.Active -> return cached.session.takeIf { it.expiresAt > now }
null -> Unit
}
val session = suspendedTransaction {
sessionRepository.findActiveByTokenHash(tokenHash, now)
} ?: return null
cacheSession(session, now)
return session
}
override fun revokeSession(
sessionId: UUID
override suspend fun revokeSession(
session: Session
): Boolean {
return sessionRepository.deleteById(sessionId)
val isDeleted = suspendedTransaction {
sessionRepository.deleteById(session.id)
}
try {
sessionCacheRepository.revoke(session)
} catch (e: RedisException) {
logger.warn("Session cache is unavailable, revoked session is not tombstoned: ${e.message}")
}
return isDeleted
}
private suspend fun findCachedSession(
tokenHash: String
): CachedSession? {
return try {
sessionCacheRepository.find(tokenHash)
} catch (e: RedisException) {
logger.warn("Session cache is unavailable, reading from the database: ${e.message}")
null
}
}
private suspend fun cacheSession(
session: Session,
now: Instant
) {
try {
sessionCacheRepository.putIfAbsent(
session = session,
cachedUntil = minOf(session.expiresAt, now + config.sessionCacheTtlSeconds.seconds)
)
} catch (e: RedisException) {
logger.warn("Session cache is unavailable, session is not cached: ${e.message}")
}
}
}
@@ -7,6 +7,7 @@ import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.infrastructure.models.message.MessageModel
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import com.mtusi.messenger.main.utils.resolveSecret
import com.typesafe.config.ConfigFactory
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
@@ -30,6 +31,7 @@ import javax.sql.DataSource
private const val MIGRATIONS_DIRECTORY = "src/main/resources/migrations"
private const val DEVELOPMENT_DATABASE_CONFIG = "run/development/config/database.conf"
private const val VALIDATION_TIMEOUT_MS = 1000L
fun Application.configureDatabase() {
@@ -57,19 +59,15 @@ private fun DatabaseConfig.createDataSource(): HikariDataSource {
poolName = "messenger"
jdbcUrl = jdbcConnectionUrl
username = this@createDataSource.username
password = resolvePassword()
password = resolveSecret(this@createDataSource.password, passwordFile).orEmpty()
maximumPoolSize = maxPoolSize
connectionTimeout = connectionTimeoutMs
validationTimeout = minOf(VALIDATION_TIMEOUT_MS, connectionTimeoutMs - 1)
addDataSourceProperty("options", "-c statement_timeout=$statementTimeoutMs")
}
)
}
private fun DatabaseConfig.resolvePassword(): String {
return password
?: passwordFile?.let { File(it).readText().trim() }
?: ""
}
fun applyDatabaseMigrations(
dataSource: DataSource
) {
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
import io.ktor.server.application.Application
import io.ktor.server.application.ApplicationStopped
import org.koin.ktor.ext.get
fun Application.configureRedis() {
val redisConnection = get<RedisConnection>()
monitor.subscribe(ApplicationStopped) {
redisConnection.close()
}
}
@@ -12,12 +12,16 @@ import io.ktor.server.plugins.BadRequestException
import io.ktor.server.plugins.NotFoundException
import io.ktor.server.plugins.UnsupportedMediaTypeException
import io.ktor.server.plugins.statuspages.StatusPages
import io.lettuce.core.RedisException
import kotlinx.serialization.SerializationException
import java.sql.SQLException
import java.sql.SQLTransientConnectionException
private const val CONNECTION_ERROR_SQL_STATE_CLASS = "08"
// admin_shutdown, crash_shutdown, cannot_connect_now: the server is going down or still starting.
private const val SERVER_SHUTDOWN_SQL_STATE_PREFIX = "57P"
fun Application.configureStatusPages() = install(StatusPages) {
exception<ApiException> { call, cause ->
call.respondError(cause.code, cause.message ?: cause.code.wire)
@@ -46,6 +50,10 @@ fun Application.configureStatusPages() = install(StatusPages) {
call.respondError(ErrorCode.INTERNAL_ERROR, "internal error")
}
}
exception<RedisException> { call, cause ->
call.application.log.warn("Redis unavailable: ${cause.message}")
call.respondError(ErrorCode.UNAVAILABLE, "service temporarily unavailable")
}
exception<Throwable> { call, cause ->
call.application.log.error("Unhandled error", cause)
call.respondError(ErrorCode.INTERNAL_ERROR, "internal error")
@@ -61,6 +69,10 @@ fun Application.configureStatusPages() = install(StatusPages) {
private fun SQLException.isConnectionFailure(): Boolean {
return generateSequence<Throwable>(this) { it.cause }.any {
it is SQLTransientConnectionException ||
(it is SQLException && it.sqlState?.startsWith(CONNECTION_ERROR_SQL_STATE_CLASS) == true)
(it is SQLException && it.sqlState.isUnavailableState())
}
}
private fun String?.isUnavailableState(): Boolean {
return this != null && (startsWith(CONNECTION_ERROR_SQL_STATE_CLASS) || startsWith(SERVER_SHUTDOWN_SQL_STATE_PREFIX))
}
@@ -32,14 +32,9 @@ fun Application.configureAuthentication() {
bearerSession(SESSION_AUTH) {
authenticate { token ->
val session = suspendedTransaction {
authenticationService.findSessionByToken(token)
} ?: return@authenticate null
val session = authenticationService.findSessionByToken(token) ?: return@authenticate null
return@authenticate UserPrincipal(
id = session.userId,
sessionId = session.id
)
return@authenticate UserPrincipal(session)
}
}
@@ -1,8 +1,13 @@
package com.mtusi.messenger.main.plugins.authentication
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import java.util.UUID
data class UserPrincipal(
val id: UUID,
val sessionId: UUID
)
val session: Session
) {
val id: UUID
get() = session.userId
}
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.utils
import java.io.File
/**
* Secrets come either inline (local development) or as a mounted file (Docker secrets), the inline value wins.
*/
fun resolveSecret(
value: String?,
file: String?
): String? {
return value ?: file?.let { File(it).readText().trim() }
}
+13
View File
@@ -27,10 +27,23 @@ database {
maxPoolSize = 10
maxPoolSize = ${?DB_MAX_POOL_SIZE}
connectionTimeoutMs = 2000
statementTimeoutMs = 5000
}
redis {
host = "localhost"
host = ${?REDIS_HOST}
port = 6379
port = ${?REDIS_PORT}
password = ${?REDIS_PASSWORD}
passwordFile = ${?REDIS_PASSWORD_FILE}
connectTimeoutMs = 500
commandTimeoutMs = 500
}
authentication {
realm = "messenger"
sessionTtlSeconds = 3600
sessionTtlSeconds = ${?SESSION_TTL_SECONDS}
sessionCacheTtlSeconds = 60
}