Move lab2 to lab3

This commit is contained in:
2026-10-22 20:21:52 +03:00
parent 0ab3a341aa
commit a3dbcd6ba4
135 changed files with 5897 additions and 0 deletions
@@ -0,0 +1,33 @@
package com.mtusi.messenger.main
import com.mtusi.messenger.main.plugins.authentication.configureAuthentication
import com.mtusi.messenger.main.plugins.configureCallLogging
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
import io.ktor.server.application.Application
import io.ktor.server.netty.EngineMain
fun main(args: Array<String>): Unit = EngineMain.main(args)
fun Application.module() {
configureKoin()
configureDatabase()
configureRedis()
configureContentNegotiation()
configureDefaultHeaders()
configureRequestId()
configureCallLogging()
configureStatusPages()
configureAuthentication()
configureRouting()
}
@@ -0,0 +1,31 @@
package com.mtusi.messenger.main.compat.serializers
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.util.UUID
typealias SerialUUID = @Serializable(UUIDSerializer::class) UUID
object UUIDSerializer : KSerializer<UUID> {
override val descriptor = PrimitiveSerialDescriptor(
serialName = "UUID",
kind = PrimitiveKind.STRING
)
override fun deserialize(decoder: Decoder): UUID {
return decoder.decodeString().run(UUID::fromString)
}
override fun serialize(
encoder: Encoder,
value: UUID
) {
encoder.encodeString(value.toString())
}
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.config
import org.koin.core.annotation.ComponentScan
import org.koin.core.annotation.Module
@Module(createdAtStart = true)
@ComponentScan
class ConfigModule
@@ -0,0 +1,10 @@
package com.mtusi.messenger.main.config.authentication
interface AuthenticationConfig {
val realm: String
val sessionTtlSeconds: Long
val sessionCacheTtlSeconds: Long
val sessionCacheSingleFlight: Boolean
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.authentication
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 DefaultAuthenticationConfig(
@Provided app: Application
) : AuthenticationConfig by app.environment.config.property("authentication").getAs<SerialAuthenticationConfig>()
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.authentication
import kotlinx.serialization.Serializable
@Serializable
data class SerialAuthenticationConfig(
override val realm: String,
override val sessionTtlSeconds: Long,
override val sessionCacheTtlSeconds: Long,
override val sessionCacheSingleFlight: Boolean = true
) : AuthenticationConfig
@@ -0,0 +1,20 @@
package com.mtusi.messenger.main.config.database
interface DatabaseConfig {
val host: String
val port: Int
val name: String
val username: String
val password: String?
val passwordFile: String?
val maxPoolSize: Int
val connectionTimeoutMs: Long
val statementTimeoutMs: Long
val jdbcConnectionUrl: String
get() = "jdbc:postgresql://$host:$port/$name"
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.database
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 DefaultDatabaseConfig(
@Provided app: Application
) : DatabaseConfig by app.environment.config.property("database").getAs<SerialDatabaseConfig>()
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.config.database
import kotlinx.serialization.Serializable
@Serializable
data class SerialDatabaseConfig(
override val host: String,
override val port: Int,
override val name: String,
override val username: String,
override val password: String? = null,
override val passwordFile: String? = null,
override val maxPoolSize: Int,
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
@@ -0,0 +1,37 @@
package com.mtusi.messenger.main.extensions
import com.mtusi.messenger.main.infrastructure.types.AuthChallenge
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.RequestIdKey
import com.mtusi.messenger.main.plugins.authentication.UserPrincipal
import io.ktor.http.HttpHeaders
import io.ktor.server.application.ApplicationCall
import io.ktor.server.auth.principal
import io.ktor.server.response.header
import io.ktor.server.response.respond
import kotlinx.serialization.Serializable
@Serializable
data class ErrorBody(val error: ErrorDetails)
@Serializable
data class ErrorDetails(
val code: String,
val message: String,
val requestId: String,
)
suspend fun ApplicationCall.respondError(
code: ErrorCode,
message: String,
challenge: String = AuthChallenge.BEARER,
) {
val requestId = attributes[RequestIdKey]
if (code == ErrorCode.UNAUTHORIZED) {
response.header(HttpHeaders.WWWAuthenticate, challenge)
}
respond(code.status, ErrorBody(ErrorDetails(code.wire, message, requestId)))
}
val ApplicationCall.currentUser: UserPrincipal
get() = principal<UserPrincipal>()!!
@@ -0,0 +1,31 @@
package com.mtusi.messenger.main.infrastructure.controllers._common.parameters
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import io.ktor.server.application.ApplicationCall
private const val DEFAULT_LIMIT = 50
private const val MAX_LIMIT = 100
data class PageParameters(
val limit: Int,
val cursor: String?
)
fun ApplicationCall.pageParameters(): PageParameters {
val query = request.queryParameters
val limit = query["limit"]
?.let { it.toIntOrNull() ?: throw ApiException(ErrorCode.INVALID_REQUEST, "invalid limit") }
?: DEFAULT_LIMIT
if (limit !in 1..MAX_LIMIT) {
throw ApiException(ErrorCode.INVALID_REQUEST, "limit out of range")
}
val cursor = query["cursor"]
?.takeIf { it.isNotEmpty() }
return PageParameters(limit, cursor)
}
@@ -0,0 +1,53 @@
package com.mtusi.messenger.main.infrastructure.controllers.authentication
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.infrastructure.controllers.authentication.responses.SessionResponse
import com.mtusi.messenger.main.infrastructure.services.authentication.AuthenticationService
import com.mtusi.messenger.main.plugins.authentication.CREDENTIALS_AUTH
import com.mtusi.messenger.main.plugins.authentication.CredentialsPrincipal
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.plugins.suspendedTransaction
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
import io.ktor.server.auth.principal
import io.ktor.server.response.respond
import io.ktor.server.routing.Routing
import io.ktor.server.routing.delete
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import org.koin.ktor.ext.inject
fun Routing.configureAuthenticationRouting() = route("/api/v1/auth/sessions") {
val authenticationService by inject<AuthenticationService>()
authenticate(CREDENTIALS_AUTH) {
post {
val (user) = call.principal<CredentialsPrincipal>()!!
val issued = suspendedTransaction {
authenticationService.createSession(user.id)
}
call.respond(
HttpStatusCode.Created,
SessionResponse(
token = issued.token,
expiresAt = issued.session.expiresAt,
user = user
)
)
}
}
authenticate(SESSION_AUTH) {
delete("current") {
authenticationService.revokeSession(call.currentUser.session)
call.respond(HttpStatusCode.NoContent)
}
}
}
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.infrastructure.controllers.authentication.responses
import com.mtusi.messenger.main.infrastructure.dto.User
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class SessionResponse(
val token: String,
val tokenType: String = "Bearer",
val expiresAt: Instant,
val user: User,
)
@@ -0,0 +1,112 @@
package com.mtusi.messenger.main.infrastructure.controllers.chat
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.controllers._common.parameters.pageParameters
import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest
import com.mtusi.messenger.main.infrastructure.models.chat.MAX_CHAT_MEMBERS
import com.mtusi.messenger.main.infrastructure.models.chat.MAX_CHAT_TITLE_LENGTH
import com.mtusi.messenger.main.infrastructure.services.chat.ChatService
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatCreationResult
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.requireNonBlankBounded
import com.mtusi.messenger.main.utils.requireUuid
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Routing
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import org.koin.ktor.ext.inject
fun Routing.configureChatRouting() = route("/api/v1/chats") {
val chatService by inject<ChatService>()
authenticate(SESSION_AUTH) {
post {
val actor = call.currentUser
val body = call.receive<CreateChatRequest>()
requireNonBlankBounded(
body.title,
min = 1,
max = MAX_CHAT_TITLE_LENGTH,
field = "title"
)
if (body.memberIds.isEmpty() || body.memberIds.size > MAX_CHAT_MEMBERS) {
throw ApiException(ErrorCode.INVALID_REQUEST, "member_ids size out of range")
}
val memberIds = body.memberIds.map { requireUuid(it, "member_ids") }
val result = suspendedTransaction {
chatService.create(
creatorId = actor.id,
title = body.title,
memberIds = memberIds
)
}
when (result) {
is ChatCreationResult.DuplicateMembers ->
call.respondError(ErrorCode.INVALID_REQUEST, "member_ids must be unique")
is ChatCreationResult.CreatorNotMember ->
call.respondError(ErrorCode.INVALID_REQUEST, "creator must be in member ids")
is ChatCreationResult.UnknownMembers ->
call.respondError(ErrorCode.INVALID_REQUEST, "unknown member")
is ChatCreationResult.Success ->
call.respond(HttpStatusCode.Created, result.chat)
}
}
get {
val actor = call.currentUser
val (limit, cursor) = call.pageParameters()
val result = suspendedTransaction {
chatService.findPageAccessible(
userId = actor.id,
limit = limit,
cursor = cursor
)
}
when (result) {
is ChatPageResult.InvalidCursor ->
call.respondError(ErrorCode.INVALID_REQUEST, "invalid cursor")
is ChatPageResult.Success ->
call.respond(HttpStatusCode.OK, result.page)
}
}
get("{chat_id}") {
val actor = call.currentUser
val chatId = requireUuid(call.parameters["chat_id"], "chat_id")
val chat = suspendedTransaction {
chatService.findAccessible(actor.id, chatId)
}
if (chat == null) {
call.respondError(ErrorCode.NOT_FOUND, "chat not found")
return@get
}
call.respond(HttpStatusCode.OK, chat)
}
}
}
@@ -0,0 +1,9 @@
package com.mtusi.messenger.main.infrastructure.controllers.chat.requests
import kotlinx.serialization.Serializable
@Serializable
data class CreateChatRequest(
val title: String,
val memberIds: List<String>,
)
@@ -0,0 +1,41 @@
package com.mtusi.messenger.main.infrastructure.controllers.health
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.controllers.health.responses.HealthResponse
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.suspendedTransaction
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.log
import io.ktor.server.response.respond
import io.ktor.server.routing.Routing
import io.ktor.server.routing.get
import io.ktor.server.routing.route
fun Routing.configureHealthRouting() = route("/health") {
get("live") {
call.respond(HttpStatusCode.OK, HealthResponse())
}
// PostgreSQL is the only dependency of the synchronous path: without it nothing can be served.
get("ready") {
val isDatabaseReachable = try {
suspendedTransaction {
exec("SELECT 1")
}
true
} catch (cause: Exception) {
call.application.log.warn("Readiness check failed: ${cause.message}")
false
}
if (!isDatabaseReachable) {
call.respondError(ErrorCode.UNAVAILABLE, "database unavailable")
return@get
}
call.respond(HttpStatusCode.OK, HealthResponse())
}
}
@@ -0,0 +1,6 @@
package com.mtusi.messenger.main.infrastructure.controllers.health.responses
import kotlinx.serialization.Serializable
@Serializable
data class HealthResponse(val status: String = "ok")
@@ -0,0 +1,88 @@
package com.mtusi.messenger.main.infrastructure.controllers.message
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.controllers._common.parameters.pageParameters
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
import com.mtusi.messenger.main.infrastructure.models.message.MAX_MESSAGE_TEXT_LENGTH
import com.mtusi.messenger.main.infrastructure.services.message.MessageService
import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult
import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.requireNonBlankBounded
import com.mtusi.messenger.main.utils.requireUuid
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Routing
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import org.koin.ktor.ext.inject
fun Routing.configureMessageRouting() = route("/api/v1/chats/{chat_id}/messages") {
val messageService by inject<MessageService>()
authenticate(SESSION_AUTH) {
post {
val actor = call.currentUser
val chatId = requireUuid(call.parameters["chat_id"], "chat_id")
val body = call.receive<CreateMessageRequest>()
requireNonBlankBounded(
body.text,
min = 1,
max = MAX_MESSAGE_TEXT_LENGTH,
field = "text"
)
val result = suspendedTransaction {
messageService.send(
chatId = chatId,
senderId = actor.id,
text = body.text
)
}
when (result) {
is MessageCreationResult.ChatNotFound ->
call.respondError(ErrorCode.NOT_FOUND, "chat not found")
is MessageCreationResult.Success ->
call.respond(HttpStatusCode.Created, result.message)
}
}
get {
val actor = call.currentUser
val chatId = requireUuid(call.parameters["chat_id"], "chat_id")
val (limit, cursor) = call.pageParameters()
val result = suspendedTransaction {
messageService.findPageByChatId(
chatId = chatId,
actorId = actor.id,
limit = limit,
cursor = cursor
)
}
when (result) {
is MessagePageResult.ChatNotFound ->
call.respondError(ErrorCode.NOT_FOUND, "chat not found")
is MessagePageResult.InvalidCursor ->
call.respondError(ErrorCode.INVALID_REQUEST, "invalid cursor")
is MessagePageResult.Success ->
call.respond(HttpStatusCode.OK, result.page)
}
}
}
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.controllers.message.requests
import kotlinx.serialization.Serializable
@Serializable
data class CreateMessageRequest(
val text: String,
)
@@ -0,0 +1,83 @@
package com.mtusi.messenger.main.infrastructure.controllers.user
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest
import com.mtusi.messenger.main.infrastructure.models.user.MAX_DISPLAY_NAME_LENGTH
import com.mtusi.messenger.main.infrastructure.services.user.UserService
import com.mtusi.messenger.main.infrastructure.services.user.results.UserCreationResult
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.requireNonBlankBounded
import com.mtusi.messenger.main.utils.requireUsername
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Routing
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import org.koin.ktor.ext.inject
private const val PASSWORD_MIN = 12
private const val PASSWORD_MAX = 128
fun Routing.configureUserRouting() = route("/api/v1/users") {
val userService by inject<UserService>()
post {
val body = call.receive<CreateUserRequest>()
requireUsername(body.username)
requireNonBlankBounded(
body.displayName,
min = 1,
max = MAX_DISPLAY_NAME_LENGTH,
field = "display_name"
)
requireNonBlankBounded(
body.password,
min = PASSWORD_MIN,
max = PASSWORD_MAX,
field = "password"
)
val result = suspendedTransaction {
userService.create(
username = body.username,
displayName = body.displayName,
password = body.password
)
}
when (result) {
is UserCreationResult.UsernameTaken ->
call.respondError(ErrorCode.CONFLICT, "username already taken")
is UserCreationResult.Success ->
call.respond(HttpStatusCode.Created, result.user)
}
}
authenticate(SESSION_AUTH) {
get("me") {
val user = suspendedTransaction {
userService.findById(call.currentUser.id)
}
if (user == null) {
call.respondError(ErrorCode.UNAUTHORIZED, "unknown user")
return@get
}
call.respond(HttpStatusCode.OK, user)
}
}
}
@@ -0,0 +1,10 @@
package com.mtusi.messenger.main.infrastructure.controllers.user.requests
import kotlinx.serialization.Serializable
@Serializable
data class CreateUserRequest(
val username: String,
val displayName: String,
val password: String,
)
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.infrastructure.dto
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class Chat(
val id: SerialUUID,
val title: String,
val memberIds: List<SerialUUID>,
val createdAt: Instant,
)
@@ -0,0 +1,14 @@
package com.mtusi.messenger.main.infrastructure.dto
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class Message(
val id: SerialUUID,
val chatId: SerialUUID,
val senderId: SerialUUID,
val text: String,
val createdAt: Instant,
)
@@ -0,0 +1,9 @@
package com.mtusi.messenger.main.infrastructure.dto
import kotlinx.serialization.Serializable
@Serializable
data class PageResponse<T : Any>(
val items: List<T>,
val nextCursor: String?,
)
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.infrastructure.dto
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class User(
val id: SerialUUID,
val username: String,
val displayName: String,
val createdAt: Instant,
)
@@ -0,0 +1,6 @@
package com.mtusi.messenger.main.infrastructure.dto.authentication
data class IssuedSession(
val session: Session,
val token: String,
)
@@ -0,0 +1,12 @@
package com.mtusi.messenger.main.infrastructure.dto.authentication
import java.util.UUID
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,8 @@
package com.mtusi.messenger.main.infrastructure.dto.authentication
import kotlin.time.Instant
data class SessionRevocation(
val tokenHash: String,
val expiresAt: Instant,
)
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.dto.authentication
import com.mtusi.messenger.main.infrastructure.dto.User
data class UserCredentials(
val user: User,
val passwordHash: String,
)
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.models.authentication
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import org.jetbrains.exposed.v1.core.ReferenceOption
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
object SessionModel : UUIDTable("sessions") {
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "sessions_user_id_fkey")
val tokenHash = varchar("token_hash", 64).uniqueIndex("sessions_token_hash_key")
val createdAt = timestamp("created_at")
val expiresAt = timestamp("expires_at")
init {
index("sessions_user_id_idx", false, userId)
}
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.infrastructure.models.authentication
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.datetime.timestamp
object SessionRevocationModel : Table("session_revocations") {
val tokenHash = varchar("token_hash", 64)
val expiresAt = timestamp("expires_at")
override val primaryKey = PrimaryKey(tokenHash, name = "session_revocations_pkey")
}
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.models.chat
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import org.jetbrains.exposed.v1.core.ReferenceOption
import org.jetbrains.exposed.v1.core.Table
object ChatMemberModel : Table("chat_members") {
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "chat_members_chat_id_fkey")
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "chat_members_user_id_fkey")
val position = integer("position")
override val primaryKey = PrimaryKey(chatId, userId)
init {
index("chat_members_user_id_idx", false, userId)
}
}
@@ -0,0 +1,12 @@
package com.mtusi.messenger.main.infrastructure.models.chat
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
const val MAX_CHAT_TITLE_LENGTH = 100
const val MAX_CHAT_MEMBERS = 100
object ChatModel : UUIDTable("chats") {
val title = varchar("title", MAX_CHAT_TITLE_LENGTH)
val createdAt = timestamp("created_at")
}
@@ -0,0 +1,20 @@
package com.mtusi.messenger.main.infrastructure.models.message
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import org.jetbrains.exposed.v1.core.ReferenceOption
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
const val MAX_MESSAGE_TEXT_LENGTH = 4000
object MessageModel : UUIDTable("messages") {
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "messages_chat_id_fkey")
val senderId = reference("sender_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "messages_sender_id_fkey")
val text = varchar("text", MAX_MESSAGE_TEXT_LENGTH)
val createdAt = timestamp("created_at")
init {
index("messages_chat_id_created_at_id_idx", false, chatId, createdAt, id)
}
}
@@ -0,0 +1,14 @@
package com.mtusi.messenger.main.infrastructure.models.user
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
const val MAX_USERNAME_LENGTH = 32
const val MAX_DISPLAY_NAME_LENGTH = 100
object UserModel : UUIDTable("users") {
val username = varchar("username", MAX_USERNAME_LENGTH).uniqueIndex("users_username_key")
val displayName = varchar("display_name", MAX_DISPLAY_NAME_LENGTH)
val passwordHash = varchar("password_hash", 255)
val createdAt = timestamp("created_at")
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.repositories
import org.koin.core.annotation.ComponentScan
import org.koin.core.annotation.Module
@Module
@ComponentScan
class RepositoriesModule
@@ -0,0 +1,3 @@
package com.mtusi.messenger.main.infrastructure.repositories
interface Repository<TId, TEntity>
@@ -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()
}
}
@@ -0,0 +1,73 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionModel
import com.mtusi.messenger.main.utils.nowMicros
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.greater
import org.jetbrains.exposed.v1.jdbc.deleteWhere
import org.jetbrains.exposed.v1.jdbc.insert
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
class ExposedSessionRepository : SessionRepository {
override fun create(
userId: UUID,
tokenHash: String,
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] = createdAt
it[this.expiresAt] = expiresAt
}
return Session(
id = insertedRow[SessionModel.id].value,
userId = userId,
tokenHash = tokenHash,
createdAt = createdAt,
expiresAt = expiresAt
)
}
override fun findActiveByTokenHash(
tokenHash: String,
now: Instant
): Session? {
return SessionModel
.selectAll()
.where((SessionModel.tokenHash eq tokenHash) and (SessionModel.expiresAt greater now))
.firstOrNull()
?.toSession()
}
override fun deleteById(
id: UUID
): Boolean {
val deletedRows = SessionModel.deleteWhere { SessionModel.id eq id }
return deletedRows > 0
}
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]
)
}
@@ -0,0 +1,26 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session
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> {
fun create(
userId: UUID,
tokenHash: String,
ttl: Duration
): Session
fun findActiveByTokenHash(
tokenHash: String,
now: Instant
): Session?
fun deleteById(
id: UUID
): Boolean
}
@@ -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,87 @@
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(
tokenHash: String,
expiresAt: Instant
) {
redis.commands().set(
key(tokenHash),
REVOKED,
SetArgs.Builder.pxAt(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,34 @@
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 [expiresAt], when the session would have expired.
*/
suspend fun revoke(
tokenHash: String,
expiresAt: Instant
)
}
@@ -0,0 +1,52 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation
import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionRevocationModel
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.greater
import org.jetbrains.exposed.v1.core.lessEq
import org.jetbrains.exposed.v1.jdbc.deleteWhere
import org.jetbrains.exposed.v1.jdbc.insertIgnore
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import kotlin.time.Instant
@Single
class ExposedSessionRevocationRepository : SessionRevocationRepository {
override fun add(
revocation: SessionRevocation
) {
SessionRevocationModel.insertIgnore {
it[tokenHash] = revocation.tokenHash
it[expiresAt] = revocation.expiresAt
}
}
override fun findPending(
now: Instant
): List<SessionRevocation> {
return SessionRevocationModel
.selectAll()
.where(SessionRevocationModel.expiresAt greater now)
.map {
SessionRevocation(
tokenHash = it[SessionRevocationModel.tokenHash],
expiresAt = it[SessionRevocationModel.expiresAt]
)
}
}
override fun delete(
tokenHash: String
) {
SessionRevocationModel.deleteWhere { SessionRevocationModel.tokenHash eq tokenHash }
}
override fun deleteExpired(
now: Instant
) {
SessionRevocationModel.deleteWhere { SessionRevocationModel.expiresAt lessEq now }
}
}
@@ -0,0 +1,31 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation
import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import kotlin.time.Instant
/**
* Logouts that still have to be written to the session cache as tombstones (outbox).
*/
interface SessionRevocationRepository : Repository<String, SessionRevocation> {
fun add(
revocation: SessionRevocation
)
/**
* Revocations of sessions that have not expired yet: an expired session is rejected even if its copy is cached.
*/
fun findPending(
now: Instant
): List<SessionRevocation>
fun delete(
tokenHash: String
)
fun deleteExpired(
now: Instant
)
}
@@ -0,0 +1,33 @@
package com.mtusi.messenger.main.infrastructure.repositories.chat
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import com.mtusi.messenger.main.utils.PageKey
import java.util.UUID
interface ChatRepository : Repository<UUID, Chat> {
fun create(
title: String,
memberIds: List<UUID>
): Chat
fun findById(
id: UUID
): Chat?
fun isMember(
chatId: UUID,
userId: UUID
): Boolean
/**
* Chats of [userId] ordered by `(created_at, id)`, strictly after [after].
*/
fun findPageByMemberId(
userId: UUID,
after: PageKey?,
limit: Int
): List<Chat>
}
@@ -0,0 +1,134 @@
package com.mtusi.messenger.main.infrastructure.repositories.chat
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.exposed.operations.RowGreater
import com.mtusi.messenger.main.utils.nowMicros
import org.jetbrains.exposed.v1.core.QueryParameter
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.SortOrder
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.dao.id.EntityID
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.inList
import org.jetbrains.exposed.v1.jdbc.batchInsert
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
@Single
class ExposedChatRepository : ChatRepository {
override fun create(
title: String,
memberIds: List<UUID>
): Chat {
val insertedRow = ChatModel.insert {
it[this.title] = title
it[this.createdAt] = Clock.System.nowMicros()
}
val chatId = insertedRow[ChatModel.id].value
ChatMemberModel.batchInsert(memberIds.withIndex()) { (position, userId) ->
this[ChatMemberModel.chatId] = chatId
this[ChatMemberModel.userId] = userId
this[ChatMemberModel.position] = position
}
return Chat(
id = chatId,
title = title,
memberIds = memberIds,
createdAt = insertedRow[ChatModel.createdAt]
)
}
override fun findById(
id: UUID
): Chat? {
val row = ChatModel
.selectAll()
.where(ChatModel.id eq id)
.firstOrNull()
?: return null
return row.toChat(findMemberIds(listOf(id))[id].orEmpty())
}
override fun isMember(
chatId: UUID,
userId: UUID
): Boolean {
return ChatMemberModel
.selectAll()
.where((ChatMemberModel.chatId eq chatId) and (ChatMemberModel.userId eq userId))
.empty()
.not()
}
override fun findPageByMemberId(
userId: UUID,
after: PageKey?,
limit: Int
): List<Chat> {
var condition = ChatMemberModel.userId eq userId
if (after != null) {
condition = condition and RowGreater(
left = listOf(ChatModel.createdAt, ChatModel.id),
right = listOf(
QueryParameter(after.createdAt, ChatModel.createdAt.columnType),
QueryParameter(EntityID(after.id, ChatModel), ChatModel.id.columnType)
)
)
}
val rows = ChatModel
.innerJoin(ChatMemberModel)
.selectAll()
.where(condition)
.orderBy(ChatModel.createdAt to SortOrder.ASC, ChatModel.id to SortOrder.ASC)
.limit(limit)
.toList()
val memberIds = findMemberIds(rows.map { it[ChatModel.id].value })
return rows.map {
it.toChat(memberIds[it[ChatModel.id].value].orEmpty())
}
}
private fun findMemberIds(
chatIds: List<UUID>
): Map<UUID, List<UUID>> {
if (chatIds.isEmpty()) {
return emptyMap()
}
return ChatMemberModel
.selectAll()
.where(ChatMemberModel.chatId inList chatIds)
.orderBy(ChatMemberModel.position to SortOrder.ASC)
.groupBy(
keySelector = { it[ChatMemberModel.chatId].value },
valueTransform = { it[ChatMemberModel.userId].value }
)
}
private fun ResultRow.toChat(memberIds: List<UUID>) = Chat(
id = this[ChatModel.id].value,
title = this[ChatModel.title],
memberIds = memberIds,
createdAt = this[ChatModel.createdAt]
)
}
@@ -0,0 +1,81 @@
package com.mtusi.messenger.main.infrastructure.repositories.message
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.models.message.MessageModel
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.exposed.operations.RowGreater
import com.mtusi.messenger.main.utils.nowMicros
import org.jetbrains.exposed.v1.core.QueryParameter
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.SortOrder
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.dao.id.EntityID
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
@Single
class ExposedMessageRepository : MessageRepository {
override fun create(
chatId: UUID,
senderId: UUID,
text: String
): Message {
val insertedRow = MessageModel.insert {
it[this.chatId] = chatId
it[this.senderId] = senderId
it[this.text] = text
it[this.createdAt] = Clock.System.nowMicros()
}
return Message(
id = insertedRow[MessageModel.id].value,
chatId = chatId,
senderId = senderId,
text = text,
createdAt = insertedRow[MessageModel.createdAt]
)
}
override fun findPageByChatId(
chatId: UUID,
after: PageKey?,
limit: Int
): List<Message> {
var condition = MessageModel.chatId eq chatId
if (after != null) {
condition = condition and RowGreater(
left = listOf(MessageModel.createdAt, MessageModel.id),
right = listOf(
QueryParameter(after.createdAt, MessageModel.createdAt.columnType),
QueryParameter(EntityID(after.id, MessageModel), MessageModel.id.columnType)
)
)
}
return MessageModel
.selectAll()
.where(condition)
.orderBy(MessageModel.createdAt to SortOrder.ASC, MessageModel.id to SortOrder.ASC)
.limit(limit)
.map {
it.toMessage()
}
}
private fun ResultRow.toMessage() = Message(
id = this[MessageModel.id].value,
chatId = this[MessageModel.chatId].value,
senderId = this[MessageModel.senderId].value,
text = this[MessageModel.text],
createdAt = this[MessageModel.createdAt]
)
}
@@ -0,0 +1,22 @@
package com.mtusi.messenger.main.infrastructure.repositories.message
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import com.mtusi.messenger.main.utils.PageKey
import java.util.UUID
interface MessageRepository : Repository<UUID, Message> {
fun create(
chatId: UUID,
senderId: UUID,
text: String
): Message
fun findPageByChatId(
chatId: UUID,
after: PageKey?,
limit: Int
): List<Message>
}
@@ -0,0 +1,82 @@
package com.mtusi.messenger.main.infrastructure.repositories.user
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.dto.authentication.UserCredentials
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import com.mtusi.messenger.main.utils.nowMicros
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.inList
import org.jetbrains.exposed.v1.jdbc.insertIgnore
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
@Single
class ExposedUserRepository : UserRepository {
override fun create(
username: String,
displayName: String,
passwordHash: String
): User? {
val statement = UserModel.insertIgnore {
it[this.username] = username
it[this.displayName] = displayName
it[this.passwordHash] = passwordHash
it[this.createdAt] = Clock.System.nowMicros()
}
if (statement.insertedCount == 0) {
return null
}
return statement.resultedValues
?.singleOrNull()
?.toUser()
}
override fun findById(
id: UUID
): User? {
return UserModel
.selectAll()
.where(UserModel.id eq id)
.firstOrNull()
?.toUser()
}
override fun findCredentialsByUsername(
username: String
): UserCredentials? {
return UserModel
.selectAll()
.where(UserModel.username eq username)
.firstOrNull()
?.let {
UserCredentials(
user = it.toUser(),
passwordHash = it[UserModel.passwordHash]
)
}
}
override fun countByIds(
ids: Collection<UUID>
): Long {
return UserModel
.selectAll()
.where(UserModel.id inList ids)
.count()
}
private fun ResultRow.toUser() = User(
id = this[UserModel.id].value,
username = this[UserModel.username],
displayName = this[UserModel.displayName],
createdAt = this[UserModel.createdAt]
)
}
@@ -0,0 +1,28 @@
package com.mtusi.messenger.main.infrastructure.repositories.user
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.dto.authentication.UserCredentials
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import java.util.UUID
interface UserRepository : Repository<UUID, User> {
fun create(
username: String,
displayName: String,
passwordHash: String
): User?
fun findById(
id: UUID
): User?
fun findCredentialsByUsername(
username: String
): UserCredentials?
fun countByIds(
ids: Collection<UUID>
): Long
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.services
import org.koin.core.annotation.ComponentScan
import org.koin.core.annotation.Module
@Module
@ComponentScan
class ServicesModule
@@ -0,0 +1,34 @@
package com.mtusi.messenger.main.infrastructure.services.authentication
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 java.util.UUID
interface AuthenticationService {
fun validateCredentials(
username: String,
password: String
): User?
fun createSession(
userId: UUID
): IssuedSession
/**
* Opens its own transaction only on a cache miss, so it must not be called inside one.
*/
suspend fun findSessionByToken(
token: String
): Session?
/**
* 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
}
@@ -0,0 +1,311 @@
package com.mtusi.messenger.main.infrastructure.services.authentication
import com.mtusi.messenger.main.config.authentication.AuthenticationConfig
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.dto.authentication.SessionRevocation
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.authentication.session.revocation.SessionRevocationRepository
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 io.lettuce.core.RedisException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import org.koin.core.annotation.Single
import org.slf4j.LoggerFactory
import java.io.IOException
import java.security.SecureRandom
import java.util.Base64
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlin.time.Clock
import kotlin.time.Instant
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeSource
private const val TOKEN_BYTES = 32
private val CACHE_RESTORE_BACKOFF = 1.seconds
@Single
class DefaultAuthenticationService(
private val userRepository: UserRepository,
private val sessionRepository: SessionRepository,
private val sessionCacheRepository: SessionCacheRepository,
private val sessionRevocationRepository: SessionRevocationRepository,
private val hashingService: HashingService,
private val config: AuthenticationConfig
) : AuthenticationService {
private val logger = LoggerFactory.getLogger(DefaultAuthenticationService::class.java)
private val random = SecureRandom()
/**
* Database lookups currently running per token hash. Concurrent cache misses for one token wait for the
* lookup already in flight instead of each sending their own query (cache stampede protection).
*/
private val inFlightLookups = ConcurrentHashMap<String, CompletableDeferred<Session?>>()
/**
* Only availability changes are logged: with Redis down every request would otherwise add a warning.
*/
private val isCacheAvailable = AtomicBoolean(true)
/**
* Number of failed cache operations. A failure may have lost a logout tombstone, so the cache is trusted only
* after the pending revocations were written to it with no failure since: [trustedAtFailures] equals this counter.
* A fresh process starts untrusted, as the previous one may have stopped with revocations still pending.
*/
private val cacheFailures = AtomicLong()
@Volatile
private var trustedAtFailures = -1L
private val cacheRestoreMutex = Mutex()
@Volatile
private var nextCacheRestoreAttempt = TimeSource.Monotonic.markNow()
private val dummyPasswordHash by lazy {
hashingService.computeHash(HashingAlgorithm.Argon2id, "dummy-password-for-timing")
}
override fun validateCredentials(
username: String,
password: String
): User? {
val credentials = userRepository.findCredentialsByUsername(username)
val isPasswordValid = hashingService.validateHash(
algorithm = HashingAlgorithm.Argon2id,
input = password,
hashed = credentials?.passwordHash ?: dummyPasswordHash
)
if (credentials == null || !isPasswordValid) {
return null
}
return credentials.user
}
override fun createSession(
userId: UUID
): IssuedSession {
val token = ByteArray(TOKEN_BYTES)
.also(random::nextBytes)
.let(Base64.getUrlEncoder().withoutPadding()::encodeToString)
val session = sessionRepository.create(
userId = userId,
tokenHash = token.toByteArray().computeSha256(),
ttl = config.sessionTtlSeconds.seconds
)
return IssuedSession(
session = session,
token = token
)
}
override suspend fun findSessionByToken(
token: String
): Session? {
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
}
if (!config.sessionCacheSingleFlight) {
return selectSession(tokenHash, now)?.also { cacheSession(it, now) }
}
val flight = CompletableDeferred<Session?>()
inFlightLookups.putIfAbsent(tokenHash, flight)?.let { leader ->
return leader.await()
}
try {
// The query is shared with the followers, so the leader's own cancellation must not abort it.
val session = withContext(NonCancellable) {
selectSession(tokenHash, now)
}
flight.complete(session)
// Requests arriving until the cache write lands reuse this result instead of starting a new lookup.
// A logout drops the flight first (see revokeSession), so a revoked session is never handed out here.
session?.let { cacheSession(it, now) }
return session
} catch (e: Throwable) {
flight.completeExceptionally(e)
throw e
} finally {
inFlightLookups.remove(tokenHash, flight)
}
}
private suspend fun selectSession(
tokenHash: String,
now: Instant
): Session? {
return suspendedTransaction {
sessionRepository.findActiveByTokenHash(tokenHash, now)
}
}
override suspend fun revokeSession(
session: Session
): Boolean {
// The revocation is kept in PostgreSQL until its tombstone is in Redis: if Redis is unavailable now,
// the tombstone is written when the cache is trusted again (see restoreCache), even after a restart.
val isDeleted = suspendedTransaction {
sessionRevocationRepository.add(SessionRevocation(session.tokenHash, session.expiresAt))
sessionRepository.deleteById(session.id)
}
// A lookup that started before the delete must not be joined by requests arriving after the logout.
inFlightLookups.remove(session.tokenHash)
if (withCache { sessionCacheRepository.revoke(session.tokenHash, session.expiresAt) } != null) {
// Best effort: a leftover row only costs one more tombstone write on the next restore.
runCatchingDatabase { sessionRevocationRepository.delete(session.tokenHash) }
}
return isDeleted
}
private suspend fun findCachedSession(
tokenHash: String
): CachedSession? {
if (trustedAtFailures != cacheFailures.get() && !restoreCache()) {
return null
}
return withCache { sessionCacheRepository.find(tokenHash) }
}
/**
* Writes the tombstones of logouts that happened while Redis was unavailable. Until that succeeds the cache
* is bypassed: a copy cached before the outage could otherwise outlive the logout. One request restores,
* the others go to the database meanwhile; a failed attempt is repeated after [CACHE_RESTORE_BACKOFF].
*/
private suspend fun restoreCache(): Boolean {
if (!cacheRestoreMutex.tryLock()) {
return false
}
try {
val failures = cacheFailures.get()
if (trustedAtFailures == failures) {
return true
}
if (nextCacheRestoreAttempt.hasNotPassedNow()) {
return false
}
nextCacheRestoreAttempt = TimeSource.Monotonic.markNow() + CACHE_RESTORE_BACKOFF
val now = Clock.System.now()
val pending = runCatchingDatabase {
sessionRevocationRepository.deleteExpired(now)
sessionRevocationRepository.findPending(now)
} ?: return false
for (revocation in pending) {
withCache { sessionCacheRepository.revoke(revocation.tokenHash, revocation.expiresAt) } ?: return false
}
if (pending.isNotEmpty()) {
runCatchingDatabase { pending.forEach { sessionRevocationRepository.delete(it.tokenHash) } }
logger.info("Wrote ${pending.size} pending session revocations to the cache")
}
// A failure while restoring changed the counter, so the cache stays untrusted.
trustedAtFailures = failures
return trustedAtFailures == cacheFailures.get()
} finally {
cacheRestoreMutex.unlock()
}
}
private suspend fun <T> runCatchingDatabase(
statement: () -> T
): T? {
return try {
suspendedTransaction { statement() }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logger.warn("Unable to update pending session revocations: ${e.message}")
null
}
}
private suspend fun cacheSession(
session: Session,
now: Instant
) {
withCache {
sessionCacheRepository.putIfAbsent(
session = session,
cachedUntil = minOf(session.expiresAt, now + config.sessionCacheTtlSeconds.seconds)
)
}
}
/**
* Runs a cache operation, treating an unavailable Redis as a miss: the database stays the source of truth.
* A command already written when Redis drops the connection fails with the raw [IOException] (connection
* reset), not with a [RedisException]; it means the same.
*/
private suspend fun <T> withCache(
operation: suspend () -> T
): T? {
return try {
operation().also {
if (isCacheAvailable.compareAndSet(false, true)) {
logger.info("Session cache is available again")
}
}
} catch (e: RedisException) {
onCacheUnavailable(e)
} catch (e: IOException) {
onCacheUnavailable(e)
}
}
private fun onCacheUnavailable(
cause: Exception
): Nothing? {
cacheFailures.incrementAndGet()
if (isCacheAvailable.compareAndSet(true, false)) {
logger.warn("Session cache is unavailable, sessions are read from the database: ${cause.message}")
}
return null
}
}
@@ -0,0 +1,27 @@
package com.mtusi.messenger.main.infrastructure.services.chat
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatCreationResult
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult
import java.util.UUID
interface ChatService {
fun create(
creatorId: UUID,
title: String,
memberIds: List<UUID>
): ChatCreationResult
fun findAccessible(
userId: UUID,
chatId: UUID
): Chat?
fun findPageAccessible(
userId: UUID,
limit: Int,
cursor: String?
): ChatPageResult
}
@@ -0,0 +1,79 @@
package com.mtusi.messenger.main.infrastructure.services.chat
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository
import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatCreationResult
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.decodeCursor
import com.mtusi.messenger.main.utils.toPage
import org.koin.core.annotation.Single
import java.util.UUID
@Single
class DefaultChatService(
private val chatRepository: ChatRepository,
private val userRepository: UserRepository
) : ChatService {
override fun create(
creatorId: UUID,
title: String,
memberIds: List<UUID>
): ChatCreationResult {
if (memberIds.toSet().size != memberIds.size) {
return ChatCreationResult.DuplicateMembers
}
if (creatorId !in memberIds) {
return ChatCreationResult.CreatorNotMember
}
if (userRepository.countByIds(memberIds) != memberIds.size.toLong()) {
return ChatCreationResult.UnknownMembers
}
val chat = chatRepository.create(
title = title,
memberIds = memberIds
)
return ChatCreationResult.Success(chat)
}
override fun findAccessible(
userId: UUID,
chatId: UUID
): Chat? {
return chatRepository.findById(chatId)
?.takeIf { userId in it.memberIds }
}
override fun findPageAccessible(
userId: UUID,
limit: Int,
cursor: String?
): ChatPageResult {
val scope = "chats:$userId"
val after = cursor?.let {
decodeCursor(it, scope) ?: return ChatPageResult.InvalidCursor
}
val page = chatRepository
.findPageByMemberId(
userId = userId,
after = after,
limit = limit + 1
)
.toPage(limit, scope) {
PageKey(it.createdAt, it.id)
}
return ChatPageResult.Success(page)
}
}
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.services.chat.results
import com.mtusi.messenger.main.infrastructure.dto.Chat
sealed class ChatCreationResult {
sealed class Error : ChatCreationResult()
data object DuplicateMembers : Error()
data object CreatorNotMember : Error()
data object UnknownMembers : Error()
data class Success(
val chat: Chat
) : ChatCreationResult()
}
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.infrastructure.services.chat.results
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.dto.PageResponse
sealed class ChatPageResult {
sealed class Error : ChatPageResult()
data object InvalidCursor : Error()
data class Success(
val page: PageResponse<Chat>
) : ChatPageResult()
}
@@ -0,0 +1,123 @@
package com.mtusi.messenger.main.infrastructure.services.hashing
import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm
import org.bouncycastle.crypto.generators.Argon2BytesGenerator
import org.bouncycastle.crypto.params.Argon2Parameters
import org.koin.core.annotation.Single
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
// TODO: Move to config later
private const val ARGON2_MEMORY_KIB = 19 * 1024
private const val ARGON2_ITERATIONS = 2
private const val ARGON2_PARALLELISM = 1
private const val ARGON2_SALT_LENGTH = 16
private const val ARGON2_HASH_LENGTH = 32
@Single
class DefaultHashingService : HashingService {
private val random = SecureRandom()
private val encoder = Base64.getEncoder().withoutPadding()
private val decoder = Base64.getDecoder()
override fun computeHash(
algorithm: HashingAlgorithm,
input: String
): String {
return when (algorithm) {
HashingAlgorithm.Argon2id -> computeHashArgon2id(input)
}
}
private fun computeHashArgon2id(input: String): String {
val salt = ByteArray(ARGON2_SALT_LENGTH).also(random::nextBytes)
val hash = argon2id(
input = input,
salt = salt,
memoryKib = ARGON2_MEMORY_KIB,
iterations = ARGON2_ITERATIONS,
parallelism = ARGON2_PARALLELISM,
length = ARGON2_HASH_LENGTH
)
return "\$argon2id\$v=19\$m=$ARGON2_MEMORY_KIB,t=$ARGON2_ITERATIONS,p=$ARGON2_PARALLELISM" +
"\$${encoder.encodeToString(salt)}\$${encoder.encodeToString(hash)}"
}
override fun validateHash(
algorithm: HashingAlgorithm,
input: String,
hashed: String
): Boolean {
return when (algorithm) {
HashingAlgorithm.Argon2id -> validateHashArgon2id(input, hashed)
}
}
private fun validateHashArgon2id(
input: String,
hashed: String
): Boolean {
return try {
val parts = hashed.split('$')
if (parts.size != 6 || parts[1] != "argon2id" || parts[2] != "v=19") {
return false
}
val parameters = parts[3]
.split(',')
.associate {
val (key, value) = it.split('=')
key to value.toInt()
}
val salt = decoder.decode(parts[4])
val expected = decoder.decode(parts[5])
val actual = argon2id(
input = input,
salt = salt,
memoryKib = parameters.getValue("m"),
iterations = parameters.getValue("t"),
parallelism = parameters.getValue("p"),
length = expected.size
)
MessageDigest.isEqual(expected, actual)
} catch (_: Exception) {
false
}
}
private fun argon2id(
input: String,
salt: ByteArray,
memoryKib: Int,
iterations: Int,
parallelism: Int,
length: Int
): ByteArray {
val parameters = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withMemoryAsKB(memoryKib)
.withIterations(iterations)
.withParallelism(parallelism)
.withSalt(salt)
.build()
val generator = Argon2BytesGenerator().apply {
init(parameters)
}
return ByteArray(length).also {
generator.generateBytes(input.toByteArray(Charsets.UTF_8), it)
}
}
}
@@ -0,0 +1,18 @@
package com.mtusi.messenger.main.infrastructure.services.hashing
import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm
interface HashingService {
fun computeHash(
algorithm: HashingAlgorithm,
input: String
): String
fun validateHash(
algorithm: HashingAlgorithm,
input: String,
hashed: String
): Boolean
}
@@ -0,0 +1,5 @@
package com.mtusi.messenger.main.infrastructure.services.hashing.types
sealed class HashingAlgorithm {
data object Argon2id : HashingAlgorithm()
}
@@ -0,0 +1,68 @@
package com.mtusi.messenger.main.infrastructure.services.message
import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository
import com.mtusi.messenger.main.infrastructure.repositories.message.MessageRepository
import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult
import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.decodeCursor
import com.mtusi.messenger.main.utils.toPage
import org.koin.core.annotation.Single
import java.util.UUID
@Single
class DefaultMessageService(
private val chatRepository: ChatRepository,
private val messageRepository: MessageRepository
) : MessageService {
override fun send(
chatId: UUID,
senderId: UUID,
text: String
): MessageCreationResult {
if (!chatRepository.isMember(chatId, senderId)) {
return MessageCreationResult.ChatNotFound
}
val message = messageRepository.create(
chatId = chatId,
senderId = senderId,
text = text
)
return MessageCreationResult.Success(message)
}
override fun findPageByChatId(
chatId: UUID,
actorId: UUID,
limit: Int,
cursor: String?
): MessagePageResult {
if (!chatRepository.isMember(chatId, actorId)) {
return MessagePageResult.ChatNotFound
}
val scope = "messages:$chatId"
val after = cursor?.let {
decodeCursor(it, scope) ?: return MessagePageResult.InvalidCursor
}
val page = messageRepository
.findPageByChatId(
chatId = chatId,
after = after,
limit = limit + 1
)
.toPage(limit, scope) {
PageKey(it.createdAt, it.id)
}
return MessagePageResult.Success(page)
}
}
@@ -0,0 +1,22 @@
package com.mtusi.messenger.main.infrastructure.services.message
import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult
import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult
import java.util.UUID
interface MessageService {
fun send(
chatId: UUID,
senderId: UUID,
text: String
): MessageCreationResult
fun findPageByChatId(
chatId: UUID,
actorId: UUID,
limit: Int,
cursor: String?
): MessagePageResult
}
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.infrastructure.services.message.results
import com.mtusi.messenger.main.infrastructure.dto.Message
sealed class MessageCreationResult {
sealed class Error : MessageCreationResult()
data object ChatNotFound : Error()
data class Success(
val message: Message
) : MessageCreationResult()
}
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.services.message.results
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.dto.PageResponse
sealed class MessagePageResult {
sealed class Error : MessagePageResult()
data object ChatNotFound : Error()
data object InvalidCursor : Error()
data class Success(
val page: PageResponse<Message>
) : MessagePageResult()
}
@@ -0,0 +1,43 @@
package com.mtusi.messenger.main.infrastructure.services.user
import com.mtusi.messenger.main.infrastructure.dto.User
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.infrastructure.services.user.results.UserCreationResult
import org.koin.core.annotation.Single
import java.util.UUID
@Single
class DefaultUserService(
private val userRepository: UserRepository,
private val hashingService: HashingService
) : UserService {
override fun create(
username: String,
displayName: String,
password: String
): UserCreationResult {
val passwordHash = hashingService.computeHash(
algorithm = HashingAlgorithm.Argon2id,
input = password
)
val user = userRepository.create(
username = username,
displayName = displayName,
passwordHash = passwordHash
) ?: return UserCreationResult.UsernameTaken
return UserCreationResult.Success(user)
}
override fun findById(
id: UUID
): User? {
return userRepository.findById(id)
}
}
@@ -0,0 +1,19 @@
package com.mtusi.messenger.main.infrastructure.services.user
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.services.user.results.UserCreationResult
import java.util.UUID
interface UserService {
fun create(
username: String,
displayName: String,
password: String
): UserCreationResult
fun findById(
id: UUID
): User?
}
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.infrastructure.services.user.results
import com.mtusi.messenger.main.infrastructure.dto.User
sealed class UserCreationResult {
sealed class Error : UserCreationResult()
data object UsernameTaken : Error()
data class Success(
val user: User
) : UserCreationResult()
}
@@ -0,0 +1,3 @@
package com.mtusi.messenger.main.infrastructure.types
class ApiException(val code: ErrorCode, message: String) : RuntimeException(message)
@@ -0,0 +1,6 @@
package com.mtusi.messenger.main.infrastructure.types
object AuthChallenge {
const val BASIC = "Basic realm=\"messenger\", charset=\"UTF-8\""
const val BEARER = "Bearer realm=\"messenger\""
}
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.infrastructure.types
import io.ktor.http.HttpStatusCode
enum class ErrorCode(val wire: String, val status: HttpStatusCode) {
INVALID_REQUEST("invalid_request", HttpStatusCode.BadRequest),
UNAUTHORIZED("unauthorized", HttpStatusCode.Unauthorized),
NOT_FOUND("not_found", HttpStatusCode.NotFound),
CONFLICT("conflict", HttpStatusCode.Conflict),
PAYLOAD_TOO_LARGE("payload_too_large", HttpStatusCode.PayloadTooLarge),
UNSUPPORTED_MEDIA_TYPE("unsupported_media_type", HttpStatusCode.UnsupportedMediaType),
RATE_LIMITED("rate_limited", HttpStatusCode.TooManyRequests),
UNAVAILABLE("unavailable", HttpStatusCode.ServiceUnavailable),
INTERNAL_ERROR("internal_error", HttpStatusCode.InternalServerError),
}
@@ -0,0 +1,14 @@
package com.mtusi.messenger.main.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.calllogging.CallLogging
import org.slf4j.event.Level
fun Application.configureCallLogging() = install(CallLogging) {
level = Level.INFO
filter { call ->
val uri = call.request.local.uri
uri.startsWith("/api") || uri.startsWith("/health")
}
}
@@ -0,0 +1,21 @@
package com.mtusi.messenger.main.plugins
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNamingStrategy
@OptIn(ExperimentalSerializationApi::class)
val json = Json {
ignoreUnknownKeys = false
explicitNulls = true
encodeDefaults = true
namingStrategy = JsonNamingStrategy.SnakeCase
}
fun Application.configureContentNegotiation() = install(ContentNegotiation) {
json(json)
}
@@ -0,0 +1,149 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.config.database.DatabaseConfig
import com.mtusi.messenger.main.config.database.SerialDatabaseConfig
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionModel
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionRevocationModel
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
import io.ktor.server.application.Application
import io.ktor.server.application.ApplicationStopped
import io.ktor.server.config.HoconApplicationConfig
import io.ktor.server.config.getAs
import kotlinx.coroutines.Dispatchers
import org.flywaydb.core.Flyway
import org.jetbrains.exposed.v1.core.ExperimentalDatabaseMigrationApi
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.core.DatabaseConfig as ExposedDatabaseConfig
import org.jetbrains.exposed.v1.jdbc.Database
import org.jetbrains.exposed.v1.jdbc.JdbcTransaction
import org.jetbrains.exposed.v1.jdbc.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
import org.jetbrains.exposed.v1.migration.jdbc.MigrationUtils
import org.koin.ktor.ext.inject
import java.io.File
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() {
val config by inject<DatabaseConfig>()
val dataSource = config.createDataSource()
Database.connect(
datasource = dataSource,
databaseConfig = ExposedDatabaseConfig {
defaultMaxAttempts = 1
}
)
applyDatabaseMigrations(dataSource)
monitor.subscribe(ApplicationStopped) {
dataSource.close()
}
}
private fun DatabaseConfig.createDataSource(): HikariDataSource {
return HikariDataSource(
HikariConfig().apply {
poolName = "messenger"
jdbcUrl = jdbcConnectionUrl
username = this@createDataSource.username
password = resolveSecret(this@createDataSource.password, passwordFile).orEmpty()
maximumPoolSize = maxPoolSize
connectionTimeout = connectionTimeoutMs
validationTimeout = minOf(VALIDATION_TIMEOUT_MS, connectionTimeoutMs - 1)
addDataSourceProperty("options", "-c statement_timeout=$statementTimeoutMs")
}
)
}
fun applyDatabaseMigrations(
dataSource: DataSource
) {
val flyway = Flyway.configure()
.dataSource(dataSource)
.locations("classpath:migrations")
.load()
flyway.migrate()
flyway.validate()
}
fun main(args: Array<out String>) {
generateMigration(args.joinToString("_"))
}
@OptIn(ExperimentalDatabaseMigrationApi::class)
private fun generateMigration(description: String) {
require(description.isNotEmpty()) { "Description cannot be empty" }
val tables: Array<Table> = arrayOf(
UserModel,
ChatModel,
ChatMemberModel,
MessageModel,
SessionModel,
SessionRevocationModel
)
val config = HoconApplicationConfig(ConfigFactory.parseFile(File(DEVELOPMENT_DATABASE_CONFIG)).resolve())
.property("database")
.getAs<SerialDatabaseConfig>()
config.createDataSource().use { dataSource ->
Database.connect(dataSource)
applyDatabaseMigrations(dataSource)
val migrations = File(MIGRATIONS_DIRECTORY).listFiles { it.extension == "sql" }.orEmpty()
val latestVersion = migrations.maxOfOrNull {
it.name
.substringBefore("__")
.drop(1)
.toInt()
}
val version = latestVersion?.inc() ?: 1
transaction {
val statements = MigrationUtils.statementsRequiredForDatabaseMigration(*tables)
if (statements.isEmpty()) {
println("Database schema is up to date, no migration generated")
return@transaction
}
val script = MigrationUtils.generateMigrationScript(
tables = tables,
scriptDirectory = MIGRATIONS_DIRECTORY,
scriptName = "V${version}__$description"
)
println("Generated migration ${script.path}")
}
}
}
suspend fun <R> suspendedTransaction(statement: JdbcTransaction.() -> R) = newSuspendedTransaction(
context = Dispatchers.IO,
statement = statement
)
@@ -0,0 +1,7 @@
package com.mtusi.messenger.main.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.defaultheaders.DefaultHeaders
fun Application.configureDefaultHeaders() = install(DefaultHeaders)
@@ -0,0 +1,27 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.config.ConfigModule
import com.mtusi.messenger.main.infrastructure.repositories.RepositoriesModule
import com.mtusi.messenger.main.infrastructure.services.ServicesModule
import io.ktor.server.application.Application
import io.ktor.server.application.install
import org.koin.dsl.module
import org.koin.ksp.generated.module
import org.koin.ktor.plugin.Koin
fun Application.configureKoin() {
val applicationModule = module {
single { this@configureKoin }
}
install(Koin) {
modules(
applicationModule,
ConfigModule().module,
RepositoriesModule().module,
ServicesModule().module
)
}
}
@@ -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()
}
}
@@ -0,0 +1,20 @@
package com.mtusi.messenger.main.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.createApplicationPlugin
import io.ktor.server.application.install
import io.ktor.util.AttributeKey
import java.util.UUID
val RequestIdKey: AttributeKey<String> = AttributeKey("X-Request-Id")
private val RequestIdPlugin = createApplicationPlugin("RequestId") {
onCall { call ->
val incoming = call.request.headers["X-Request-Id"]?.takeIf { it.isNotBlank() }
val id = incoming ?: UUID.randomUUID().toString()
call.attributes.put(RequestIdKey, id)
call.response.headers.append("X-Request-Id", id, safeOnly = false)
}
}
fun Application.configureRequestId() = install(RequestIdPlugin)
@@ -0,0 +1,18 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.infrastructure.controllers.authentication.configureAuthenticationRouting
import com.mtusi.messenger.main.infrastructure.controllers.chat.configureChatRouting
import com.mtusi.messenger.main.infrastructure.controllers.health.configureHealthRouting
import com.mtusi.messenger.main.infrastructure.controllers.message.configureMessageRouting
import com.mtusi.messenger.main.infrastructure.controllers.user.configureUserRouting
import io.ktor.server.application.Application
import io.ktor.server.routing.routing
fun Application.configureRouting() = routing {
configureSwaggerRouting()
configureHealthRouting()
configureUserRouting()
configureAuthenticationRouting()
configureChatRouting()
configureMessageRouting()
}
@@ -0,0 +1,78 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import io.ktor.http.HttpStatusCode
import io.ktor.serialization.JsonConvertException
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.application.log
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)
}
exception<JsonConvertException> { call, _ ->
call.respondError(ErrorCode.INVALID_REQUEST, "invalid JSON body")
}
exception<SerializationException> { call, _ ->
call.respondError(ErrorCode.INVALID_REQUEST, "invalid JSON body")
}
exception<BadRequestException> { call, _ ->
call.respondError(ErrorCode.INVALID_REQUEST, "invalid request")
}
exception<NotFoundException> { call, _ ->
call.respondError(ErrorCode.NOT_FOUND, "not found")
}
exception<UnsupportedMediaTypeException> { call, _ ->
call.respondError(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "unsupported media type")
}
exception<SQLException> { call, cause ->
if (cause.isConnectionFailure()) {
call.application.log.warn("Database unavailable: ${cause.message}")
call.respondError(ErrorCode.UNAVAILABLE, "service temporarily unavailable")
} else {
call.application.log.error("Database error", cause)
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")
}
status(HttpStatusCode.NotFound) { call, _ ->
call.respondError(ErrorCode.NOT_FOUND, "not found")
}
status(HttpStatusCode.MethodNotAllowed) { call, _ ->
call.respondError(ErrorCode.NOT_FOUND, "not found")
}
}
private fun SQLException.isConnectionFailure(): Boolean {
return generateSequence<Throwable>(this) { it.cause }.any {
it is SQLTransientConnectionException ||
(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))
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.plugins
import io.ktor.server.plugins.swagger.swaggerUI
import io.ktor.server.routing.Routing
fun Routing.configureSwaggerRouting() {
swaggerUI(path = "docs", swaggerFile = "openapi.json")
}
@@ -0,0 +1,43 @@
package com.mtusi.messenger.main.plugins.authentication
import com.mtusi.messenger.main.infrastructure.services.authentication.AuthenticationService
import com.mtusi.messenger.main.plugins.authentication.providers.basicCredentials
import com.mtusi.messenger.main.plugins.authentication.providers.bearerSession
import com.mtusi.messenger.main.plugins.suspendedTransaction
import io.ktor.server.application.Application
import io.ktor.server.auth.authentication
import org.koin.ktor.ext.inject
const val CREDENTIALS_AUTH = "credentials"
const val SESSION_AUTH = "session"
fun Application.configureAuthentication() {
val authenticationService by inject<AuthenticationService>()
authentication {
basicCredentials(CREDENTIALS_AUTH) {
validate { credential ->
val user = suspendedTransaction {
authenticationService.validateCredentials(
username = credential.name,
password = credential.password
)
} ?: return@validate null
return@validate CredentialsPrincipal(user)
}
}
bearerSession(SESSION_AUTH) {
authenticate { token ->
val session = authenticationService.findSessionByToken(token) ?: return@authenticate null
return@authenticate UserPrincipal(session)
}
}
}
}
@@ -0,0 +1,7 @@
package com.mtusi.messenger.main.plugins.authentication
import com.mtusi.messenger.main.infrastructure.dto.User
data class CredentialsPrincipal(
val user: User
)
@@ -0,0 +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 session: Session
) {
val id: UUID
get() = session.userId
}
@@ -0,0 +1,66 @@
package com.mtusi.messenger.main.plugins.authentication.providers
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.types.AuthChallenge
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import io.ktor.server.application.ApplicationCall
import io.ktor.server.auth.AuthenticationConfig
import io.ktor.server.auth.AuthenticationContext
import io.ktor.server.auth.AuthenticationFailedCause
import io.ktor.server.auth.AuthenticationProvider
import io.ktor.server.auth.UserPasswordCredential
import io.ktor.server.auth.basicAuthenticationCredentials
import io.ktor.server.plugins.BadRequestException
private const val CHALLENGE_KEY = "BasicCredentials"
class BasicCredentialsProvider(config: Config) : AuthenticationProvider(config) {
private val validate = config.validate
override suspend fun onAuthenticate(context: AuthenticationContext) {
val credential = try {
context.call.request.basicAuthenticationCredentials(Charsets.UTF_8)
} catch (_: BadRequestException) {
null
}
val principal = credential?.let { validate(context.call, it) }
if (principal == null) {
val cause = if (credential == null) {
AuthenticationFailedCause.NoCredentials
} else {
AuthenticationFailedCause.InvalidCredentials
}
context.challenge(CHALLENGE_KEY, cause) { challenge, call ->
call.respondError(ErrorCode.UNAUTHORIZED, "invalid credentials", AuthChallenge.BASIC)
challenge.complete()
}
return
}
context.principal(principal)
}
class Config(name: String?) : AuthenticationProvider.Config(name) {
internal var validate: suspend ApplicationCall.(UserPasswordCredential) -> Any? = { null }
fun validate(body: suspend ApplicationCall.(UserPasswordCredential) -> Any?) {
validate = body
}
}
}
fun AuthenticationConfig.basicCredentials(
name: String,
configure: BasicCredentialsProvider.Config.() -> Unit
) {
register(BasicCredentialsProvider(BasicCredentialsProvider.Config(name).apply(configure)))
}
@@ -0,0 +1,71 @@
package com.mtusi.messenger.main.plugins.authentication.providers
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.types.AuthChallenge
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import io.ktor.http.auth.HttpAuthHeader
import io.ktor.server.application.ApplicationCall
import io.ktor.server.auth.AuthenticationConfig
import io.ktor.server.auth.AuthenticationContext
import io.ktor.server.auth.AuthenticationFailedCause
import io.ktor.server.auth.AuthenticationProvider
import io.ktor.server.auth.parseAuthorizationHeader
import io.ktor.server.plugins.BadRequestException
private const val CHALLENGE_KEY = "BearerSession"
private const val BEARER_SCHEME = "Bearer"
class BearerSessionProvider(config: Config) : AuthenticationProvider(config) {
private val authenticate = config.authenticate
override suspend fun onAuthenticate(context: AuthenticationContext) {
val header = try {
context.call.request.parseAuthorizationHeader()
} catch (_: BadRequestException) {
null
}
val token = (header as? HttpAuthHeader.Single)
?.takeIf { it.authScheme.equals(BEARER_SCHEME, ignoreCase = true) }
?.blob
val principal = token?.let { authenticate(context.call, it) }
if (principal == null) {
val cause = if (token == null) {
AuthenticationFailedCause.NoCredentials
} else {
AuthenticationFailedCause.InvalidCredentials
}
context.challenge(CHALLENGE_KEY, cause) { challenge, call ->
call.respondError(ErrorCode.UNAUTHORIZED, "authentication required", AuthChallenge.BEARER)
challenge.complete()
}
return
}
context.principal(principal)
}
class Config(name: String?) : AuthenticationProvider.Config(name) {
internal var authenticate: suspend ApplicationCall.(String) -> Any? = { null }
fun authenticate(body: suspend ApplicationCall.(String) -> Any?) {
authenticate = body
}
}
}
fun AuthenticationConfig.bearerSession(
name: String,
configure: BearerSessionProvider.Config.() -> Unit
) {
register(BearerSessionProvider(BearerSessionProvider.Config(name).apply(configure)))
}
@@ -0,0 +1,10 @@
package com.mtusi.messenger.main.utils
import java.security.MessageDigest
@OptIn(ExperimentalStdlibApi::class)
fun ByteArray.computeSha256(): String {
return MessageDigest.getInstance("SHA-256")
.digest(this)
.toHexString()
}
@@ -0,0 +1,64 @@
package com.mtusi.messenger.main.utils
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import com.mtusi.messenger.main.infrastructure.dto.PageResponse
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.util.Base64
import java.util.UUID
import kotlin.time.Instant
private val json = Json { ignoreUnknownKeys = false }
/**
* Position in a `(created_at, id)` ordered list: the next page starts strictly after it.
*/
data class PageKey(
val createdAt: Instant,
val id: UUID,
)
@Serializable
private data class Cursor(
val scope: String,
val createdAt: Instant,
val id: SerialUUID,
)
fun encodeCursor(scope: String, key: PageKey): String {
val raw = json.encodeToString(Cursor.serializer(), Cursor(scope, key.createdAt, key.id))
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.toByteArray(Charsets.UTF_8))
}
/**
* @return page key, or null if the cursor is malformed or was issued for another resource
*/
fun decodeCursor(raw: String, expectedScope: String): PageKey? {
val cursor = try {
val bytes = Base64.getUrlDecoder().decode(raw)
json.decodeFromString(Cursor.serializer(), String(bytes, Charsets.UTF_8))
} catch (_: Exception) {
return null
}
if (cursor.scope != expectedScope) {
return null
}
return PageKey(cursor.createdAt, cursor.id)
}
/**
* Builds a page from `limit + 1` rows fetched after the cursor: the extra row only signals that more data exists.
*/
fun <T : Any> List<T>.toPage(
limit: Int,
scope: String,
key: (T) -> PageKey,
): PageResponse<T> {
val items = take(limit)
val nextCursor = if (size > limit) encodeCursor(scope, key(items.last())) else null
return PageResponse(items, nextCursor)
}
@@ -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() }
}
@@ -0,0 +1,18 @@
package com.mtusi.messenger.main.utils
import kotlin.time.Clock
import kotlin.time.Instant
private const val NANOS_PER_MICRO = 1_000
/**
* Current time truncated to microseconds: PostgreSQL timestamptz keeps exactly this precision,
* so the value returned to the client equals the one read back from the database.
*/
fun Clock.nowMicros(): Instant {
val now = now()
return Instant.fromEpochSeconds(
epochSeconds = now.epochSeconds,
nanosecondAdjustment = now.nanosecondsOfSecond / NANOS_PER_MICRO * NANOS_PER_MICRO
)
}
@@ -0,0 +1,36 @@
package com.mtusi.messenger.main.utils
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import java.util.UUID
private val USERNAME = Regex("^[a-z0-9_]{3,32}$")
private val UUID_REGEX = Regex(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
)
fun codePoints(value: String): Int = value.codePointCount(0, value.length)
fun requireUsername(value: String) {
if (!USERNAME.matches(value)) {
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid username")
}
}
fun requireNonBlankBounded(value: String, min: Int, max: Int, field: String) {
if (value.isBlank()) {
throw ApiException(ErrorCode.INVALID_REQUEST, "$field must not be blank")
}
val n = codePoints(value)
if (n !in min..max) {
throw ApiException(ErrorCode.INVALID_REQUEST, "$field length out of range")
}
}
fun requireUuid(value: String?, field: String): UUID {
if (value == null || !UUID_REGEX.matches(value)) {
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid $field")
}
return UUID.fromString(value)
}
@@ -0,0 +1,32 @@
package com.mtusi.messenger.main.utils.exposed.operations
import org.jetbrains.exposed.v1.core.Expression
import org.jetbrains.exposed.v1.core.Op
import org.jetbrains.exposed.v1.core.QueryBuilder
class RowGreater(
private val left: List<Expression<*>>,
private val right: List<Expression<*>>
) : Op<Boolean>() {
init {
require(left.size == right.size) { "Rows must have the same arity" }
}
override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder {
appendRow(left)
append(" > ")
appendRow(right)
}
private fun QueryBuilder.appendRow(expressions: List<Expression<*>>) {
append("(")
expressions.forEachIndexed { index, expression ->
if (index > 0) {
append(", ")
}
append(expression)
}
append(")")
}
}
+52
View File
@@ -0,0 +1,52 @@
ktor {
application {
modules = [com.mtusi.messenger.main.AppKt.module]
}
deployment {
host = "0.0.0.0"
host = ${?APP_HOST}
port = 8080
port = ${?APP_PORT}
shutdownGracePeriod = 3000
shutdownTimeout = 10000
}
}
database {
host = "localhost"
host = ${?DB_HOST}
port = 5432
port = ${?DB_PORT}
name = "messenger"
name = ${?DB_NAME}
username = "messenger"
username = ${?DB_USER}
password = ${?DB_PASSWORD}
passwordFile = ${?DB_PASSWORD_FILE}
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
# Collapse concurrent cache misses for one token into a single database lookup (track 1 compares on/off).
sessionCacheSingleFlight = true
sessionCacheSingleFlight = ${?SESSION_CACHE_SINGLE_FLIGHT}
}
+12
View File
@@ -0,0 +1,12 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5level [%thread] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
<logger name="io.netty" level="WARN"/>
<logger name="org.eclipse.jetty" level="WARN"/>
</configuration>
@@ -0,0 +1,50 @@
-- Users, chats, membership, messages and sessions. PostgreSQL is the source of truth.
-- Timestamps are timestamptz: an absolute instant, independent of server/JVM time zone.
CREATE TABLE users (
id uuid PRIMARY KEY,
username varchar(32) NOT NULL,
display_name varchar(100) NOT NULL,
password_hash varchar(255) NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$')
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title varchar(100) NOT NULL,
created_at timestamptz NOT NULL
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
position integer NOT NULL,
PRIMARY KEY (chat_id, user_id)
);
-- "Chats of a user": the PK leads with chat_id, so the reverse lookup needs its own index.
CREATE INDEX chat_members_user_id_idx ON chat_members (user_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
text varchar(4000) NOT NULL,
created_at timestamptz NOT NULL
);
-- Keyset pagination of a chat history: WHERE chat_id = ? AND (created_at, id) > (?, ?) ORDER BY created_at, id.
CREATE INDEX messages_chat_id_created_at_id_idx ON messages (chat_id, created_at, id);
CREATE TABLE sessions (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
token_hash varchar(64) NOT NULL,
created_at timestamptz NOT NULL,
expires_at timestamptz NOT NULL,
CONSTRAINT sessions_token_hash_key UNIQUE (token_hash)
);
CREATE INDEX sessions_user_id_idx ON sessions (user_id);
@@ -0,0 +1,6 @@
-- Logouts whose tombstone has not reached Redis yet. Written in the same transaction as the session delete and
-- removed once the tombstone is stored, so a copy cached before an outage cannot outlive the logout.
CREATE TABLE session_revocations (
token_hash varchar(64) PRIMARY KEY,
expires_at timestamptz NOT NULL
);
@@ -0,0 +1,151 @@
package com.mtusi.messenger.main.infrastructure.controllers.authentication
import com.mtusi.messenger.main.extensions.ErrorBody
import com.mtusi.messenger.main.infrastructure.controllers.authentication.responses.SessionResponse
import com.mtusi.messenger.main.support.TEST_PASSWORD
import com.mtusi.messenger.main.support.auth
import com.mtusi.messenger.main.support.createUser
import com.mtusi.messenger.main.support.register
import com.mtusi.messenger.main.support.runApp
import io.ktor.client.call.body
import io.ktor.client.request.basicAuth
import io.ktor.client.request.bearerAuth
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.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import kotlinx.coroutines.delay
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
import kotlin.time.Clock
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
private const val BASIC_CHALLENGE = "Basic realm=\"messenger\", charset=\"UTF-8\""
class AuthenticationControllerTest {
@Test
fun `valid Basic credentials open a session`() = runApp { client ->
val user = client.createUser("alice")
val response = client.post("/api/v1/auth/sessions") {
basicAuth(user.username, TEST_PASSWORD)
}
assertEquals(HttpStatusCode.Created, response.status)
val session = response.body<SessionResponse>()
assertEquals("Bearer", session.tokenType)
assertEquals(user, session.user)
assertTrue(session.token.length >= 43, "token must carry at least 256 bits")
assertTrue(session.expiresAt > Clock.System.now() + 59.minutes)
}
@Test
fun `each login issues a different token`() = runApp { client ->
val user = client.createUser("alice")
val first = client.post("/api/v1/auth/sessions") { basicAuth(user.username, TEST_PASSWORD) }
val second = client.post("/api/v1/auth/sessions") { basicAuth(user.username, TEST_PASSWORD) }
assertNotEquals(first.body<SessionResponse>().token, second.body<SessionResponse>().token)
}
@Test
fun `password containing a colon and non-ASCII characters works`() = runApp { client ->
val password = "пароль:с-двоеточием"
val user = client.createUser("colon", password = password)
val response = client.post("/api/v1/auth/sessions") {
basicAuth(user.username, password)
}
assertEquals(HttpStatusCode.Created, response.status)
}
@Test
fun `wrong password and unknown user get the same 401`() = runApp { client ->
val user = client.createUser("alice")
val wrongPassword = client.post("/api/v1/auth/sessions") {
basicAuth(user.username, "wrong-password-123")
}
val unknownUser = client.post("/api/v1/auth/sessions") {
basicAuth("nobody_${user.username}".take(32), TEST_PASSWORD)
}
for (response in listOf(wrongPassword, unknownUser)) {
assertEquals(HttpStatusCode.Unauthorized, response.status)
assertEquals(BASIC_CHALLENGE, response.headers[HttpHeaders.WWWAuthenticate])
assertEquals("unauthorized", response.body<ErrorBody>().error.code)
}
}
@Test
fun `missing or malformed Basic header returns 401`() = runApp { client ->
val missing = client.post("/api/v1/auth/sessions")
val malformed = client.post("/api/v1/auth/sessions") {
header(HttpHeaders.Authorization, "Basic !!!not-base64")
}
for (response in listOf(missing, malformed)) {
assertEquals(HttpStatusCode.Unauthorized, response.status)
assertEquals(BASIC_CHALLENGE, response.headers[HttpHeaders.WWWAuthenticate])
}
}
@Test
fun `Bearer token cannot open a session`() = runApp { client ->
val alice = client.register("alice")
val response = client.post("/api/v1/auth/sessions") {
auth(alice)
}
assertEquals(HttpStatusCode.Unauthorized, response.status)
}
@Test
fun `logout revokes only the current token`() = runApp { client ->
val alice = client.register("alice")
val secondSession = client.post("/api/v1/auth/sessions") {
basicAuth(alice.user.username, alice.password)
}.body<SessionResponse>()
val logout = client.delete("/api/v1/auth/sessions/current") { auth(alice) }
assertEquals(HttpStatusCode.NoContent, logout.status)
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
assertEquals(HttpStatusCode.Unauthorized, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
val other = client.get("/api/v1/users/me") { bearerAuth(secondSession.token) }
assertEquals(HttpStatusCode.OK, other.status)
}
@Test
fun `unknown token returns 401`() = runApp { client ->
val response = client.get("/api/v1/users/me") {
bearerAuth("this-token-was-never-issued-by-the-server-at-all")
}
assertEquals(HttpStatusCode.Unauthorized, response.status)
}
@Test
fun `session expires after SESSION_TTL_SECONDS`() = runApp(sessionTtlSeconds = 2) { client ->
val alice = client.register("alice")
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
delay(2.5.seconds)
val expired = client.get("/api/v1/users/me") { auth(alice) }
assertEquals(HttpStatusCode.Unauthorized, expired.status)
assertEquals("Bearer realm=\"messenger\"", expired.headers[HttpHeaders.WWWAuthenticate])
}
}

Some files were not shown because too many files have changed in this diff Show More